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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jatinpandey/Tweeter
|
tweeter/User.swift
|
1
|
2111
|
//
// User.swift
// tweeter
//
// Created by Jatin Pandey on 9/27/14.
// Copyright (c) 2014 Jatin Pandey. All rights reserved.
//
import UIKit
var _currentUser: User?
let currentUserKey = "kCurrent"
let userDidLoginNotification = "userDidLogin"
let userDidLogoutNotification = "userDidLogout"
class User: NSObject {
var name: String!
var screenName: String!
var profileImageUrl: String!
var tagline: String!
var dictionary: NSDictionary!
init(userDict: NSDictionary) {
self.dictionary = userDict
self.name = userDict["name"] as? NSString
self.screenName = userDict["screen_name"] as? NSString
self.profileImageUrl = userDict["profile_image_url"] as? NSString
self.tagline = userDict["description"] as? NSString
}
class var currentUser: User? {
get {
if _currentUser == nil {
var data = NSUserDefaults.standardUserDefaults().objectForKey(currentUserKey) as? NSData
if data != nil {
var dictionary = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSDictionary
_currentUser = User(userDict: dictionary)
}
}
return _currentUser
}
set(user) {
_currentUser = user
if _currentUser != nil {
var data = NSJSONSerialization.dataWithJSONObject(user!.dictionary, options: nil, error: nil)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: currentUserKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
else {
NSUserDefaults.standardUserDefaults().setObject(nil, forKey: currentUserKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
}
func logout() {
User.currentUser = nil
TwitterClient.sharedInstance.requestSerializer.removeAccessToken()
NSNotificationCenter.defaultCenter().postNotificationName(userDidLogoutNotification, object: nil)
}
}
|
mit
|
a0e11b141776072663f618e43888a283
| 32.507937 | 124 | 0.626243 | 5.186732 | false | false | false | false |
ludoded/ReceiptBot
|
ReceiptBot/Helper/Utils/RebotAttributedTextBuilder.swift
|
1
|
1185
|
//
// RebotAttributedTextBuilder.swift
// ReceiptBot
//
// Created by Haik Ampardjian on 4/20/17.
// Copyright © 2017 receiptbot. All rights reserved.
//
import UIKit
struct RebotAttributedTextBuilder {
static func buildPie(for value: Int, and label: String, with color: UIColor) -> NSAttributedString {
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = .byTruncatingTail
paragraph.alignment = .center
let valueStr = String(value)
let title: NSString = valueStr + "\n" + label as NSString
let attributed = NSMutableAttributedString(string: String(title), attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 18.0),
NSForegroundColorAttributeName : UIColor.darkGray,
NSParagraphStyleAttributeName : paragraph])
attributed.addAttributes([NSForegroundColorAttributeName : color, NSFontAttributeName : UIFont.systemFont(ofSize: 40.0)], range: title.range(of: valueStr))
return attributed
}
}
|
lgpl-3.0
|
3eab9ec2b2f7f2d0b0fbc724a4f31c86
| 44.538462 | 163 | 0.612331 | 5.747573 | false | false | false | false |
Jnosh/swift
|
test/SILGen/objc_imported_generic.swift
|
3
|
8526
|
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen %s | %FileCheck %s
// For integration testing, ensure we get through IRGen too.
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-ir -verify -DIRGEN_INTEGRATION_TEST %s
// REQUIRES: objc_interop
import objc_generics
func callInitializer() {
_ = GenericClass(thing: NSObject())
}
// CHECK-LABEL: sil shared [serializable] @_T0So12GenericClassCSQyAByxGGSQyxG5thing_tcfC
// CHECK: thick_to_objc_metatype {{%.*}} : $@thick GenericClass<T>.Type to $@objc_metatype GenericClass<T>.Type
public func genericMethodOnAnyObject(o: AnyObject, b: Bool) -> AnyObject {
return o.thing!()!
}
// CHECK-LABEL: sil @_T021objc_imported_generic0C17MethodOnAnyObject{{[_0-9a-zA-Z]*}}F
// CHECK: dynamic_method [volatile] {{%.*}} : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!1.foreign : <T where T : AnyObject> (GenericClass<T>) -> () -> T?, $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>
public func genericMethodOnAnyObjectChained(o: AnyObject, b: Bool) -> AnyObject? {
return o.thing?()
}
// CHECK-LABEL: sil @_T021objc_imported_generic0C24MethodOnAnyObjectChainedyXlSgyXl1o_Sb1btF
// CHECK: bb0([[ANY:%.*]] : $AnyObject, [[BOOL:%.*]] : $Bool):
// CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!1.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
// CHECK: } // end sil function '_T021objc_imported_generic0C24MethodOnAnyObjectChainedyXlSgyXl1o_Sb1btF'
public func genericSubscriptOnAnyObject(o: AnyObject, b: Bool) -> AnyObject? {
return o[0 as UInt16]
}
// CHECK-LABEL: sil @_T021objc_imported_generic0C20SubscriptOnAnyObjectyXlSgyXl1o_Sb1btF
// CHECK: bb0([[ANY:%.*]]
// CHCEK: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.subscript!getter.1.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) @pseudogeneric (UInt16, @opened([[TAG]]) AnyObject) -> @autoreleased AnyObject):
// CHECK: } // end sil function '_T021objc_imported_generic0C20SubscriptOnAnyObjectyXlSgyXl1o_Sb1btF'
public func genericPropertyOnAnyObject(o: AnyObject, b: Bool) -> AnyObject?? {
return o.propertyThing
}
// CHECK-LABEL: sil @_T021objc_imported_generic0C19PropertyOnAnyObjectyXlSgSgyXl1o_Sb1btF
// CHECK: bb0([[ANY:%.*]] : $AnyObject, [[BOOL:%.*]] : $Bool):
// CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.propertyThing!getter.1.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
// CHECK: } // end sil function '_T021objc_imported_generic0C19PropertyOnAnyObjectyXlSgSgyXl1o_Sb1btF'
public protocol ThingHolder {
associatedtype Thing
init!(thing: Thing!)
func thing() -> Thing?
func arrayOfThings() -> [Thing]
func setArrayOfThings(_: [Thing])
static func classThing() -> Thing?
var propertyThing: Thing? { get set }
var propertyArrayOfThings: [Thing]? { get set }
}
// TODO: Crashes in IRGen because the type metadata for `T` is not found in
// the witness thunk to satisfy the associated type requirement. This could be
// addressed by teaching IRGen to fulfill erased type parameters from protocol
// witness tables (rdar://problem/26602097).
#if !IRGEN_INTEGRATION_TEST
extension GenericClass: ThingHolder {}
#endif
public protocol Ansible: class {
associatedtype Anser: ThingHolder
}
public func genericBlockBridging<T: Ansible>(x: GenericClass<T>) {
let block = x.blockForPerformingOnThings()
x.performBlock(onThings: block)
}
// CHECK-LABEL: sil @_T021objc_imported_generic0C13BlockBridging{{[_0-9a-zA-Z]*}}F
// CHECK: [[BLOCK_TO_FUNC:%.*]] = function_ref @_T0xxIyBya_xxIxxo_RlzC21objc_imported_generic7AnsibleRzlTR
// CHECK: partial_apply [[BLOCK_TO_FUNC]]<T>
// CHECK: [[FUNC_TO_BLOCK:%.*]] = function_ref @_T0xxIxxo_xxIyBya_RlzC21objc_imported_generic7AnsibleRzlTR
// CHECK: init_block_storage_header {{.*}} invoke [[FUNC_TO_BLOCK]]<T>
// CHECK-LABEL: sil @_T021objc_imported_generic20arraysOfGenericParam{{[_0-9a-zA-Z]*}}F
public func arraysOfGenericParam<T: AnyObject>(y: Array<T>) {
// CHECK: function_ref {{@_T0So12GenericClassCSQyAByxGGSayxG13arrayOfThings.*}} : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@owned Array<τ_0_0>, @thick GenericClass<τ_0_0>.Type) -> @owned Optional<GenericClass<τ_0_0>>
let x = GenericClass<T>(arrayOfThings: y)!
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.setArrayOfThings!1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, GenericClass<τ_0_0>) -> ()
x.setArrayOfThings(y)
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!getter.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (GenericClass<τ_0_0>) -> @autoreleased Optional<NSArray>
_ = x.propertyArrayOfThings
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!setter.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (Optional<NSArray>, GenericClass<τ_0_0>) -> ()
x.propertyArrayOfThings = y
}
// CHECK-LABEL: sil private @_T021objc_imported_generic0C4FuncyxmRlzClFyycfU_ : $@convention(thin) <V where V : AnyObject> () -> () {
// CHECK: [[INIT:%.*]] = function_ref @_T0So12GenericClassCAByxGycfC : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@thick GenericClass<τ_0_0>.Type) -> @owned GenericClass<τ_0_0>
// CHECK: [[META:%.*]] = metatype $@thick GenericClass<V>.Type
// CHECK: apply [[INIT]]<V>([[META]])
// CHECK: return
func genericFunc<V: AnyObject>(_ v: V.Type) {
let _ = {
var _ = GenericClass<V>()
}
}
// CHECK-LABEL: sil hidden @_T021objc_imported_generic23configureWithoutOptionsyyF : $@convention(thin) () -> ()
// CHECK: [[NIL_FN:%.*]] = function_ref @_T0SqxSgyt10nilLiteral_tcfC : $@convention(method) <τ_0_0> (@thin Optional<τ_0_0>.Type) -> @out Optional<τ_0_0>
// CHECK: apply [[NIL_FN]]<[GenericOption : Any]>({{.*}})
// CHECK: return
func configureWithoutOptions() {
_ = GenericClass<NSObject>(options: nil)
}
// foreign to native thunk for init(options:), uses GenericOption : Hashable
// conformance
// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So12GenericClassCSQyAByxGGs10DictionaryVySC0A6OptionVypGSg7options_tcfcTO : $@convention(method) <T where T : AnyObject> (@owned Optional<Dictionary<GenericOption, Any>>, @owned GenericClass<T>) -> @owned Optional<GenericClass<T>>
// CHECK: [[FN:%.*]] = function_ref @_T0s10DictionaryV10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: apply [[FN]]<GenericOption, Any>({{.*}}) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: return
// This gets emitted down here for some reason
// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So12GenericClassCSQyAByxGGSayxG13arrayOfThings_tcfcTO
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.init!initializer.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, @owned GenericClass<τ_0_0>) -> @owned Optional<GenericClass<τ_0_0>>
// Make sure we emitted the witness table for the above conformance
// CHECK-LABEL: sil_witness_table shared [serialized] GenericOption: Hashable module objc_generics {
// CHECK: method #Hashable.hashValue!getter.1: {{.*}}: @_T0SC13GenericOptionVs8Hashable13objc_genericssACP9hashValueSifgTW
// CHECK: }
|
apache-2.0
|
41c2453a1db9eb345e99348baa5a2bb2
| 57.558621 | 284 | 0.693793 | 3.447422 | false | false | false | false |
VirgilSecurity/virgil-sdk-pfs-x
|
Source/Utils/AsyncOperation.swift
|
1
|
2403
|
//
// AsyncOperation.swift
// VirgilSDKPFS
//
// Created by Oleksandr Deundiak on 8/9/17.
// Copyright © 2017 VirgilSecurity. All rights reserved.
//
import Foundation
protocol FailableOperation: class {
var vsp_isFailed: Bool { get }
var vsp_error: Error? { get }
}
extension Operation: FailableOperation {
@objc open var vsp_isFailed: Bool { return false }
@objc open var vsp_error: Error? { return .none }
}
extension Operation {
func vsp_findDependency<T: Operation>() -> T? {
for dependency in self.dependencies {
if let typeDependency = dependency as? T {
return typeDependency
}
}
return .none
}
}
class AsyncOperation: Operation {
override var isAsynchronous: Bool { return true }
override var isExecuting: Bool { return self._executing }
private var _executing = false {
willSet {
self.willChangeValue(forKey: "isExecuting")
}
didSet {
self.didChangeValue(forKey: "isExecuting")
}
}
override var isFinished: Bool { return self._finished }
private var _finished = false {
willSet {
self.willChangeValue(forKey: "isFinished")
}
didSet {
self.didChangeValue(forKey: "isFinished")
}
}
override func start() {
guard !self.isCancelled else {
return
}
for dependency in self.dependencies {
guard !dependency.vsp_isFailed else {
self.fail(withError: dependency.vsp_error)
return
}
}
self._executing = true
self.execute()
}
func execute() {
// Execute your async task here.
}
func finish() {
// Notify the completion of async task and hence the completion of the operation
self._executing = false
self._finished = true
}
@objc override var vsp_isFailed: Bool { return self._failed }
private var _failed = false
func fail() {
self._failed = true
self.finish()
}
func fail(withError error: Error?) {
self._error = error
self.fail()
}
private var _error: Error?
@objc override var vsp_error: Error? { return self._error }
}
|
bsd-3-clause
|
77eeb6c6fc0a78e3208f37ddc2c77caa
| 22.782178 | 88 | 0.558701 | 4.673152 | false | false | false | false |
antocara/MVPPatternSwift
|
MVPSwift/Views/Controllers/LoginController.swift
|
1
|
2471
|
//
// LoginController.swift
// ARCHITEC_ARQ
//
// Created by Antonio Carabantes Millán on 13/5/16.
// Copyright © 2016 kibo. All rights reserved.
//
import UIKit
class LoginController: UIViewController {
@IBOutlet weak var editName: UITextField!
@IBOutlet weak var editPass: UITextField!
@IBOutlet weak var loading: UIActivityIndicatorView!
@IBOutlet weak var labelError: UILabel!
@IBAction func actionButtonLogin(sender: AnyObject) {
LoginPresenter(nameView: self).actionInitLogin(self.getUserFromForm())
}
@IBAction func actionButtonRegister(sender: AnyObject) {
LoginPresenter(nameView: self).actionInitRegister(self.getUserFromForm())
}
}
extension LoginController: LoginView{
func showLoading(){
self.loading.hidden = false;
self.loading.startAnimating();
}
func hideLoading(){
self.loading.hidden = true;
}
func openAlertController(message: String) {
self.cleanForm();
self.createAlertController(message);
}
func cleanForm(){
self.editName.text = "";
self.editPass.text = "";
}
func showErrorMessage(errorMessage: String){
self.labelError.hidden = false;
self.labelError.text = errorMessage;
}
func createAlertController(message: String){
let alertView = UIAlertController(title: "Congratulations", message: "Your credentials are corrects", preferredStyle: .Alert)
alertView.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
presentViewController(alertView, animated: true, completion: nil)
}
func getUserFromForm() -> User{
let user = User()
if let email = self.editName.text, let pass = self.editPass.text{
user.email = email
user.password = pass
}
return user
}
}
extension LoginController: UITextFieldDelegate{
func textFieldDidBeginEditing(textField: UITextField){
self.labelError.hidden = true;
}
//change to the next edit when press return keyboard key
func textFieldShouldReturn(textField: UITextField) -> Bool {
let nexTag = textField.tag + 1;
let nextResponder = textField.superview?.viewWithTag(nexTag);
if let nextResponder = nextResponder{
nextResponder.becomeFirstResponder();
}else{
textField.resignFirstResponder();
}
return false;
}
}
|
mit
|
0b8e3402c2ac50dbb5a34b25e007a515
| 23.205882 | 133 | 0.658971 | 4.658491 | false | false | false | false |
OatmealCode/Oatmeal
|
Example/Pods/Carlos/Carlos/PostProcess.swift
|
1
|
7906
|
import Foundation
import PiedPiper
infix operator ~>> { associativity left }
extension CacheLevel {
/**
Adds a post-processing step to the get results of this CacheLevel
As usual, if the transformation fails, the get request will also fail
- parameter transformer: The OneWayTransformer that will be applied to every successful result of the method get called on the cache level. The transformer has to return the same type of the input type, and the transformation won't be applied when setting values on the cache level.
- returns: A transformed CacheLevel that incorporates the post-processing step
*/
public func postProcess<A: OneWayTransformer where OutputType == A.TypeIn, A.TypeIn == A.TypeOut>(transformer: A) -> BasicCache<KeyType, OutputType> {
return BasicCache(
getClosure: { key in
self.get(key).mutate(transformer)
},
setClosure: self.set,
clearClosure: self.clear,
memoryClosure: self.onMemoryWarning
)
}
/**
Adds a post-processing step to the get results of this CacheLevel
As usual, if the transformation fails, the get request will also fail
- parameter transformerClosure: The transformation closure that will be applied to every successful result of the method get called on the cache level. The closure has to return the same type of the input type, and the transformation won't be applied when setting values on the cache level.
- returns: A transformed CacheLevel that incorporates the post-processing step
*/
@available(*, deprecated=0.7)
public func postProcess(transformerClosure: OutputType -> Future<OutputType>) -> BasicCache<KeyType, OutputType> {
return self.postProcess(wrapClosureIntoOneWayTransformer(transformerClosure))
}
}
/**
Adds a post-processing step to the get results of a fetch closure
As usual, if the transformation fails, the get request will also fail
- parameter fetchClosure: The fetch closure you want to decorate
- parameter transformer: The OneWayTransformer that will be applied to every successful result of the fetch closure. The transformer has to return the same type of the input type
- returns: A CacheLevel that incorporates the post-processing step
*/
@available(*, deprecated=0.5)
public func postProcess<A, B: OneWayTransformer where B.TypeIn == B.TypeOut>(fetchClosure: (key: A) -> Future<B.TypeIn>, transformer: B) -> BasicCache<A, B.TypeOut> {
return wrapClosureIntoFetcher(fetchClosure).postProcess(transformer)
}
/**
Adds a post-processing step to the get results of a fetch closure
As usual, if the transformation fails, the get request will also fail
- parameter fetchClosure: The fetch closure you want to decorate
- parameter transformerClosure: The transformation closure that will be applied to every successful result of the fetch closure. The transformation closure has to return the same type of the input type
- returns: A CacheLevel that incorporates the post-processing step
*/
@available(*, deprecated=0.5)
public func postProcess<A, B>(fetchClosure: (key: A) -> Future<B>, transformerClosure: B -> Future<B>) -> BasicCache<A, B> {
return wrapClosureIntoFetcher(fetchClosure).postProcess(wrapClosureIntoOneWayTransformer(transformerClosure))
}
/**
Adds a post-processing step to the get results of a CacheLevel
As usual, if the transformation fails, the get request will also fail
- parameter cache: The CacheLevel you want to decorate
- parameter transformer: The OneWayTransformer that will be applied to every successful result of the CacheLevel. The transformer has to return the same type of the input type, and the transformation won't be applied when setting values on the cache level.
- returns: A transformed CacheLevel that incorporates the post-processing step
*/
@available(*, deprecated=0.5)
public func postProcess<A: CacheLevel, B: OneWayTransformer where A.OutputType == B.TypeIn, B.TypeIn == B.TypeOut>(cache: A, transformer: B) -> BasicCache<A.KeyType, A.OutputType> {
return cache.postProcess(transformer)
}
/**
Adds a post-processing step to the get results of a CacheLevel
As usual, if the transformation fails, the get request will also fail
- parameter cache: The CacheLevel you want to decorate
- parameter transformerClosure: The transformation closure that will be applied to every successful result of the method get called on the cache level. The closure has to return the same type of the input type, and the transformation won't be applied when setting values on the cache level.
- returns: A transformed CacheLevel that incorporates the post-processing step
*/
@available(*, deprecated=0.5)
public func postProcess<A: CacheLevel>(cache: A, transformerClosure: A.OutputType -> Future<A.OutputType>) -> BasicCache<A.KeyType, A.OutputType> {
return cache.postProcess(wrapClosureIntoOneWayTransformer(transformerClosure))
}
/**
Adds a post-processing step to the get results of a fetch closure
As usual, if the transformation fails, the get request will also fail
- parameter fetchClosure: The fetch closure you want to decorate
- parameter transformer: The OneWayTransformer that will be applied to every successful result of the fetch closure. The transformer has to return the same type of the input type
- returns: A CacheLevel that incorporates the post-processing step
*/
@available(*, deprecated=0.7)
public func ~>><A, B: OneWayTransformer where B.TypeIn == B.TypeOut>(fetchClosure: (key: A) -> Future<B.TypeIn>, transformer: B) -> BasicCache<A, B.TypeOut> {
return wrapClosureIntoFetcher(fetchClosure).postProcess(transformer)
}
/**
Adds a post-processing step to the get results of a fetch closure
As usual, if the transformation fails, the get request will also fail
- parameter fetchClosure: The fetch closure you want to decorate
- parameter transformerClosure: The transformation closure that will be applied to every successful result of the fetch closure. The transformation closure has to return the same type of the input type
- returns: A CacheLevel that incorporates the post-processing step
*/
@available(*, deprecated=0.7)
public func ~>><A, B>(fetchClosure: (key: A) -> Future<B>, transformerClosure: B -> Future<B>) -> BasicCache<A, B> {
return wrapClosureIntoFetcher(fetchClosure).postProcess(wrapClosureIntoOneWayTransformer(transformerClosure))
}
/**
Adds a post-processing step to the get results of a CacheLevel
As usual, if the transformation fails, the get request will also fail
- parameter cache: The CacheLevel you want to decorate
- parameter transformer: The OneWayTransformer that will be applied to every successful result of the CacheLevel. The transformer has to return the same type of the input type, and the transformation won't be applied when setting values on the cache level.
- returns: A transformed CacheLevel that incorporates the post-processing step
*/
public func ~>><A: CacheLevel, B: OneWayTransformer where A.OutputType == B.TypeIn, B.TypeIn == B.TypeOut>(cache: A, transformer: B) -> BasicCache<A.KeyType, A.OutputType> {
return cache.postProcess(transformer)
}
/**
Adds a post-processing step to the get results of a CacheLevel
As usual, if the transformation fails, the get request will also fail
- parameter cache: The CacheLevel you want to decorate
- parameter transformerClosure: The transformation closure that will be applied to every successful result of the method get called on the cache level. The closure has to return the same type of the input type, and the transformation won't be applied when setting values on the cache level.
- returns: A transformed CacheLevel that incorporates the post-processing step
*/
@available(*, deprecated=0.7)
public func ~>><A: CacheLevel>(cache: A, transformerClosure: A.OutputType -> Future<A.OutputType>) -> BasicCache<A.KeyType, A.OutputType> {
return cache.postProcess(wrapClosureIntoOneWayTransformer(transformerClosure))
}
|
mit
|
ecc665ea81bc9b86dab185d1e8bad683
| 48.41875 | 292 | 0.775234 | 4.451577 | false | false | false | false |
cardstream/iOS-SDK
|
cardstream-ios-sdk/CryptoSwift-0.7.2/Tests/CryptoSwiftTests/ChaCha20Tests.swift
|
1
|
8532
|
//
// CipherChaCha20Tests.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 27/12/14.
// Copyright (C) 2014-2017 Krzyzanowski. All rights reserved.
//
import XCTest
import Foundation
@testable import CryptoSwift
final class ChaCha20Tests: XCTestCase {
func testChaCha20() {
let keys: [Array<UInt8>] = [
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01],
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f],
]
let ivs: [Array<UInt8>] = [
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01],
[0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07],
]
let expectedHexes = [
"76B8E0ADA0F13D90405D6AE55386BD28BDD219B8A08DED1AA836EFCC8B770DC7DA41597C5157488D7724E03FB8D84A376A43B8F41518A11CC387B669B2EE6586",
"4540F05A9F1FB296D7736E7B208E3C96EB4FE1834688D2604F450952ED432D41BBE2A0B6EA7566D2A5D1E7E20D42AF2C53D792B1C43FEA817E9AD275AE546963",
"DE9CBA7BF3D69EF5E786DC63973F653A0B49E015ADBFF7134FCB7DF137821031E85A050278A7084527214F73EFC7FA5B5277062EB7A0433E445F41E3",
"EF3FDFD6C61578FBF5CF35BD3DD33B8009631634D21E42AC33960BD138E50D32111E4CAF237EE53CA8AD6426194A88545DDC497A0B466E7D6BBDB0041B2F586B",
"F798A189F195E66982105FFB640BB7757F579DA31602FC93EC01AC56F85AC3C134A4547B733B46413042C9440049176905D3BE59EA1C53F15916155C2BE8241A38008B9A26BC35941E2444177C8ADE6689DE95264986D95889FB60E84629C9BD9A5ACB1CC118BE563EB9B3A4A472F82E09A7E778492B562EF7130E88DFE031C79DB9D4F7C7A899151B9A475032B63FC385245FE054E3DD5A97A5F576FE064025D3CE042C566AB2C507B138DB853E3D6959660996546CC9C4A6EAFDC777C040D70EAF46F76DAD3979E5C5360C3317166A1C894C94A371876A94DF7628FE4EAAF2CCB27D5AAAE0AD7AD0F9D4B6AD3B54098746D4524D38407A6DEB3AB78FAB78C9",
]
for idx in 0..<keys.count {
let expectedHex = expectedHexes[idx]
let message = Array<UInt8>(repeating: 0, count: (expectedHex.characters.count / 2))
do {
let encrypted = try message.encrypt(cipher: ChaCha20(key: keys[idx], iv: ivs[idx]))
let decrypted = try encrypted.decrypt(cipher: ChaCha20(key: keys[idx], iv: ivs[idx]))
XCTAssertEqual(message, decrypted, "ChaCha20 decryption failed")
XCTAssertEqual(encrypted, Array<UInt8>(hex: expectedHex))
} catch CipherError.encrypt {
XCTAssert(false, "Encryption failed")
} catch CipherError.decrypt {
XCTAssert(false, "Decryption failed")
} catch {
XCTAssert(false, "Failed")
}
}
}
func testCore() {
let key: Array<UInt8> = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
var counter: Array<UInt8> = [1, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 74, 0, 0, 0, 0]
let input = Array<UInt8>.init(repeating: 0, count: 129)
let chacha = try! ChaCha20(key: key, iv: Array(key[4..<16]))
let result = chacha.process(bytes: input, counter: &counter, key: key)
XCTAssertEqual(result.toHexString(), "10f1e7e4d13b5915500fdd1fa32071c4c7d1f4c733c068030422aa9ac3d46c4ed2826446079faa0914c2d705d98b02a2b5129cd1de164eb9cbd083e8a2503c4e0a88837739d7bf4ef8ccacb0ea2bb9d69d56c394aa351dfda5bf459f0a2e9fe8e721f89255f9c486bf21679c683d4f9c5cf2fa27865526005b06ca374c86af3bdc")
}
func testVector1Py() {
let key: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
let iv: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
let expected: Array<UInt8> = [0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90, 0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28, 0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a, 0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7, 0xda, 0x41, 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d, 0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37, 0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, 0xa1, 0x1c, 0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86]
let message = Array<UInt8>(repeating: 0, count: expected.count)
do {
let encrypted = try ChaCha20(key: key, iv: iv).encrypt(message)
XCTAssertEqual(encrypted, expected, "Ciphertext failed")
} catch {
XCTFail()
}
}
func testChaCha20EncryptPartial() {
let key: Array<UInt8> = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f]
let iv: Array<UInt8> = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]
let expectedHex = "F798A189F195E66982105FFB640BB7757F579DA31602FC93EC01AC56F85AC3C134A4547B733B46413042C9440049176905D3BE59EA1C53F15916155C2BE8241A38008B9A26BC35941E2444177C8ADE6689DE95264986D95889FB60E84629C9BD9A5ACB1CC118BE563EB9B3A4A472F82E09A7E778492B562EF7130E88DFE031C79DB9D4F7C7A899151B9A475032B63FC385245FE054E3DD5A97A5F576FE064025D3CE042C566AB2C507B138DB853E3D6959660996546CC9C4A6EAFDC777C040D70EAF46F76DAD3979E5C5360C3317166A1C894C94A371876A94DF7628FE4EAAF2CCB27D5AAAE0AD7AD0F9D4B6AD3B54098746D4524D38407A6DEB3AB78FAB78C9"
let plaintext: Array<UInt8> = Array<UInt8>(repeating: 0, count: (expectedHex.characters.count / 2))
do {
let cipher = try ChaCha20(key: key, iv: iv)
var ciphertext = Array<UInt8>()
var encryptor = cipher.makeEncryptor()
ciphertext += try encryptor.update(withBytes: Array(plaintext[0..<8]))
ciphertext += try encryptor.update(withBytes: Array(plaintext[8..<16]))
ciphertext += try encryptor.update(withBytes: Array(plaintext[16..<80]))
ciphertext += try encryptor.update(withBytes: Array(plaintext[80..<256]))
ciphertext += try encryptor.finish()
XCTAssertEqual(Array<UInt8>(hex: expectedHex), ciphertext)
} catch {
XCTFail()
}
}
}
#if !CI
extension ChaCha20Tests {
func testChaCha20Performance() {
let key: Array<UInt8> = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f]
let iv: Array<UInt8> = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]
let message = Array<UInt8>(repeating: 7, count: 1024)
measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: true, for: { () -> Void in
do {
_ = try ChaCha20(key: key, iv: iv).encrypt(message)
} catch {
XCTFail()
}
self.stopMeasuring()
})
}
}
#endif
extension ChaCha20Tests {
static func allTests() -> [(String, (ChaCha20Tests) -> () -> Void)] {
var tests = [
("testChaCha20", testChaCha20),
("testCore", testCore),
("testVector1Py", testVector1Py),
("testChaCha20EncryptPartial", testChaCha20EncryptPartial),
]
#if !CI
tests += [("testChaCha20Performance", testChaCha20Performance)]
#endif
return tests
}
}
|
gpl-3.0
|
c5fc7c1d091b4207537bfaeae59dbe43
| 59.942857 | 540 | 0.663619 | 2.314076 | false | true | false | false |
wikimedia/wikipedia-ios
|
Wikipedia/Code/ShareViewController.swift
|
1
|
6387
|
import UIKit
@objc(WMFShareViewController)
class ShareViewController: UIViewController, Themeable {
@IBOutlet weak var cancelButton: UIButton!
let text: String
let articleTitle: String
let articleURL: URL
let articleImageURL: URL?
let articleDescription: String?
let loadGroup: WMFTaskGroup
var theme: Theme
var image: UIImage?
var imageLicense: MWKLicense?
// SINGLETONTODO
let infoFetcher = MWKImageInfoFetcher(dataStore: MWKDataStore.shared())
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var busyView: UIView!
@IBOutlet weak var busyLabel: UILabel!
@IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewVerticallyCenteredConstraint: NSLayoutConstraint!
@objc required public init?(text: String, article: WMFArticle, theme: Theme) {
guard let articleURL = article.url else {
return nil
}
self.text = text
self.articleTitle = article.displayTitle ?? ""
self.articleDescription = article.capitalizedWikidataDescription
self.articleURL = articleURL
self.articleImageURL = article.imageURL(forWidth: 640)
self.theme = theme
self.loadGroup = WMFTaskGroup()
super.init(nibName: "ShareViewController", bundle: nil)
modalPresentationStyle = .overCurrentContext
loadImage()
}
required convenience init?(coder aDecoder: NSCoder) {
self.init(text: "", article: WMFArticle(), theme: Theme.standard)
}
override func viewDidLoad() {
super.viewDidLoad()
busyLabel.text = WMFLocalizedString("share-building", value: "Building Share-a-fact card…", comment: "Shown while Share-a-fact card is being constructed")
cancelButton.setTitle(WMFLocalizedString("cancel", value: "Cancel", comment: "Cancel"), for: .normal)
apply(theme: theme)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.loadGroup.waitInBackground {
let image = self.createShareAFactCard()
self.showActivityViewController(with: image)
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { (context) in
self.imageViewTopConstraint.isActive = true
self.imageViewVerticallyCenteredConstraint.isActive = false
if let presentedActivityVC = self.presentedViewController as? UIActivityViewController {
presentedActivityVC.popoverPresentationController?.sourceRect = self.imageView.frame
}
}, completion: nil)
}
func loadImage() {
if let imageURL = self.articleImageURL, let imageName = WMFParseUnescapedNormalizedImageNameFromSourceURL(imageURL), let siteURL = articleURL.wmf_site {
loadGroup.enter()
let filename = "File:" + imageName
infoFetcher.fetchGalleryInfo(forImage: filename, fromSiteURL: siteURL, failure: { (error) in
self.loadGroup.leave()
}, success: { (info) in
defer {
self.loadGroup.leave()
}
guard let imageInfo = info as? MWKImageInfo else {
return
}
self.imageLicense = imageInfo.license
})
loadGroup.enter()
MWKDataStore.shared().cacheController.imageCache.fetchImage(withURL: imageURL, failure: { (fail) in
self.loadGroup.leave()
}) { (download) in
self.image = download.image.staticImage
self.loadGroup.leave()
}
}
}
func createShareAFactCard() -> UIImage? {
let cardController = ShareAFactViewController(nibName: "ShareAFactViewController", bundle: nil)
let cardView = cardController.view
cardController.update(with: articleURL, articleTitle: articleTitle, text: text, image: image, imageLicense: imageLicense)
return cardView?.wmf_snapshotImage()
}
func showActivityViewController(with shareAFactImage: UIImage?) {
cancelButton.isEnabled = false
imageView.image = shareAFactImage
UIView.animate(withDuration: 0.3) {
self.imageView.alpha = 1
self.busyView.alpha = 0
self.cancelButton.alpha = 0
}
let itemProvider = ShareAFactActivityTextItemProvider(text: text, articleTitle: articleTitle, articleURL: articleURL)
var activityItems = [Any]()
if let image = shareAFactImage {
activityItems.append(ShareAFactActivityImageItemProvider(image: image))
}
activityItems.append(itemProvider)
let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
activityVC.excludedActivityTypes = [.addToReadingList]
activityVC.popoverPresentationController?.sourceView = view
activityVC.popoverPresentationController?.permittedArrowDirections = .up
activityVC.completionWithItemsHandler = { (activityType, completed, returnedItems, error) in
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(750), execute: {
UIView.animate(withDuration: 0.3, animations: {
self.imageViewTopConstraint.isActive = true
self.imageViewVerticallyCenteredConstraint.isActive = false
self.view.layoutIfNeeded()
}, completion: { _ in
activityVC.popoverPresentationController?.sourceRect = self.imageView.frame
self.present(activityVC, animated: true, completion: nil)})
})
}
@IBAction func cancel(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
busyLabel.textColor = theme.colors.primaryText
view.backgroundColor = theme.colors.paperBackground.withAlphaComponent(0.9)
}
}
|
mit
|
9b1c3d6bc641c6551e24e04210938939
| 41.284768 | 162 | 0.651684 | 5.2422 | false | false | false | false |
open-telemetry/opentelemetry-swift
|
Tests/OpenTelemetrySdkTests/Metrics/CounterTests.swift
|
1
|
11001
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
@testable import OpenTelemetryApi
@testable import OpenTelemetrySdk
import XCTest
final class CounterTests: XCTestCase {
public func testIntCounterBoundInstrumentsStatusUpdatedCorrectlySingleThread() {
let testProcessor = TestMetricProcessor()
let meter = MeterProviderSdk(metricProcessor: testProcessor, metricExporter: NoopMetricExporter()).get(instrumentationName: "scope1") as! MeterSdk
let testCounter = meter.createIntCounter(name: "testCounter").internalCounter as! CounterMetricSdk<Int>
let labels1 = ["dim1": "value1"]
let ls1 = meter.getLabelSet(labels: labels1)
let labels2 = ["dim1": "value2"]
let ls2 = meter.getLabelSet(labels: labels2)
let labels3 = ["dim1": "value3"]
let ls3 = meter.getLabelSet(labels: labels3)
// We have ls1, ls2, ls3
// ls1 and ls3 are not bound so they should removed when no usage for a Collect cycle.
// ls2 is bound by user.
testCounter.add( value: 100, labelset: ls1)
testCounter.add( value: 10, labelset: ls1)
// initial status for temp bound instruments are UpdatePending.
XCTAssertEqual(RecordStatus.updatePending, testCounter.boundInstruments[ls1]?.status)
let boundCounterLabel2 = testCounter.bind(labelset: ls2)
boundCounterLabel2.add( value: 200)
// initial/forever status for user bound instruments are Bound.
XCTAssertEqual(RecordStatus.bound, testCounter.boundInstruments[ls2]?.status)
testCounter.add( value: 200, labelset: ls3)
testCounter.add( value: 10, labelset: ls3)
// initial status for temp bound instruments are UpdatePending.
XCTAssertEqual(RecordStatus.updatePending, testCounter.boundInstruments[ls3]?.status)
// This collect should mark ls1, ls3 as noPendingUpdate, leave ls2 untouched.
meter.collect()
// Validate collect() has marked records correctly.
XCTAssertEqual(RecordStatus.noPendingUpdate, testCounter.boundInstruments[ls1]?.status)
XCTAssertEqual(RecordStatus.noPendingUpdate, testCounter.boundInstruments[ls3]?.status)
XCTAssertEqual(RecordStatus.bound, testCounter.boundInstruments[ls2]?.status)
// Use ls1 again, so that it'll be promoted to UpdatePending
testCounter.add( value: 100, labelset: ls1)
// This collect should mark ls1 as noPendingUpdate, leave ls2 untouched.
// And ls3 as candidateForRemoval, as it was not used since last Collect
meter.collect()
// Validate collect() has marked records correctly.
XCTAssertEqual(RecordStatus.noPendingUpdate, testCounter.boundInstruments[ls1]?.status)
XCTAssertEqual(RecordStatus.candidateForRemoval, testCounter.boundInstruments[ls3]?.status)
XCTAssertEqual(RecordStatus.bound, testCounter.boundInstruments[ls2]?.status)
// This collect should mark
// ls1 as candidateForRemoval as it was not used since last Collect
// leave ls2 untouched.
// ls3 should be physically removed as it remained candidateForRemoval during an entire Collect cycle.
meter.collect()
XCTAssertEqual(RecordStatus.candidateForRemoval, testCounter.boundInstruments[ls1]?.status)
XCTAssertEqual(RecordStatus.bound, testCounter.boundInstruments[ls2]?.status)
XCTAssertNil(testCounter.boundInstruments[ls3])
}
public func testDoubleCounterBoundInstrumentsStatusUpdatedCorrectlySingleThread() {
let testProcessor = TestMetricProcessor()
let meter = MeterProviderSdk(metricProcessor: testProcessor, metricExporter: NoopMetricExporter()).get(instrumentationName: "scope1") as! MeterSdk
let testCounter = meter.createDoubleCounter(name: "testCounter").internalCounter as! CounterMetricSdk<Double>
let labels1 = ["dim1": "value1"]
let ls1 = meter.getLabelSet(labels: labels1)
let labels2 = ["dim1": "value2"]
let ls2 = meter.getLabelSet(labels: labels2)
let labels3 = ["dim1": "value3"]
let ls3 = meter.getLabelSet(labels: labels3)
// We have ls1, ls2, ls3
// ls1 and ls3 are not bound so they should removed when no usage for a Collect cycle.
// ls2 is bound by user.
testCounter.add( value: 100.0, labelset: ls1)
testCounter.add( value: 10.0, labelset: ls1)
// initial status for temp bound instruments are UpdatePending.
XCTAssertEqual(RecordStatus.updatePending, testCounter.boundInstruments[ls1]?.status)
let boundCounterLabel2 = testCounter.bind(labelset: ls2)
boundCounterLabel2.add( value: 200.0)
// initial/forever status for user bound instruments are Bound.
XCTAssertEqual(RecordStatus.bound, testCounter.boundInstruments[ls2]?.status)
testCounter.add( value: 200.0, labelset: ls3)
testCounter.add( value: 10.0, labelset: ls3)
// initial status for temp bound instruments are UpdatePending.
XCTAssertEqual(RecordStatus.updatePending, testCounter.boundInstruments[ls3]?.status)
// This collect should mark ls1, ls3 as noPendingUpdate, leave ls2 untouched.
meter.collect()
// Validate collect() has marked records correctly.
XCTAssertEqual(RecordStatus.noPendingUpdate, testCounter.boundInstruments[ls1]?.status)
XCTAssertEqual(RecordStatus.noPendingUpdate, testCounter.boundInstruments[ls3]?.status)
XCTAssertEqual(RecordStatus.bound, testCounter.boundInstruments[ls2]?.status)
// Use ls1 again, so that it'll be promoted to UpdatePending
testCounter.add( value: 100.0, labelset: ls1)
// This collect should mark ls1 as noPendingUpdate, leave ls2 untouched.
// And ls3 as candidateForRemoval, as it was not used since last Collect
meter.collect()
// Validate collect() has marked records correctly.
XCTAssertEqual(RecordStatus.noPendingUpdate, testCounter.boundInstruments[ls1]?.status)
XCTAssertEqual(RecordStatus.candidateForRemoval, testCounter.boundInstruments[ls3]?.status)
XCTAssertEqual(RecordStatus.bound, testCounter.boundInstruments[ls2]?.status)
// This collect should mark
// ls1 as candidateForRemoval as it was not used since last Collect
// leave ls2 untouched.
// ls3 should be physically removed as it remained candidateForRemoval during an entire Collect cycle.
meter.collect()
XCTAssertEqual(RecordStatus.candidateForRemoval, testCounter.boundInstruments[ls1]?.status)
XCTAssertEqual(RecordStatus.bound, testCounter.boundInstruments[ls2]?.status)
XCTAssertNil(testCounter.boundInstruments[ls3])
}
public func testIntCounterBoundInstrumentsStatusUpdatedCorrectlyMultiThread() {
let testProcessor = TestMetricProcessor()
let meter = MeterProviderSdk(metricProcessor: testProcessor, metricExporter: NoopMetricExporter()).get(instrumentationName: "scope1") as! MeterSdk
let testCounter = meter.createIntCounter(name: "testCounter").internalCounter as! CounterMetricSdk<Int>
let labels1 = ["dim1": "value1"]
let ls1 = meter.getLabelSet(labels: labels1)
// Call metric update with ls1 so that ls1 wont be brand new labelset when doing multi-thread test.
testCounter.add( value: 100, labelset: ls1)
testCounter.add( value: 10, labelset: ls1)
// This collect should mark ls1 NoPendingUpdate
meter.collect()
// Validate collect() has marked records correctly.
XCTAssertEqual(RecordStatus.noPendingUpdate, testCounter.boundInstruments[ls1]?.status)
// Another collect(). This collect should mark ls1 as CandidateForRemoval.
meter.collect()
XCTAssertEqual(RecordStatus.candidateForRemoval, testCounter.boundInstruments[ls1]?.status)
let mygroup = DispatchGroup()
DispatchQueue.global().async(group: mygroup) {
for _ in 0 ..< 5 {
meter.collect()
}
}
DispatchQueue.global().async(group: mygroup) {
for _ in 0 ..< 5 {
testCounter.add( value: 100, labelset: ls1)
}
}
mygroup.wait()
// Validate that the exported record doesn't miss any update.
// The Add(100) value must have already been exported, or must be exported in the next Collect().
meter.collect()
var sum = 0
testProcessor.metrics.forEach {
$0.data.forEach {
sum += ($0 as! SumData<Int>).sum
}
}
// 610 = 110 from initial update, 500 from the multi-thread test case.
XCTAssertEqual(610, sum)
}
public func testDoubleCounterBoundInstrumentsStatusUpdatedCorrectlyMultiThread() {
// let testProcessor = TestMetricProcessor()
// let meterSharedState = MeterSharedState(metricProcessor: testProcessor)
// let meter = MeterProviderSdk(meterSharedState: meterSharedState).get(instrumentationName: "scope1") as! MeterSdk
// let testCounter = meter.createDoubleCounter(name: "testCounter").internalCounter as! CounterMetricSdk<Double>
//
// let labels1 = ["dim1": "value1"]
// let ls1 = meter.getLabelSet(labels: labels1)
//
// // Call metric update with ls1 so that ls1 wont be brand new labelset when doing multi-thread test.
// testCounter.add( value: 100.0, labelset: ls1)
// testCounter.add( value: 10.0, labelset: ls1)
//
// // This collect should mark ls1 NoPendingUpdate
// meter.collect()
//
// // Validate collect() has marked records correctly.
// XCTAssertEqual(RecordStatus.noPendingUpdate, testCounter.boundInstruments[ls1]?.status)
//
// // Another collect(). This collect should mark ls1 as CandidateForRemoval.
// meter.collect()
// XCTAssertEqual(RecordStatus.candidateForRemoval, testCounter.boundInstruments[ls1]?.status)
//
// let mygroup = DispatchGroup()
// DispatchQueue.global().async(group: mygroup) {
// for _ in 0 ..< 5 {
// meter.collect()
// }
// }
// DispatchQueue.global().async(group: mygroup) {
// for _ in 0 ..< 5 {
// testCounter.add( value: 100.0, labelset: ls1)
// }
// }
// mygroup.wait()
//
// // Validate that the exported record doesn't miss any update.
// // The Add(100) value must have already been exported, or must be exported in the next Collect().
// meter.collect()
// var sum = 0.0
// testProcessor.metrics.forEach {
// $0.data.forEach {
// sum += ($0 as! SumData<Double>).sum
// }
// }
// // 610 = 110 from initial update, 500 from the multi-thread test case.
// XCTAssertEqual(610.0, sum)
}
}
|
apache-2.0
|
897763f61c21f18365827a23cdaf9e48
| 47.25 | 154 | 0.677393 | 4.457455 | false | true | false | false |
Elm-Tree-Island/Shower
|
Shower/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoa/AppKit/NSButton.swift
|
4
|
1452
|
import ReactiveSwift
import enum Result.NoError
import AppKit
extension Reactive where Base: NSButton {
internal var associatedAction: Atomic<(action: CocoaAction<Base>, disposable: CompositeDisposable)?> {
return associatedValue { _ in Atomic(nil) }
}
public var pressed: CocoaAction<Base>? {
get {
return associatedAction.value?.action
}
nonmutating set {
associatedAction
.modify { action in
action?.disposable.dispose()
action = newValue.map { action in
let disposable = CompositeDisposable()
disposable += isEnabled <~ action.isEnabled
disposable += proxy.invoked.observeValues(action.execute)
return (action, disposable)
}
}
}
}
#if swift(>=4.0)
/// A signal of integer states (On, Off, Mixed), emitted by the button.
public var states: Signal<NSControl.StateValue, NoError> {
return proxy.invoked.map { $0.state }
}
/// Sets the button's state
public var state: BindingTarget<NSControl.StateValue> {
return makeBindingTarget { $0.state = $1 }
}
#else
/// A signal of integer states (On, Off, Mixed), emitted by the button.
public var states: Signal<Int, NoError> {
return proxy.invoked.map { $0.state }
}
/// Sets the button's state
public var state: BindingTarget<Int> {
return makeBindingTarget { $0.state = $1 }
}
#endif
/// Sets the button's image
public var image: BindingTarget<NSImage?> {
return makeBindingTarget { $0.image = $1 }
}
}
|
gpl-3.0
|
a5c786603837b52d7b21adf1d588e953
| 24.928571 | 103 | 0.692149 | 3.685279 | false | false | false | false |
elefantel/TravelWish
|
TravelWish/AppDelegate.swift
|
1
|
6601
|
//
// AppDelegate.swift
// TravelWish
//
// Created by Mpendulo Ndlovu on 2016/04/07.
// Copyright © 2016 Elefantel. All rights reserved.
//
import UIKit
import CoreData
func UIColorFromRGB(rgbValue : Int)->UIColor {
return (UIColor(colorLiteralRed: ((Float)((rgbValue & 0xFF0000) >> 16))/255.0, green: ((Float)((rgbValue & 0xFF00) >> 8))/255.0, blue: ((Float)(rgbValue & 0xFF))/255.0, alpha: 1.0))
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let navigationBarColor : UIColor = UIColorFromRGB(0xD5E5EB)
let tintColor : UIColor = UIColorFromRGB(0x77C6E0)
UINavigationBar.appearance().barTintColor = navigationBarColor
UINavigationBar.appearance().tintColor = tintColor
//UINavigationBar.appearance().translucent = YES
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "elefantel.TravelWish" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("TravelWish", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
|
mit
|
648e0e283e7038a9a3d4f74fcdc9428c
| 54 | 291 | 0.715303 | 5.694564 | false | false | false | false |
SuPair/firefox-ios
|
Storage/SyncQueue.swift
|
2
|
2007
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
import Deferred
import SwiftyJSON
public struct SyncCommand: Equatable {
public let value: String
public var commandID: Int?
public var clientGUID: GUID?
let version: String?
public init(value: String) {
self.value = value
self.version = nil
self.commandID = nil
self.clientGUID = nil
}
public init(id: Int, value: String) {
self.value = value
self.version = nil
self.commandID = id
self.clientGUID = nil
}
public init(id: Int?, value: String, clientGUID: GUID?) {
self.value = value
self.version = nil
self.clientGUID = clientGUID
self.commandID = id
}
/**
* Sent displayURI commands include the sender client GUID.
*/
public static func displayURIFromShareItem(_ shareItem: ShareItem, asClient sender: GUID) -> SyncCommand {
let jsonObj: [String: Any] = [
"command": "displayURI",
"args": [shareItem.url, sender, shareItem.title ?? ""]
]
return SyncCommand(value: JSON(jsonObj).stringify()!)
}
public func withClientGUID(_ clientGUID: String?) -> SyncCommand {
return SyncCommand(id: self.commandID, value: self.value, clientGUID: clientGUID)
}
}
public func ==(lhs: SyncCommand, rhs: SyncCommand) -> Bool {
return lhs.value == rhs.value
}
public protocol SyncCommands {
func deleteCommands() -> Success
func deleteCommands(_ clientGUID: GUID) -> Success
func getCommands() -> Deferred<Maybe<[GUID: [SyncCommand]]>>
func insertCommand(_ command: SyncCommand, forClients clients: [RemoteClient]) -> Deferred<Maybe<Int>>
func insertCommands(_ commands: [SyncCommand], forClients clients: [RemoteClient]) -> Deferred<Maybe<Int>>
}
|
mpl-2.0
|
a054dc62af942d27b094c2ccc4751e6c
| 29.876923 | 110 | 0.646736 | 4.382096 | false | false | false | false |
away4m/Vendors
|
Vendors/UIKit+/TutorialScrollViewController.swift
|
1
|
8670
|
open class TutorialScrollViewController: UIPageViewController {
open var storyboardName: String { return "Main" }
fileprivate(set) lazy var orderedViewControllers: [UIViewController] = []
open var pageControl = UIPageControl()
// Controllable variable for users. An array which contains all the storyboard ids
// of the viewControllers to be rendered
open var controllerStoryboardIds: [String] = [] {
didSet {
newColoredViewController(controllerStoryboardIds)
// class method by pageViewController: set up the viewControllers we wanna page through
if let firstViewController = orderedViewControllers.first {
setViewControllers(
[firstViewController],
direction: .forward,
animated: false,
completion: nil
)
}
pageControl.numberOfPages = orderedViewControllers.count
}
}
// whether pageLooping is available
open var enablePageLooping: Bool = false
open var currentPage = 0 {
didSet {
pageControl.currentPage = currentPage
setViewControllers([orderedViewControllers[currentPage]], direction: .forward, animated: false, completion: nil)
}
}
open var pageControlIsHidden = false {
didSet {
pageControl.isHidden = pageControlIsHidden
}
}
open var pageControlXPosition: CGFloat? {
didSet {
pageControl.frame = CGRect(x: pageControlXPosition!, y: pageControl.frame.origin.y, width: pageControl.frame.width, height: pageControl.frame.height)
}
}
open var pageControlYPosition: CGFloat? {
didSet {
pageControl.frame = CGRect(x: pageControl.frame.origin.x, y: pageControlYPosition!, width: pageControl.frame.width, height: pageControl.frame.height)
}
}
open var enableTappingPageControl: Bool = true
open override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
let pageControlHeight: CGFloat = 50
pageControl.frame = CGRect(x: 80, y: view.frame.height - pageControlHeight, width: view.frame.width - 160, height: pageControlHeight)
pageControl.numberOfPages = orderedViewControllers.count
pageControl.currentPage = currentPage
pageControl.addTarget(self, action: #selector(TutorialScrollViewController.didTapPageControl(_:)), for: .touchUpInside)
view.addSubview(pageControl)
}
open override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Bring the pageControl to front so that its background color is transparent
for subView in view.subviews {
if subView is UIScrollView {
subView.frame = view.bounds
} else if subView is UIPageControl {
view.bringSubviewToFront(subView)
}
}
}
// MARK: - Helper Methods:
fileprivate func newColoredViewController(_ ViewControllerNames: [String]) -> [UIViewController] {
for viewControllerStoryBoardId in ViewControllerNames {
orderedViewControllers.append(UIStoryboard(name: storyboardName, bundle: nil).instantiateViewController(withIdentifier: "\(viewControllerStoryBoardId)"))
}
return orderedViewControllers
}
open func goNext() {
if let currentViewController = viewControllers?[0] {
let currentPageIndex = orderedViewControllers.index(of: currentViewController)! + 1
if currentPageIndex < pageControl.numberOfPages {
setViewControllers([orderedViewControllers[currentPageIndex]], direction: .forward, animated: true, completion: nil)
pageControl.currentPage = currentPageIndex
}
}
}
@objc open func didTapPageControl(_ pageControl: UIPageControl?) {
if !enableTappingPageControl {
return
}
if let pageControl = pageControl {
if let currentViewController = viewControllers?[0] {
let currentPageIndex = orderedViewControllers.index(of: currentViewController)
var upcomingTutorialPage = pageControl.currentPage
var direction: UIPageViewController.NavigationDirection = (currentPageIndex! <= upcomingTutorialPage) ? .forward : .reverse
if currentPageIndex == 0, currentPageIndex == upcomingTutorialPage {
direction = .reverse
}
if enablePageLooping {
switch currentViewController {
case orderedViewControllers.last!:
if direction == .forward {
pageControl.currentPage = 0
upcomingTutorialPage = 0
}
case orderedViewControllers.first!:
if direction == .reverse {
pageControl.currentPage = orderedViewControllers.count - 1
upcomingTutorialPage = orderedViewControllers.count - 1
}
default:
break
}
}
setViewControllers([orderedViewControllers[upcomingTutorialPage]], direction: direction, animated: true, completion: nil)
}
}
}
}
// MARK: UIPageViewControllerDataSource
extension TutorialScrollViewController: UIPageViewControllerDataSource {
// protocal function: render previous page
public func pageViewController(
_: UIPageViewController,
viewControllerBefore viewController: UIViewController
) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
if enablePageLooping {
return orderedViewControllers.last
} else {
return nil
}
}
guard orderedViewControllers.count > previousIndex else {
return nil
}
return orderedViewControllers[previousIndex]
}
// protocal function: render later page
public func pageViewController(
_: UIPageViewController,
viewControllerAfter viewController: UIViewController
) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = orderedViewControllers.count
guard orderedViewControllersCount != nextIndex else {
if enablePageLooping {
return orderedViewControllers.first
} else {
return nil
}
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return orderedViewControllers[nextIndex]
}
// // protocal function: render page control
// func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
// return orderedViewControllers.count
// }
//
// // protocal function: determine the current page
// func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
// guard let currentViewController = viewControllers?.first,
// currentViewControllerIndex = orderedViewControllers.indexOf(currentViewController) else {
// return 0
// }
//
// return currentViewControllerIndex
// }
}
extension TutorialScrollViewController: UIPageViewControllerDelegate {
public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating _: Bool, previousViewControllers _: [UIViewController], transitionCompleted completed: Bool) {
if completed {
guard let currentViewController = pageViewController.viewControllers?[0],
let currentViewControllerIndex = orderedViewControllers.index(of: currentViewController) else {
fatalError("No controller to be rendered")
}
pageControl.currentPage = currentViewControllerIndex
}
}
}
|
mit
|
894fd1ed457e17428eb373a67d5a39d7
| 36.051282 | 192 | 0.630334 | 6.470149 | false | false | false | false |
darthpelo/SurviveAmsterdam
|
mobile/SurviveAmsterdam/ModelManager.swift
|
1
|
8215
|
//
// ModelManager.swift
// SurviveAmsterdam
//
// Created by Alessio Roberto on 08/03/16.
// Copyright © 2016 Alessio Roberto. All rights reserved.
//
import CloudKit
enum ModelManagerError: ErrorType {
case SaveFailed
case QueryFailed
case DeleteFailed
case UpdateFailed
case CloudKtFailed
}
class ModelManager {
// func getShops() throws -> Results<(Shop)> {
// do {
// let realm = try Realm()
// return realm.objects(Shop)
// } catch {
// throw ModelManagerError.QueryFailed
// }
// }
//
// func getShopsMatching(query:String) throws -> Results<(Shop)> {
// do {
// let realm = try Realm()
// return realm.objects(Shop).filter(NSPredicate(format: "name CONTAINS[c] %@", query))
// } catch {
// throw ModelManagerError.QueryFailed
// }
// }
//
// func getShopMatchingID(query:String) throws -> Results<(Shop)> {
// do {
// let realm = try Realm()
// let result = realm.objects(Shop).filter(NSPredicate(format: "id ==[c] %@", query))
// if result.count == 0 {
// throw ModelManagerError.QueryFailed
// }
// return result
// } catch {
// throw ModelManagerError.QueryFailed
// }
// }
//
// func saveShop(newShop: Shop) throws {
// let realm = try! Realm()
//
// do {
// try realm.write {
// realm.add(newShop)
// }
// } catch {
// throw ModelManagerError.SaveFailed
// }
// }
//
// func deleteShop(shop: Shop) throws {
// let realm = try! Realm()
//
// do {
//
// try realm.write {
// realm.delete(shop)
// }
// } catch {
// throw ModelManagerError.DeleteFailed
// }
// }
//
// func updateShop(shop: Shop) throws {
// let realm = try! Realm()
//
// do {
// try realm.write {
// realm.add(shop, update: true)
// }
// } catch {
// throw ModelManagerError.UpdateFailed
// }
// }
//
// func getProducts() throws -> Results<(Product)> {
// do {
// let realm = try Realm()
// return realm.objects(Product)
// } catch {
// throw ModelManagerError.QueryFailed
// }
// }
//
// func getProductsMatching(query:String) throws -> Results<(Product)> {
// do {
// let realm = try Realm()
// return realm.objects(Product).filter(NSPredicate(format: "name CONTAINS[c] %@", query))
// } catch {
// throw ModelManagerError.QueryFailed
// }
// }
//
// func getProductMatchingID(query:String) throws -> Results<(Product)> {
// do {
// let realm = try Realm()
// let result = realm.objects(Product).filter(NSPredicate(format: "id ==[c] %@", query))
// if result.count == 0 {
// throw ModelManagerError.QueryFailed
// }
// return result
// } catch {
// throw ModelManagerError.QueryFailed
// }
// }
//
// func saveProduct(newProduct: Product, completion: (ModelManagerError?) -> Void ) {
// let realm = try! Realm()
//
// do {
// try realm.write {
// realm.add(newProduct)
// let productRecord = CloudProduct(productRecordID: newProduct.id!,
// productRecordName: newProduct.name,
// productRecordShopName: newProduct.shops.first?.name ?? "",
// productRecordShopAddress: newProduct.shops.first?.address ?? "")
//
// saveOnCloudKit(productRecord, completion: { (error) in
// if error != nil {
// completion(ModelManagerError.CloudKtFailed)
// } else {
// completion(nil)
// }
// })
// }
// } catch {
// completion(ModelManagerError.SaveFailed)
// }
// }
//
// func deleteProcut(product: Product) throws {
// deleteRecord(product.id!)
// let realm = try! Realm()
//
// do {
// try realm.write {
// realm.delete(product)
// }
// } catch {
// throw ModelManagerError.DeleteFailed
// }
// }
//
// func updateProduct(product: Product) throws {
// let realm = try! Realm()
//
// do {
// try realm.write {
// realm.add(product, update: true)
// }
// } catch {
// throw ModelManagerError.UpdateFailed
// }
// }
}
extension ModelManager {
// struct CloudProduct {
// let productRecordID:String
// let productRecordName:String
// let productRecordShopName:String
// let productRecordShopAddress:String
// }
//
// func getAllRecords(completionHandler: (ModelManagerError?) -> Void) {
// let predicate = NSPredicate(value: true)
//
// let query = CKQuery(recordType: "Product", predicate: predicate)
//
// let privateDatabase = CKContainer.defaultContainer().privateCloudDatabase
// privateDatabase.performQuery(query, inZoneWithID: nil, completionHandler: { (results, error) in
// if (results?.count == 0 || error != nil) {
// completionHandler(ModelManagerError.CloudKtFailed)
// } else {
// let realm = try! Realm()
//
// results?.forEach({ record in
// let product = Product()
// let shop = Shop()
// shop.setupModel(record["shopName"] as! String, address: record["shopAddress"] as? String, shopImage: nil)
// let recordID = record.recordID.recordName
// product.setupModelID(recordID, name: record["name"] as! String, shop: shop, productImage: nil, productThumbnail: nil)
// try! realm.write {
// realm.add(product)
// }
// })
// completionHandler(nil)
// }
// })
// }
//
// private func saveOnCloudKit(newProduct: CloudProduct, completion: (ModelManagerError?) -> Void ) {
// CKContainer.defaultContainer().accountStatusWithCompletionHandler { (accountStatus, error) in
// if accountStatus == .NoAccount {
// completion(ModelManagerError.CloudKtFailed)
// } else {
// let productRecordID = CKRecordID(recordName: newProduct.productRecordID)
// let productRecord = CKRecord(recordType: "Product", recordID: productRecordID)
// productRecord["name"] = newProduct.productRecordName
// productRecord["shopName"] = newProduct.productRecordShopName
// productRecord["shopAddress"] = newProduct.productRecordShopAddress
// // productRecord["image"] = newProduct.productImage
// let myContainer = CKContainer.defaultContainer()
// let privateDatabase = myContainer.privateCloudDatabase
// privateDatabase.saveRecord(productRecord, completionHandler: { (productRecord, error) in
// if (error == nil) {
// print("saved on cloud")
// completion(nil)
// } else {
// print("error")
// print(error.debugDescription)
// completion(ModelManagerError.CloudKtFailed)
// }
// })
// }
// }
// }
//
// private func deleteRecord(id: String) {
// let privateDatabase = CKContainer.defaultContainer().privateCloudDatabase
// privateDatabase.deleteRecordWithID(CKRecordID(recordName: id)) { (recordID, error) in
// assert(error == nil)
// }
// }
}
|
mit
|
a77a79ce43a6db05153061e2745fe5ab
| 33.658228 | 139 | 0.50767 | 4.260373 | false | false | false | false |
edx/edx-app-ios
|
Source/CourseCatalogAPI.swift
|
1
|
2549
|
//
// CourseCatalogAPI.swift
// edX
//
// Created by Anna Callahan on 10/14/15.
// Copyright © 2015 edX. All rights reserved.
//
import edXCore
public struct CourseCatalogAPI {
static func coursesDeserializer(response : HTTPURLResponse, json : JSON) -> Result<[OEXCourse]> {
return (json.array?.compactMap {item in
item.dictionaryObject.map { OEXCourse(dictionary: $0) }
}).toResult()
}
static func courseDeserializer(response : HTTPURLResponse, json : JSON) -> Result<OEXCourse> {
return json.dictionaryObject.map { OEXCourse(dictionary: $0) }.toResult()
}
static func enrollmentDeserializer(response: HTTPURLResponse, json: JSON) -> Result<UserCourseEnrollment> {
return UserCourseEnrollment(json: json).toResult()
}
private enum Params : String {
case User = "username"
case CourseDetails = "course_details"
case CourseID = "course_id"
case EmailOptIn = "email_opt_in"
case Mobile = "mobile"
case Org = "org"
}
public static func getCourseCatalog(userID: String, page : Int, organizationCode: String?) -> NetworkRequest<Paginated<[OEXCourse]>> {
var query = [Params.Mobile.rawValue: JSON(true), Params.User.rawValue: JSON(userID)]
if let orgCode = organizationCode {
query[Params.Org.rawValue] = JSON(orgCode)
}
return NetworkRequest(
method: .GET,
path : "api/courses/v1/courses/",
requiresAuth : true,
query : query,
deserializer: .jsonResponse(coursesDeserializer)
).paginated(page: page)
}
public static func getCourse(courseID: String) -> NetworkRequest<OEXCourse> {
return NetworkRequest(
method: .GET,
path: "api/courses/v1/courses/{courseID}".oex_format(withParameters: ["courseID" : courseID]),
deserializer: .jsonResponse(courseDeserializer))
}
public static func enroll(courseID: String, emailOptIn: Bool = true) -> NetworkRequest<UserCourseEnrollment> {
return NetworkRequest(
method: .POST,
path: "api/enrollment/v1/enrollment",
requiresAuth: true,
body: .jsonBody(JSON([
"course_details" : [
"course_id": courseID,
"email_opt_in": emailOptIn
]
])),
deserializer: .jsonResponse(enrollmentDeserializer)
)
}
}
|
apache-2.0
|
8479376d545d20418832f876c849fc9a
| 33.432432 | 138 | 0.600471 | 4.566308 | false | false | false | false |
kumabook/MusicFav
|
MusicFav/OAuthViewController.swift
|
1
|
2578
|
//
// OAuthWebViewController.swift
// MusicFav
//
// Created by Hiroki Kumamoto on 2018/01/01.
// Copyright © 2018 Hiroki Kumamoto. All rights reserved.
//
import Foundation
import SoundCloudKit
import FeedlyKit
import UIKit
import OAuthSwift
class OAuthViewController: OAuthWebViewController {
var targetURL: URL?
let webView: UIWebView = UIWebView()
weak var oauth: OAuthSwift?
var statusBarHeight: CGFloat {
return UIApplication.shared.statusBarFrame.height
}
init(oauth: OAuthSwift) {
self.oauth = oauth
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(OAuthViewController.close))
webView.frame = view.frame
webView.scalesPageToFit = true
webView.delegate = self
view.addSubview(webView)
loadAddressURL()
}
@objc func close() {
dismissWebViewController()
}
override func doHandle(_ url: URL) {
if navigationController == nil {
let nav = UINavigationController(rootViewController: self)
AppDelegate.shared.coverViewController?.present(nav, animated: true)
}
}
override func dismissWebViewController() {
navigationController?.dismiss(animated: true, completion: nil)
oauth?.cancel()
}
override func handle(_ url: URL) {
targetURL = url
super.handle(url)
self.loadAddressURL()
}
func loadAddressURL() {
guard let url = targetURL else {
return
}
let req = URLRequest(url: url)
self.webView.loadRequest(req)
}
}
// MARK: UINavigationBarDelegate
extension OAuthViewController: UINavigationBarDelegate {
public func position(for bar: UIBarPositioning) -> UIBarPosition {
return UIBarPosition.topAttached
}
}
// MARK: delegate
extension OAuthWebViewController: UIWebViewDelegate {
public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
guard let url = request.url else { return true }
if url.absoluteString.hasPrefix(APIClient.redirectUri) || url.absoluteString.hasPrefix(CloudAPIClient.redirectUrl) {
OAuthSwift.handle(url: url)
dismissWebViewController()
}
return true
}
}
|
mit
|
4c93c761a18244f2c16bcc70e0727084
| 27.318681 | 148 | 0.668607 | 4.927342 | false | false | false | false |
WSUCSClub/upac-ios
|
UPAC/BoardManager.swift
|
1
|
1380
|
//
// BoardManager.swift
// UPAC
//
// Created by Marquez, Richard A on 11/1/14.
// Copyright (c) 2014 wsu-cs-club. All rights reserved.
//
import Foundation
let boardMgr = BoardManager()
class Member {
var id = String()
var name = String()
var position = String()
var email = String()
var picture = NSData()
}
class BoardManager {
var list = [Member]()
init() {
populateList()
}
func populateList() {
list = []
var query = PFQuery(className: "Member")
query.findObjectsInBackgroundWithBlock { parseList, error in
if let error = error {
println("Could not retrieve board members from Parse: \(error)")
} else {
for parseMember in parseList {
let newMember = Member()
newMember.name = parseMember["name"] as! String
newMember.position = parseMember["position"] as! String
newMember.email = parseMember["email"] as! String
newMember.picture = (parseMember["picture"] as! PFFile).getData()
self.list.append(newMember)
}
__boardTableView!.reloadData()
}
}
}
}
|
gpl-3.0
|
ffd9e04fea016d64631542c5dd66778f
| 25.056604 | 85 | 0.497826 | 4.876325 | false | false | false | false |
gokush/GKAddressKit
|
GKAddressKitExample/Address/ProvinceEntity.swift
|
1
|
2141
|
//
// ProvinceEntity.swift
// GKAddressKit
//
// Created by 童小波 on 15/1/19.
// Copyright (c) 2015年 tongxiaobo. All rights reserved.
//
import Foundation
import CoreData
@objc(ProvinceEntity) class ProvinceEntity: NSManagedObject {
@NSManaged var provinceId: NSNumber
@NSManaged var name: String
@NSManaged var pinyin: String
@NSManaged var refresh: Bool
@NSManaged var addresses: NSMutableSet
@NSManaged var cities: NSMutableSet
class func insertProvince(provinceId: Int, provinceName: String, pinyin: String, managedObjectContext: NSManagedObjectContext) -> ProvinceEntity{
let province = NSEntityDescription.insertNewObjectForEntityForName("ProvinceEntity", inManagedObjectContext: managedObjectContext) as ProvinceEntity
province.provinceId = provinceId
province.name = provinceName
province.pinyin = pinyin
return province
}
class func selectWithId(provinceId: Int, managedObjectContext: NSManagedObjectContext) -> ProvinceEntity?{
let predicate = NSPredicate(format: "provinceId == \(provinceId)")
let province = fetchItems(predicate!, managedObjectContext: managedObjectContext) as? ProvinceEntity
return province
}
func updateProvince(provinceId: Int?, name: String?, pinyin: String?){
if provinceId != nil{
self.provinceId = provinceId!
}
if name != nil{
self.name = name!
}
if pinyin != nil{
self.pinyin = pinyin!
}
}
}
extension ProvinceEntity{
func addCitiesObject(value: NSManagedObject){
self.cities.addObject(value)
}
func removeCitiesObject(value: NSManagedObject){
self.cities.removeObject(value)
}
func removeCities(values: [NSManagedObject]){
for item in values{
self.removeCitiesObject(item)
}
}
}
extension ProvinceEntity{
func addAddressesObject(value: AddressEntity){
self.addresses.addObject(value)
}
func removeAddressesObject(value: AddressEntity){
self.addresses.removeObject(value)
}
}
|
mit
|
be81395f3a97560eace134d965916819
| 29.913043 | 156 | 0.680731 | 4.647059 | false | false | false | false |
srxboys/RXSwiftExtention
|
RXSwiftExtention/Tools/Extention/UIBarButtonItem-Extension.swift
|
1
|
1451
|
//
// UIBarButtonItem-Extension.swift
// RXSwiftExtention
//
// Created by srx on 2017/3/25.
// Copyright © 2017年 https://github.com/srxboys. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
/*
class func createItem(imageName : String, highImageName : String, size : CGSize) -> UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), forState: .Normal)
btn.setImage(UIImage(named: highImageName), forState: .Highlighted)
btn.frame = CGRect(origin: CGPointZero, size: size)
return UIBarButtonItem(customView: btn)
}
*/
// 便利构造函数: 1> convenience开头 2> 在构造函数中必须明确调用一个设计的构造函数(self)
convenience init(imageName : String, highImageName : String = "", size : CGSize = CGSize.zero) {
// 1.创建UIButton
let btn = UIButton()
// 2.设置btn的图片
btn.setImage(UIImage(named: imageName), for: UIControlState())
if highImageName != "" {
btn.setImage(UIImage(named: highImageName), for: .highlighted)
}
// 3.设置btn的尺寸
if size == CGSize.zero {
btn.sizeToFit()
} else {
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
// 4.创建UIBarButtonItem
self.init(customView : btn)
}
}
|
mit
|
f33d91209fa16ef23f3be6c08df15982
| 27.978723 | 105 | 0.588106 | 4.310127 | false | false | false | false |
mmcguill/StrongBox
|
FavIcon-Swift/IconExtraction.swift
|
1
|
13778
|
//
// FavIcon
// Copyright © 2016 Leon Breedt
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
//import FavIcon.XMLDocument
/// Represents an icon size.
struct IconSize : Hashable, Equatable {
func hash(into hasher: inout Hasher) {
hasher.combine(width.hashValue ^ height.hashValue)
}
static func ==(lhs: IconSize, rhs: IconSize) -> Bool {
return lhs.width == rhs.width && lhs.height == rhs.height
}
/// The width of the icon.
let width: Int
/// The height of the icon.
let height: Int
}
private let kRelIconTypeMap: [IconSize: DetectedIconType] = [
IconSize(width: 16, height: 16): .classic,
IconSize(width: 32, height: 32): .appleOSXSafariTab,
IconSize(width: 96, height: 96): .googleTV,
IconSize(width: 192, height: 192): .googleAndroidChrome,
IconSize(width: 196, height: 196): .googleAndroidChrome
]
private let kMicrosoftSizeMap: [String: IconSize] = [
"msapplication-tileimage": IconSize(width: 144, height: 144),
"msapplication-square70x70logo": IconSize(width: 70, height: 70),
"msapplication-square150x150logo": IconSize(width: 150, height: 150),
"msapplication-wide310x150logo": IconSize(width: 310, height: 150),
"msapplication-square310x310logo": IconSize(width: 310, height: 310),
]
private let siteImage: [String: IconSize] = [
"og:image": IconSize(width: 1024, height: 512),
"twitter:image": IconSize(width: 1024, height: 512)
]
/// Extracts a list of icons from the `<head>` section of an HTML document.
///
/// - parameter document: An HTML document to process.
/// - parameter baseURL: A base URL to combine with any relative image paths.
/// - parameter returns: An array of `DetectedIcon` structures.
// swiftlint:disable function_body_length
// swiftlint:disable cyclomatic_complexity
func examineHTMLMeta(_ document: HTMLDocument, baseURL: URL) -> [String:String] {
var resp: [String:String] = [:]
for meta in document.query("/html/head/meta") {
if let property = meta.attributes["property"]?.lowercased(),
let content = meta.attributes["content"]{
switch property {
case "og:url":
resp["og:url"] = content;
break
case "og:description":
resp["description"] = content;
break
case "og:image":
resp["image"] = content;
break
case "og:title":
resp["title"] = content;
break
case "og:site_name":
resp["site_name"] = content;
break
default:
break
}
}
if let name = meta.attributes["name"]?.lowercased(),
let content = meta.attributes["content"],
name == "description" {
resp["description"] = resp["description"] ?? content;
}
}
for title in document.query("/html/head/title") {
if let titleString = title.contents {
resp["title"] = resp["title"] ?? titleString;
}
}
for link in document.query("/html/head/link") {
if let rel = link.attributes["rel"],
let href = link.attributes["href"],
let url = URL(string: href, relativeTo: baseURL)
{
switch rel.lowercased() {
case "canonical":
resp["canonical"] = url.absoluteString;
break
case "amphtml":
resp["amphtml"] = url.absoluteString;
break
case "search":
resp["search"] = url.absoluteString;
break
case "fluid-icon":
resp["fluid-icon"] = url.absoluteString;
break
case "alternate":
let application = link.attributes["application"]
if application == "application/atom+xml" {
resp["atom"] = url.absoluteString;
}
break
default:
break
}
}
}
return resp;
}
func extractHTMLHeadIcons(_ document: HTMLDocument, baseURL: URL) -> [DetectedIcon] {
var icons: [DetectedIcon] = []
for link in document.query("/html/head/link") {
if let rel = link.attributes["rel"],
let href = link.attributes["href"],
let url = URL(string: href, relativeTo: baseURL) {
switch rel.lowercased() {
case "shortcut icon":
icons.append(DetectedIcon(url: url.absoluteURL, type:.shortcut))
break
case "icon":
if let type = link.attributes["type"], type.lowercased() == "image/png" {
let sizes = parseHTMLIconSizes(link.attributes["sizes"])
if sizes.count > 0 {
for size in sizes {
if let type = kRelIconTypeMap[size] {
icons.append(DetectedIcon(url: url,
type: type,
width: size.width,
height: size.height))
}
}
} else {
icons.append(DetectedIcon(url: url.absoluteURL, type: .classic))
}
} else {
icons.append(DetectedIcon(url: url.absoluteURL, type: .classic))
}
case "apple-touch-icon":
let sizes = parseHTMLIconSizes(link.attributes["sizes"])
if sizes.count > 0 {
for size in sizes {
icons.append(DetectedIcon(url: url.absoluteURL,
type: .appleIOSWebClip,
width: size.width,
height: size.height))
}
} else {
icons.append(DetectedIcon(url: url.absoluteURL,
type: .appleIOSWebClip,
width: 60,
height: 60))
}
default:
break
}
}
}
for meta in document.query("/html/head/meta") {
if let name = meta.attributes["name"]?.lowercased(),
let content = meta.attributes["content"],
let url = URL(string: content, relativeTo: baseURL),
let size = kMicrosoftSizeMap[name] {
icons.append(DetectedIcon(url: url,
type: .microsoftPinnedSite,
width: size.width,
height: size.height))
} else if
let property = meta.attributes["property"]?.lowercased(),
let content = meta.attributes["content"],
let url = URL(string: content, relativeTo: baseURL),
let size = siteImage[property] {
icons.append(DetectedIcon(url: url,
type: .FBImage,
width: size.width,
height: size.height))
}
}
return icons
}
// swiftlint:enable cyclomatic_complexity
// swiftlint:enable function_body_length
/// Extracts a list of icons from a Web Application Manifest file
///
/// - parameter jsonString: A JSON string containing the contents of the manifest file.
/// - parameter baseURL: A base URL to combine with any relative image paths.
/// - returns: An array of `DetectedIcon` structures.
func extractManifestJSONIcons(_ jsonString: String, baseURL: URL) -> [DetectedIcon] {
var icons: [DetectedIcon] = []
if let data = jsonString.data(using: String.Encoding.utf8),
let object = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()),
let manifest = object as? NSDictionary,
let manifestIcons = manifest["icons"] as? [NSDictionary] {
for icon in manifestIcons {
if let type = icon["type"] as? String, type.lowercased() == "image/png",
let src = icon["src"] as? String,
let url = URL(string: src, relativeTo: baseURL)?.absoluteURL {
let sizes = parseHTMLIconSizes(icon["sizes"] as? String)
if sizes.count > 0 {
for size in sizes {
icons.append(DetectedIcon(url: url,
type: .webAppManifest,
width: size.width,
height: size.height))
}
} else {
icons.append(DetectedIcon(url: url, type: .webAppManifest))
}
}
}
}
return icons
}
/// Extracts a list of icons from a Microsoft browser configuration XML document.
///
/// - parameter document: An `XMLDocument` for the Microsoft browser configuration file.
/// - parameter baseURL: A base URL to combine with any relative image paths.
/// - returns: An array of `DetectedIcon` structures.
func extractBrowserConfigXMLIcons(_ document: LBXMLDocument, baseURL: URL) -> [DetectedIcon] {
var icons: [DetectedIcon] = []
for tile in document.query("/browserconfig/msapplication/tile/*") {
if let src = tile.attributes["src"],
let url = URL(string: src, relativeTo: baseURL)?.absoluteURL {
switch tile.name.lowercased() {
case "tileimage":
icons.append(DetectedIcon(url: url, type: .microsoftPinnedSite, width: 144, height: 144))
break
case "square70x70logo":
icons.append(DetectedIcon(url: url, type: .microsoftPinnedSite, width: 70, height: 70))
break
case "square150x150logo":
icons.append(DetectedIcon(url: url, type: .microsoftPinnedSite, width: 150, height: 150))
break
case "wide310x150logo":
icons.append(DetectedIcon(url: url, type: .microsoftPinnedSite, width: 310, height: 150))
break
case "square310x310logo":
icons.append(DetectedIcon(url: url, type: .microsoftPinnedSite, width: 310, height: 310))
break
default:
break
}
}
}
return icons
}
/// Extracts the Web App Manifest URLs from an HTML document, if any.
///
/// - parameter document: The HTML document to scan for Web App Manifest URLs
/// - parameter baseURL: The base URL that any 'href' attributes are relative to.
/// - returns: An array of Web App Manifest `URL`s.
func extractWebAppManifestURLs(_ document: HTMLDocument, baseURL: URL) -> [URL] {
var urls: [URL] = []
for link in document.query("/html/head/link") {
if let rel = link.attributes["rel"]?.lowercased(), rel == "manifest",
let href = link.attributes["href"], let manifestURL = URL(string: href, relativeTo: baseURL) {
urls.append(manifestURL)
}
}
return urls
}
/// Extracts the first browser config XML file URL from an HTML document, if any.
///
/// - parameter document: The HTML document to scan for browser config XML file URLs.
/// - parameter baseURL: The base URL that any 'href' attributes are relative to.
/// - returns: A named tuple describing the file URL or a flag indicating that the server
/// explicitly requested that the file not be downloaded.
func extractBrowserConfigURL(_ document: HTMLDocument, baseURL: URL) -> (url: URL?, disabled: Bool) {
for meta in document.query("/html/head/meta") {
if let name = meta.attributes["name"]?.lowercased(), name == "msapplication-config",
let content = meta.attributes["content"] {
if content.lowercased() == "none" {
// Explicitly asked us not to download the file.
return (url: nil, disabled: true)
} else {
return (url: URL(string: content, relativeTo: baseURL)?.absoluteURL, disabled: false)
}
}
}
return (url: nil, disabled: false)
}
/// Helper function for parsing a W3 `sizes` attribute value.
///
/// - parameter string: If not `nil`, the value of the attribute to parse (e.g. `50x50 144x144`).
/// - returns: An array of `IconSize` structs for each size found.
func parseHTMLIconSizes(_ string: String?) -> [IconSize] {
var sizes: [IconSize] = []
if let string = string?.lowercased(), string != "any" {
for size in string.components(separatedBy: .whitespaces) {
let parts = size.components(separatedBy: "x")
if parts.count != 2 { continue }
if let width = Int(parts[0]), let height = Int(parts[1]) {
sizes.append(IconSize(width: width, height: height))
}
}
}
return sizes
}
|
agpl-3.0
|
de0fa08950adbd46f6e4d67466d56c8e
| 40.002976 | 111 | 0.54787 | 4.637159 | false | false | false | false |
themonki/onebusaway-iphone
|
Carthage/Checkouts/IGListKit/Examples/Examples-macOS/IGListKitExamples/Helpers/UsersProvider.swift
|
3
|
1313
|
/**
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 Foundation
final class UsersProvider {
enum UsersError: Error {
case invalidData
}
let users: [User]
init(with file: URL) throws {
let data = try Data(contentsOf: file)
let json = try JSONSerialization.jsonObject(with: data, options: [])
guard let dicts = json as? [[String: String]] else {
throw UsersError.invalidData
}
self.users = dicts.enumerated().flatMap { index, dict in
guard let name = dict["name"] else { return nil }
return User(pk: index, name: name.capitalized)
}.sorted(by: { $0.name < $1.name })
}
}
|
apache-2.0
|
904ef68ad609ebc3a29aa71f5c690cc4
| 31.825 | 80 | 0.686215 | 4.496575 | false | false | false | false |
ligen52/SwiftWeibo
|
SwiftWeibo/SwiftWeibo/Classes/Home/HomeTableViewController.swift
|
1
|
4332
|
//
// HomeTableViewController.swift
// SwiftWeibo
//
// Created by GenLi on 2/10/17.
// Copyright © 2017 GenLi. All rights reserved.
//
import UIKit
class HomeTableViewController: BaseTableViewController {
var vc:UIViewController?
override init(style: UITableViewStyle) {
super.init(style: style)
let sb = UIStoryboard(name: "PopoverViewController", bundle: nil)
vc = sb.instantiateInitialViewController()
vc?.transitioningDelegate = self
vc?.modalPresentationStyle = UIModalPresentationStyle.custom
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
if !isUserLogin {
visitorView?.setupVisitorViewInfo(isHome: true, imgName: "visitordiscover_feed_image_house", msg: "关注一些人,回这里看有些什么惊喜")
return
}
setupNav()
}
private func setupNav(){
navigationItem.leftBarButtonItem = UIBarButtonItem.createBarButton(imageName: "navigationbar_friendattention")
navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButton(imageName: "navigationbar_pop")
let titleBtn = TitleButton()
titleBtn.setTitle("mars ", for: UIControlState.normal)
titleBtn.addTarget(self, action: #selector(titleBtnClick), for: UIControlEvents.touchUpInside)
navigationItem.titleView = titleBtn
}
func titleBtnClick(btn:UIButton){
btn.isSelected = !btn.isSelected
present(vc!, animated: true, completion: nil)
}
var isPresent: Bool = false
}
extension HomeTableViewController:UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning
{
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController?{
return PopoverPresentationController(presentedViewController: presented, presenting: presenting)
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning?{
isPresent = true
return self
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?{
isPresent = false
return self
}
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval{
return 0.5
}
// This method can only be a nop if the transition is interactive and not a percentDriven interactive transition.
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning){
if isPresent {
//startPresentAnimation()
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)
toView?.transform = CGAffineTransform(scaleX: 1.0, y: 0.0)
transitionContext.containerView.addSubview(toView!)
toView?.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
UIView.animate(withDuration: 0.5, animations: { () -> Void in
toView?.transform = CGAffineTransform.identity
},completion : {
(Bool)->Void in
transitionContext.completeTransition(true)
})
}else{
//startdismissAnimation()
let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)
transitionContext.containerView.addSubview(fromView!)
fromView?.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
UIView.animate(withDuration: 0.5, animations: { () -> Void in
// 3.2还原动画
fromView?.transform = CGAffineTransform(scaleX: 1.0, y: 0.00000001)
},completion : {
(Bool)->Void in
transitionContext.completeTransition(true)
})
}
}
}
|
mit
|
655b7c99d2a2a1049cbb076e1aa02892
| 30.108696 | 169 | 0.632658 | 6.012605 | false | false | false | false |
zhangliangzhi/iosStudyBySwift
|
xxcolor/xxcolor/INSPersistentContainer/INSPersistentContainer.swift
|
4
|
5402
|
//
// INSPersistentContainer.swift
// INSPersistentContainer-Swift2
//
// Created by Michal Zaborowski on 24.06.2016.
// Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. 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
import CoreData
// An instance of NSPersistentContainer includes all objects needed to represent a functioning Core Data stack, and provides convenience methods and properties for common patterns.
open class INSPersistentContainer {
open class func defaultDirectoryURL() -> URL {
struct Static {
static let instance: URL = {
guard let applicationSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else {
fatalError("Found no possible URLs for directory type \(FileManager.SearchPathDirectory.applicationSupportDirectory)")
}
var isDirectory = ObjCBool(false)
if !FileManager.default.fileExists(atPath: applicationSupportURL.path, isDirectory: &isDirectory) {
do {
try FileManager.default.createDirectory(at: applicationSupportURL, withIntermediateDirectories: true, attributes: nil)
return applicationSupportURL
} catch {
fatalError("Failed to create directory \(applicationSupportURL)")
}
}
return applicationSupportURL
}()
}
return Static.instance
}
open private(set) var name: String
open private(set) var viewContext: NSManagedObjectContext
open var managedObjectModel: NSManagedObjectModel {
return persistentStoreCoordinator.managedObjectModel
}
open private(set) var persistentStoreCoordinator: NSPersistentStoreCoordinator
open var persistentStoreDescriptions: [INSPersistentStoreDescription]
public convenience init(name: String) {
if let modelURL = Bundle.main.url(forResource: name, withExtension: "mom") ?? Bundle.main.url(forResource: name, withExtension: "momd") {
if let model = NSManagedObjectModel(contentsOf: modelURL) {
self.init(name: name, managedObjectModel: model)
return
}
print("CoreData: Failed to load model at path: \(modelURL)")
}
guard let model = NSManagedObjectModel.mergedModel(from: [Bundle.main]) else {
fatalError("Couldn't find managed object model in main bundle.")
}
self.init(name: name, managedObjectModel: model)
}
public init(name: String, managedObjectModel model: NSManagedObjectModel) {
self.name = name
self.persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
self.viewContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
self.viewContext.persistentStoreCoordinator = persistentStoreCoordinator
self.persistentStoreDescriptions = [INSPersistentStoreDescription(url: type(of: self).defaultDirectoryURL().appendingPathComponent("\(name).sqlite"))]
}
// Load stores from the storeDescriptions property that have not already been successfully added to the container. The completion handler is called once for each store that succeeds or fails.
open func loadPersistentStores(completionHandler block: @escaping (INSPersistentStoreDescription, Error?) -> Swift.Void) {
for persistentStoreDescription in persistentStoreDescriptions {
persistentStoreCoordinator.ins_addPersistentStore(with: persistentStoreDescription, completionHandler: block)
}
}
open func newBackgroundContext() -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
if let parentContext = viewContext.parent {
context.parent = parentContext
} else {
context.persistentStoreCoordinator = persistentStoreCoordinator
}
return context
}
open func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) {
let context = newBackgroundContext()
context.perform {
block(context)
}
}
}
|
mit
|
cebb2fb476764e8a1b1c62e9a5b1f3ed
| 49.457944 | 195 | 0.697722 | 5.64749 | false | false | false | false |
FienMaandag/spick-and-span
|
spick_and_span/spick_and_span/SecretCodeViewController.swift
|
1
|
2019
|
//
// SecretCodeViewController.swift
// spick_and_span
//
// Created by Fien Maandag on 07-06-17.
// Copyright © 2017 Fien Maandag. All rights reserved.
//
import UIKit
import Firebase
import Social
class SecretCodeViewController: UIViewController {
@IBOutlet weak var houseNameLabel: UILabel!
@IBOutlet weak var houseKeyLabel: UILabel!
@IBOutlet weak var toHouseButton: UIButton!
let userID = Auth.auth().currentUser?.uid
let ref = Database.database().reference()
override func viewDidLoad() {
super.viewDidLoad()
// Layout setup
whiteBorder(button: toHouseButton)
// Get current users housekey and housename
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let houseKey = value?["houseKey"] as? String ?? ""
let houseName = value?["houseName"] as? String ?? ""
self.houseNameLabel.text = houseName.uppercased()
self.houseKeyLabel.text = houseKey
}) { (error) in
print(error.localizedDescription)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// Share the housekey
@IBAction func shareButtonClicked(_ sender: Any) {
let message = "Join \(String(describing: self.houseNameLabel.text!)) with the housekey: \(String(describing: self.houseKeyLabel.text!))"
let activityViewController : UIActivityViewController = UIActivityViewController(
activityItems: [message], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = (sender as! UIButton)
activityViewController.popoverPresentationController?.sourceRect = CGRect(x: 150, y: 150, width: 0, height: 0)
self.present(activityViewController, animated: true, completion: nil)
}
}
|
mit
|
87154cf871965bc3074c6f74da15a7a0
| 33.793103 | 144 | 0.648662 | 4.958231 | false | false | false | false |
Flinesoft/HandyUIKit
|
Frameworks/HandyUIKit/ColorSpaces.swift
|
1
|
6274
|
// Copyright © 2015 Flinesoft. All rights reserved.
//
// Original source: https://github.com/timrwood/ColorSpaces
// swiftlint:disable all
import UIKit
private struct ColorSpaces {}
// MARK: - Constants
private let RAD_TO_DEG = 180 / CGFloat.pi
private let LAB_E: CGFloat = 0.008856
private let LAB_16_116: CGFloat = 0.1379310
private let LAB_K_116: CGFloat = 7.787036
private let LAB_X: CGFloat = 0.95047
private let LAB_Y: CGFloat = 1
private let LAB_Z: CGFloat = 1.088_83
// MARK: - RGB
struct RGBColor {
let r: CGFloat // 0..1
let g: CGFloat // 0..1
let b: CGFloat // 0..1
let alpha: CGFloat // 0..1
init (r: CGFloat, g: CGFloat, b: CGFloat, alpha: CGFloat) {
self.r = r
self.g = g
self.b = b
self.alpha = alpha
}
fileprivate func sRGBCompand(_ v: CGFloat) -> CGFloat {
let absV = abs(v)
let out = absV > 0.040_45 ? pow((absV + 0.055) / 1.055, 2.4) : absV / 12.92
return v > 0 ? out : -out
}
func toXYZ() -> XYZColor {
let R = sRGBCompand(r)
let G = sRGBCompand(g)
let B = sRGBCompand(b)
let x: CGFloat = (R * 0.412_456_4) + (G * 0.357_576_1) + (B * 0.180_437_5)
let y: CGFloat = (R * 0.212_672_9) + (G * 0.715_152_2) + (B * 0.072_175_0)
let z: CGFloat = (R * 0.019_333_9) + (G * 0.119_192_0) + (B * 0.950_304_1)
return XYZColor(x: x, y: y, z: z, alpha: alpha)
}
func toLAB() -> LABColor {
return toXYZ().toLAB()
}
func toLCH() -> LCHColor {
return toXYZ().toLCH()
}
func color() -> UIColor {
return UIColor(red: r, green: g, blue: b, alpha: alpha)
}
func lerp(_ other: RGBColor, t: CGFloat) -> RGBColor {
return RGBColor(
r: r + (other.r - r) * t,
g: g + (other.g - g) * t,
b: b + (other.b - b) * t,
alpha: alpha + (other.alpha - alpha) * t
)
}
}
extension UIColor {
func rgbColor() -> RGBColor {
return RGBColor(r: rgba.red, g: rgba.green, b: rgba.blue, alpha: rgba.alpha)
}
}
// MARK: - XYZ
struct XYZColor {
let x: CGFloat // 0..0.95047
let y: CGFloat // 0..1
let z: CGFloat // 0..1.08883
let alpha: CGFloat // 0..1
init (x: CGFloat, y: CGFloat, z: CGFloat, alpha: CGFloat) {
self.x = x
self.y = y
self.z = z
self.alpha = alpha
}
fileprivate func sRGBCompand(_ v: CGFloat) -> CGFloat {
let absV = abs(v)
let out = absV > 0.003_130_8 ? 1.055 * pow(absV, 1 / 2.4) - 0.055 : absV * 12.92
return v > 0 ? out : -out
}
func toRGB() -> RGBColor {
let r = (x * 3.240_454_2) + (y * -1.537_138_5) + (z * -0.498_531_4)
let g = (x * -0.969_266_0) + (y * 1.876_010_8) + (z * 0.041_556_0)
let b = (x * 0.055_643_4) + (y * -0.204_025_9) + (z * 1.057_225_2)
let R = sRGBCompand(r)
let G = sRGBCompand(g)
let B = sRGBCompand(b)
return RGBColor(r: R, g: G, b: B, alpha: alpha)
}
fileprivate func labCompand(_ v: CGFloat) -> CGFloat {
return v > LAB_E ? pow(v, 1.0 / 3.0) : (LAB_K_116 * v) + LAB_16_116
}
func toLAB() -> LABColor {
let fx = labCompand(x / LAB_X)
let fy = labCompand(y / LAB_Y)
let fz = labCompand(z / LAB_Z)
return LABColor(
l: 116 * fy - 16,
a: 500 * (fx - fy),
b: 200 * (fy - fz),
alpha: alpha
)
}
func toLCH() -> LCHColor {
return toLAB().toLCH()
}
func lerp(_ other: XYZColor, t: CGFloat) -> XYZColor {
return XYZColor(
x: x + (other.x - x) * t,
y: y + (other.y - y) * t,
z: z + (other.z - z) * t,
alpha: alpha + (other.alpha - alpha) * t
)
}
}
// MARK: - LAB
struct LABColor {
let l: CGFloat // 0..100
let a: CGFloat // -128..128
let b: CGFloat // -128..128
let alpha: CGFloat // 0..1
init (l: CGFloat, a: CGFloat, b: CGFloat, alpha: CGFloat) {
self.l = l
self.a = a
self.b = b
self.alpha = alpha
}
fileprivate func xyzCompand(_ v: CGFloat) -> CGFloat {
let v3 = v * v * v
return v3 > LAB_E ? v3 : (v - LAB_16_116) / LAB_K_116
}
func toXYZ() -> XYZColor {
let y = (l + 16) / 116
let x = y + (a / 500)
let z = y - (b / 200)
return XYZColor(
x: xyzCompand(x) * LAB_X,
y: xyzCompand(y) * LAB_Y,
z: xyzCompand(z) * LAB_Z,
alpha: alpha
)
}
func toLCH() -> LCHColor {
let c = sqrt(a * a + b * b)
let angle = atan2(b, a) * RAD_TO_DEG
let h = angle < 0 ? angle + 360 : angle
return LCHColor(l: l, c: c, h: h, alpha: alpha)
}
func toRGB() -> RGBColor {
return toXYZ().toRGB()
}
func lerp(_ other: LABColor, t: CGFloat) -> LABColor {
return LABColor(
l: l + (other.l - l) * t,
a: a + (other.a - a) * t,
b: b + (other.b - b) * t,
alpha: alpha + (other.alpha - alpha) * t
)
}
}
// MARK: - LCH
struct LCHColor {
let l: CGFloat // 0..100
let c: CGFloat // 0..128
let h: CGFloat // 0..360
let alpha: CGFloat // 0..1
init (l: CGFloat, c: CGFloat, h: CGFloat, alpha: CGFloat) {
self.l = l
self.c = c
self.h = h
self.alpha = alpha
}
func toLAB() -> LABColor {
let rad = h / RAD_TO_DEG
let a = cos(rad) * c
let b = sin(rad) * c
return LABColor(l: l, a: a, b: b, alpha: alpha)
}
func toXYZ() -> XYZColor {
return toLAB().toXYZ()
}
func toRGB() -> RGBColor {
return toXYZ().toRGB()
}
func lerp(_ other: LCHColor, t: CGFloat) -> LCHColor {
let angle = (((((other.h - h).truncatingRemainder(dividingBy: 360)) + 540).truncatingRemainder(dividingBy: 360)) - 180) * t
return LCHColor(
l: l + (other.l - l) * t,
c: c + (other.c - c) * t,
h: (h + angle + 360).truncatingRemainder(dividingBy: 360),
alpha: alpha + (other.alpha - alpha) * t
)
}
}
|
mit
|
e20f5af0782c73be504ff4b602205793
| 26.038793 | 131 | 0.487805 | 3.017316 | false | false | false | false |
seltzered/SVGKit
|
SVGKit-iOS Tests/SwiftColor_Tests.swift
|
2
|
12688
|
//
// SwiftColor_Tests.swift
// SVGKit
//
// Created by C.W. Betts on 3/18/15.
// Copyright (c) 2015 C.W. Betts. All rights reserved.
//
import Foundation
import XCTest
import SVGKit
private let gColorDict = [
"aliceblue": SVGColor(red: 240, green: 248, blue: 255),
"antiquewhite": SVGColor(red: 250, green: 235, blue: 215),
"aqua": SVGColor(red: 0, green: 255, blue: 255),
"aquamarine": SVGColor(red: 127, green: 255, blue: 212),
"azure": SVGColor(red: 240, green: 255, blue: 255),
"beige": SVGColor(red: 245, green: 245, blue: 220),
"bisque": SVGColor(red: 255, green: 228, blue: 196),
"black": SVGColor(red: 0, green: 0, blue: 0),
"blanchedalmond": SVGColor(red: 255, green: 235, blue: 205),
"blue": SVGColor(red: 0, green: 0, blue: 255),
"blueviolet": SVGColor(red: 138, green: 43, blue: 226),
"brown": SVGColor(red: 165, green: 42, blue: 42),
"burlywood": SVGColor(red: 222, green: 184, blue: 135),
"cadetblue": SVGColor(red: 95, green: 158, blue: 160),
"chartreuse": SVGColor(red: 127, green: 255, blue: 0),
"chocolate": SVGColor(red: 210, green: 105, blue: 30),
"coral": SVGColor(red: 255, green: 127, blue: 80),
"cornflowerblue": SVGColor(red: 100, green: 149, blue: 237),
"cornsilk": SVGColor(red: 255, green: 248, blue: 220),
"crimson": SVGColor(red: 220, green: 20, blue: 60),
"cyan": SVGColor(red: 0, green: 255, blue: 255),
"darkblue": SVGColor(red: 0, green: 0, blue: 139),
"darkcyan": SVGColor(red: 0, green: 139, blue: 139),
"darkgoldenrod": SVGColor(red: 184, green: 134, blue: 11),
"darkgray": SVGColor(red: 169, green: 169, blue: 169),
"darkgreen": SVGColor(red: 0, green: 100, blue: 0),
"darkgrey": SVGColor(red: 169, green: 169, blue: 169),
"darkkhaki": SVGColor(red: 189, green: 183, blue: 107),
"darkmagenta": SVGColor(red: 139, green: 0, blue: 139),
"darkolivegreen": SVGColor(red: 85, green: 107, blue: 47),
"darkorange": SVGColor(red: 255, green: 140, blue: 0),
"darkorchid": SVGColor(red: 153, green: 50, blue: 204),
"darkred": SVGColor(red: 139, green: 0, blue: 0),
"darksalmon": SVGColor(red: 233, green: 150, blue: 122),
"darkseagreen": SVGColor(red: 143, green: 188, blue: 143),
"darkslateblue": SVGColor(red: 72, green: 61, blue: 139),
"darkslategray": SVGColor(red: 47, green: 79, blue: 79),
"darkslategrey": SVGColor(red: 47, green: 79, blue: 79),
"darkturquoise": SVGColor(red: 0, green: 206, blue: 209),
"darkviolet": SVGColor(red: 148, green: 0, blue: 211),
"deeppink": SVGColor(red: 255, green: 20, blue: 147),
"deepskyblue": SVGColor(red: 0, green: 191, blue: 255),
"dimgray": SVGColor(red: 105, green: 105, blue: 105),
"dimgrey": SVGColor(red: 105, green: 105, blue: 105),
"dodgerblue": SVGColor(red: 30, green: 144, blue: 255),
"firebrick": SVGColor(red: 178, green: 34, blue: 34),
"floralwhite": SVGColor(red: 255, green: 250, blue: 240),
"forestgreen": SVGColor(red: 34, green: 139, blue: 34),
"fuchsia": SVGColor(red: 255, green: 0, blue: 255),
"gainsboro": SVGColor(red: 220, green: 220, blue: 220),
"ghostwhite": SVGColor(red: 248, green: 248, blue: 255),
"gold": SVGColor(red: 255, green: 215, blue: 0),
"goldenrod": SVGColor(red: 218, green: 165, blue: 32),
"gray": SVGColor(red: 128, green: 128, blue: 128),
"green": SVGColor(red: 0, green: 128, blue: 0),
"greenyellow": SVGColor(red: 173, green: 255, blue: 47),
"grey": SVGColor(red: 128, green: 128, blue: 128),
"honeydew": SVGColor(red: 240, green: 255, blue: 240),
"hotpink": SVGColor(red: 255, green: 105, blue: 180),
"indianred": SVGColor(red: 205, green: 92, blue: 92),
"indigo": SVGColor(red: 75, green: 0, blue: 130),
"ivory": SVGColor(red: 255, green: 255, blue: 240),
"khaki": SVGColor(red: 240, green: 230, blue: 140),
"lavender": SVGColor(red: 230, green: 230, blue: 250),
"lavenderblush": SVGColor(red: 255, green: 240, blue: 245),
"lawngreen": SVGColor(red: 124, green: 252, blue: 0),
"lemonchiffon": SVGColor(red: 255, green: 250, blue: 205),
"lightblue": SVGColor(red: 173, green: 216, blue: 230),
"lightcoral": SVGColor(red: 240, green: 128, blue: 128),
"lightcyan": SVGColor(red: 224, green: 255, blue: 255),
"lightgoldenrodyellow": SVGColor(red: 250, green: 250, blue: 210),
"lightgray": SVGColor(red: 211, green: 211, blue: 211),
"lightgreen": SVGColor(red: 144, green: 238, blue: 144),
"lightgrey": SVGColor(red: 211, green: 211, blue: 211),
"lightpink": SVGColor(red: 255, green: 182, blue: 193),
"lightsalmon": SVGColor(red: 255, green: 160, blue: 122),
"lightseagreen": SVGColor(red: 32, green: 178, blue: 170),
"lightskyblue": SVGColor(red: 135, green: 206, blue: 250),
"lightslategray": SVGColor(red: 119, green: 136, blue: 153),
"lightslategrey": SVGColor(red: 119, green: 136, blue: 153),
"lightsteelblue": SVGColor(red: 176, green: 196, blue: 222),
"lightyellow": SVGColor(red: 255, green: 255, blue: 224),
"lime": SVGColor(red: 0, green: 255, blue: 0),
"limegreen": SVGColor(red: 50, green: 205, blue: 50),
"linen": SVGColor(red: 250, green: 240, blue: 230),
"magenta": SVGColor(red: 255, green: 0, blue: 255),
"maroon": SVGColor(red: 128, green: 0, blue: 0),
"mediumaquamarine": SVGColor(red: 102, green: 205, blue: 170),
"mediumblue": SVGColor(red: 0, green: 0, blue: 205),
"mediumorchid": SVGColor(red: 186, green: 85, blue: 211),
"mediumpurple": SVGColor(red: 147, green: 112, blue: 219),
"mediumseagreen": SVGColor(red: 60, green: 179, blue: 113),
"mediumslateblue": SVGColor(red: 123, green: 104, blue: 238),
"mediumspringgreen": SVGColor(red: 0, green: 250, blue: 154),
"mediumturquoise": SVGColor(red: 72, green: 209, blue: 204),
"mediumvioletred": SVGColor(red: 199, green: 21, blue: 133),
"midnightblue": SVGColor(red: 25, green: 25, blue: 112),
"mintcream": SVGColor(red: 245, green: 255, blue: 250),
"mistyrose": SVGColor(red: 255, green: 228, blue: 225),
"moccasin": SVGColor(red: 255, green: 228, blue: 181),
"navajowhite": SVGColor(red: 255, green: 222, blue: 173),
"navy": SVGColor(red: 0, green: 0, blue: 128),
"oldlace": SVGColor(red: 253, green: 245, blue: 230),
"olive": SVGColor(red: 128, green: 128, blue: 0),
"olivedrab": SVGColor(red: 107, green: 142, blue: 35),
"orange": SVGColor(red: 255, green: 165, blue: 0),
"orangered": SVGColor(red: 255, green: 69, blue: 0),
"orchid": SVGColor(red: 218, green: 112, blue: 214),
"palegoldenrod": SVGColor(red: 238, green: 232, blue: 170),
"palegreen": SVGColor(red: 152, green: 251, blue: 152),
"paleturquoise": SVGColor(red: 175, green: 238, blue: 238),
"palevioletred": SVGColor(red: 219, green: 112, blue: 147),
"papayawhip": SVGColor(red: 255, green: 239, blue: 213),
"peachpuff": SVGColor(red: 255, green: 218, blue: 185),
"peru": SVGColor(red: 205, green: 133, blue: 63),
"pink": SVGColor(red: 255, green: 192, blue: 203),
"plum": SVGColor(red: 221, green: 160, blue: 221),
"powderblue": SVGColor(red: 176, green: 224, blue: 230),
"purple": SVGColor(red: 128, green: 0, blue: 128),
"red": SVGColor(red: 255, green: 0, blue: 0),
"rosybrown": SVGColor(red: 188, green: 143, blue: 143),
"royalblue": SVGColor(red: 65, green: 105, blue: 225),
"saddlebrown": SVGColor(red: 139, green: 69, blue: 19),
"salmon": SVGColor(red: 250, green: 128, blue: 114),
"sandybrown": SVGColor(red: 244, green: 164, blue: 96),
"seagreen": SVGColor(red: 46, green: 139, blue: 87),
"seashell": SVGColor(red: 255, green: 245, blue: 238),
"sienna": SVGColor(red: 160, green: 82, blue: 45),
"silver": SVGColor(red: 192, green: 192, blue: 192),
"skyblue": SVGColor(red: 135, green: 206, blue: 235),
"slateblue": SVGColor(red: 106, green: 90, blue: 205),
"slategray": SVGColor(red: 112, green: 128, blue: 144),
"slategrey": SVGColor(red: 112, green: 128, blue: 144),
"snow": SVGColor(red: 255, green: 250, blue: 250),
"springgreen": SVGColor(red: 0, green: 255, blue: 127),
"steelblue": SVGColor(red: 70, green: 130, blue: 180),
"tan": SVGColor(red: 210, green: 180, blue: 140),
"teal": SVGColor(red: 0, green: 128, blue: 128),
"thistle": SVGColor(red: 216, green: 191, blue: 216),
"tomato": SVGColor(red: 255, green: 99, blue: 71),
"turquoise": SVGColor(red: 64, green: 224, blue: 208),
"violet": SVGColor(red: 238, green: 130, blue: 238),
"wheat": SVGColor(red: 245, green: 222, blue: 179),
"white": SVGColor(red: 255, green: 255, blue: 255),
"whitesmoke": SVGColor(red: 245, green: 245, blue: 245),
"yellow": SVGColor(red: 255, green: 255, blue: 0),
"yellowgreen": SVGColor(red: 154, green: 205, blue: 50)
]
private var gColorValues: [SVGColor] = {
var toRet = [SVGColor]()
//var names = gColorDict.keys.array
let names = gColorNames
#if false
names.sort( {
return $0 < $1
})
#endif
for name in names {
toRet.append(gColorDict[name]!)
}
return toRet
}()
private let gColorNames = [
"aliceblue",
"antiquewhite",
"aqua",
"aquamarine",
"azure",
"beige",
"bisque",
"black",
"blanchedalmond",
"blue",
"blueviolet",
"brown",
"burlywood",
"cadetblue",
"chartreuse",
"chocolate",
"coral",
"cornflowerblue",
"cornsilk",
"crimson",
"cyan",
"darkblue",
"darkcyan",
"darkgoldenrod",
"darkgray",
"darkgreen",
"darkgrey",
"darkkhaki",
"darkmagenta",
"darkolivegreen",
"darkorange",
"darkorchid",
"darkred",
"darksalmon",
"darkseagreen",
"darkslateblue",
"darkslategray",
"darkslategrey",
"darkturquoise",
"darkviolet",
"deeppink",
"deepskyblue",
"dimgray",
"dimgrey",
"dodgerblue",
"firebrick",
"floralwhite",
"forestgreen",
"fuchsia",
"gainsboro",
"ghostwhite",
"gold",
"goldenrod",
"gray",
"green",
"greenyellow",
"grey",
"honeydew",
"hotpink",
"indianred",
"indigo",
"ivory",
"khaki",
"lavender",
"lavenderblush",
"lawngreen",
"lemonchiffon",
"lightblue",
"lightcoral",
"lightcyan",
"lightgoldenrodyellow",
"lightgray",
"lightgreen",
"lightgrey",
"lightpink",
"lightsalmon",
"lightseagreen",
"lightskyblue",
"lightslategray",
"lightslategrey",
"lightsteelblue",
"lightyellow",
"lime",
"limegreen",
"linen",
"magenta",
"maroon",
"mediumaquamarine",
"mediumblue",
"mediumorchid",
"mediumpurple",
"mediumseagreen",
"mediumslateblue",
"mediumspringgreen",
"mediumturquoise",
"mediumvioletred",
"midnightblue",
"mintcream",
"mistyrose",
"moccasin",
"navajowhite",
"navy",
"oldlace",
"olive",
"olivedrab",
"orange",
"orangered",
"orchid",
"palegoldenrod",
"palegreen",
"paleturquoise",
"palevioletred",
"papayawhip",
"peachpuff",
"peru",
"pink",
"plum",
"powderblue",
"purple",
"red",
"rosybrown",
"royalblue",
"saddlebrown",
"salmon",
"sandybrown",
"seagreen",
"seashell",
"sienna",
"silver",
"skyblue",
"slateblue",
"slategray",
"slategrey",
"snow",
"springgreen",
"steelblue",
"tan",
"teal",
"thistle",
"tomato",
"turquoise",
"violet",
"wheat",
"white",
"whitesmoke",
"yellow",
"yellowgreen"
]
class SwiftColor_Tests: 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()
}
lazy var SVGcolorDict: [String: SVGColor] = self.colorDictionary()
func colorDictionary() -> [String: SVGColor] {
var toRetArray = [String: SVGColor]()
for colorName in gColorNames {
toRetArray[colorName] = SVGColor(string: colorName)
}
return toRetArray
}
func testCColorPerformance() {
//measure the block for populating a color array with the C Function
self.measureBlock() {
var cLookupArray = [SVGColor]()
for strColor in gColorNames {
var aColor = SVGColorFromString(strColor)
cLookupArray.append(aColor)
}
}
}
func testCColorEquality() {
var cLookupArray = [SVGColor]()
for strColor in gColorNames {
var aColor = SVGColorFromString(strColor)
cLookupArray.append(aColor)
}
for i in 0 ..< cLookupArray.count {
XCTAssertEqual(cLookupArray[i], gColorValues[i])
}
XCTAssertEqual(cLookupArray, gColorValues)
}
func testSwiftColorPerformance() {
self.measureBlock() {
let colorDict = self.colorDictionary()
var swiftLookupArray = [SVGColor]()
for strColor in gColorNames {
if let aColor = colorDict[strColor] {
swiftLookupArray.append(aColor)
} else {
XCTAssert(false, "Got wrong value")
}
}
}
}
func testSwiftColorEquality() {
var swiftLookupArray = [SVGColor]()
for strColor in gColorNames {
if let aColor = SVGcolorDict[strColor] {
swiftLookupArray.append(aColor)
} else {
XCTAssert(false, "Got wrong value")
}
}
XCTAssertEqual(swiftLookupArray, gColorValues)
}
}
|
mit
|
8a4b4bb56c4b4be7588ac489aee2071e
| 30.022005 | 111 | 0.659915 | 2.709953 | false | false | false | false |
vowed21/HWSwiftyViewPager
|
HWSwiftyViewPagerDemo/HWSwiftyViewPagerDemo/FirstVC.swift
|
1
|
1434
|
//
// FirstVC.swift
// HWSwiftViewPager
//
// Created by HyunWoo Kim on 2016. 1. 11..
// Copyright © 2016년 KokohApps. All rights reserved.
//
import UIKit
class FirstVC: UIViewController, UICollectionViewDataSource, HWSwiftyViewPagerDelegate {
@IBOutlet weak var pager: HWSwiftyViewPager!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.pager.dataSource = self
self.pager.pageSelectedDelegate = self
}
//MARK: CollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FullCollectionCell", for: indexPath)
return cell
}
//MARK: HWSwiftyViewPagerDelegate
func pagerDidSelecedPage(_ selectedPage: Int) {
let string = "SectionInset Left,Right = 30\nminLineSpacing = 20\nSelectedPage = \(selectedPage)"
self.label.text = string
}
@IBAction func clickGoToPage0(_ sender: AnyObject) {
self.pager.setPage(pageNum: 0, isAnimation: false)
}
@IBAction func clickGoToPage2(_ sender: AnyObject) {
self.pager.setPage(pageNum: 2, isAnimation: true)
}
}
|
mit
|
1a61fb51317b83bb4fd53fc465c9a9ef
| 28.8125 | 121 | 0.686932 | 4.631068 | false | false | false | false |
ktakayama/SimpleRSSReader
|
Pods/RealmResultsController/Source/RealmResultsCache.swift
|
1
|
10237
|
//
// RealmResultsCache.swift
// redbooth-ios-sdk
//
// Created by Isaac Roldan on 4/8/15.
// Copyright © 2015 Redbooth Inc.
//
import Foundation
import RealmSwift
enum RealmCacheUpdateType: String {
case Move
case Update
case Insert
}
protocol RealmResultsCacheDelegate: class {
func didInsertSection<T: Object>(section: Section<T>, index: Int)
func didDeleteSection<T: Object>(section: Section<T>, index: Int)
func didInsert<T: Object>(object: T, indexPath: NSIndexPath)
func didUpdate<T: Object>(object: T, oldIndexPath: NSIndexPath, newIndexPath: NSIndexPath, changeType: RealmResultsChangeType)
func didDelete<T: Object>(object: T, indexPath: NSIndexPath)
}
/**
The Cache is responsible to store a copy of the current objects used by the RRC obtained by the original request.
It has an Array of sections where the objects are stored, always filtered and sorted by the request.
The array of sections is constructed depending on the SectionKeyPath given in the RRC creation.
When interacting with the cache is important to do it always in this order:
Taking into account that a MOVE is not an update but a pair of delete/insert operations.
- Deletions
- Insertions
- Updates (Only for objects that won't change position)
:important: always call the three methods, the operations are commited at the end
so calling only `delete` will change the cache but not call the delegate.
*/
class RealmResultsCache<T: Object> {
var request: RealmRequest<T>
var sectionKeyPath: String? = ""
var sections: [Section<T>] = []
let defaultKeyPathValue = "default"
weak var delegate: RealmResultsCacheDelegate?
var temporalDeletions: [T] = []
var temporalDeletionsIndexPath: [T: NSIndexPath] = [:]
//MARK: Initializer
init(request: RealmRequest<T>, sectionKeyPath: String?) {
self.request = request
self.sectionKeyPath = sectionKeyPath
}
//MARK: Population
func populateSections(objects: [T]) {
objects.forEach { getOrCreateSection($0).insert($0) }
sections.forEach { $0.sort() }
}
func reset(objects: [T]) {
sections.removeAll()
populateSections(objects)
}
//MARK: Actions
func insert(objects: [T]) {
let mirrorsArray = sortedMirrors(objects)
for object in mirrorsArray {
let section = getOrCreateSection(object) //Calls the delegate when there is an insertion
let rowIndex = section.insertSorted(object)
guard let sectionIndex = indexForSection(section) else { continue }
let indexPath = NSIndexPath(forRow: rowIndex, inSection: sectionIndex)
// If the object was not deleted previously, it is just an INSERT.
if !temporalDeletions.contains(object) {
delegate?.didInsert(object, indexPath: indexPath)
continue
}
// If the object was already deleted, then is a MOVE, and the insert/deleted
// should be wrapped in only one operation to the delegate
guard let oldIndexPath = temporalDeletionsIndexPath[object] else { continue }
delegate?.didUpdate(object, oldIndexPath: oldIndexPath, newIndexPath: indexPath, changeType: RealmResultsChangeType.Move)
guard let index = temporalDeletions.indexOf(object) else { continue }
temporalDeletions.removeAtIndex(index)
temporalDeletionsIndexPath.removeValueForKey(object)
}
// The remaining objects, not MOVED or INSERTED, are DELETES, and must be deleted at the end
for object in temporalDeletions {
guard let oldIndexPath = temporalDeletionsIndexPath[object] else { continue }
delegate?.didDelete(object, indexPath: oldIndexPath)
}
temporalDeletions.removeAll()
temporalDeletionsIndexPath.removeAll()
}
func delete(objects: [T]) {
var outdated: [T] = []
for object in objects {
guard let section = sectionForOutdateObject(object) else { continue }
guard let index = section.indexForOutdatedObject(object),
let object = section.objects.objectAtIndex(index) as? T else { continue }
outdated.append(object)
}
let mirrorsArray = sortedMirrors(outdated).reverse() as [T]
for object in mirrorsArray {
guard let section = sectionForOutdateObject(object),
let sectionIndex = indexForSection(section) else { continue }
guard let index = section.deleteOutdatedObject(object) else { continue }
let indexPath = NSIndexPath(forRow: index, inSection: sectionIndex)
temporalDeletions.append(object)
temporalDeletionsIndexPath[object] = indexPath
if section.objects.count == 0 {
sections.removeAtIndex(indexPath.section)
delegate?.didDeleteSection(section, index: indexPath.section)
}
}
}
func update(objects: [T]) {
for object in objects {
guard let oldSection = sectionForOutdateObject(object),
let oldSectionIndex = indexForSection(oldSection),
let oldIndexRow = oldSection.indexForOutdatedObject(object) else {
insert([object])
continue
}
let oldIndexPath = NSIndexPath(forRow: oldIndexRow, inSection: oldSectionIndex)
oldSection.deleteOutdatedObject(object)
let newIndexRow = oldSection.insertSorted(object)
let newIndexPath = NSIndexPath(forRow: newIndexRow, inSection: oldSectionIndex)
delegate?.didUpdate(object, oldIndexPath: oldIndexPath, newIndexPath: newIndexPath, changeType: .Update)
}
}
//MARK: Create
private func createNewSection(keyPath: String, notifyDelegate: Bool = true) -> Section<T> {
let newSection = Section<T>(keyPath: keyPath, sortDescriptors: request.sortDescriptors.map(toNSSortDescriptor))
sections.append(newSection)
sortSections()
let index = indexForSection(newSection)!
if notifyDelegate {
delegate?.didInsertSection(newSection, index: index)
}
return newSection
}
//MARK: Retrieve
private func getOrCreateSection(object: T) -> Section<T> {
let key = keyPathForObject(object)
guard let section = sectionForKeyPath(key) else {
return createNewSection(key)
}
return section
}
private func sectionForKeyPath(keyPath: String, create: Bool = true) -> Section<T>? {
let section = sections.filter{$0.keyPath == keyPath}
return section.first
}
private func sectionForOutdateObject(object: T) -> Section<T>? {
for section in sections {
if let _ = section.indexForOutdatedObject(object) {
return section
}
}
let key = keyPathForObject(object)
return sectionForKeyPath(key)
}
//MARK: Indexes
private func indexForSection(section: Section<T>) -> Int? {
return sections.indexOf(section)
}
//MARK: Helpers
/**
Given an object this method returns the type of update that this object will
perform in the cache: .Move, .Update or .Insert
:param: object Object to update
:returns: Type of the update needed for the given object
*/
func updateType(object: T) -> RealmCacheUpdateType {
//Sections
guard let oldSection = sectionForOutdateObject(object) else { return .Insert }
guard let newSection = sectionForKeyPath(keyPathForObject(object)) else { return .Insert }
//OutdatedCopy
guard let outdatedCopy = oldSection.outdatedObject(object) else { return .Insert }
//Indexes
guard let oldIndexRow = oldSection.delete(outdatedCopy) else { return .Insert }
let newIndexRow = newSection.insertSorted(object)
//Restore
newSection.delete(object)
oldSection.insertSorted(outdatedCopy)
if oldSection == newSection && oldIndexRow == newIndexRow {
return .Update
}
return .Move
}
func keyPathForObject(object: T) -> String {
var keyPathValue = defaultKeyPathValue
if let keyPath = sectionKeyPath {
if keyPath.isEmpty { return defaultKeyPathValue }
Threading.executeOnMainThread(true) {
if let objectKeyPathValue = object.valueForKeyPath(keyPath) {
keyPathValue = String(objectKeyPathValue)
}
}
}
return keyPathValue
}
/**
Sort an array of objects (mirrors of the original realm objects)
Using the SortDescriptors of the RealmRequest of the RRC.
:param: mirrors Objects to sort
:returns: sorted Array<T>
*/
private func sortedMirrors(mirrors: [T]) -> [T] {
let mutArray = NSMutableArray(array: mirrors)
let sorts = request.sortDescriptors.map(toNSSortDescriptor)
mutArray.sortUsingDescriptors(sorts)
guard let sortedMirrors = NSArray(array: mutArray) as? [T] else {
return []
}
return sortedMirrors
}
/**
Sort the sections using the Given KeyPath
*/
private func sortSections() {
guard let sortd = request.sortDescriptors.first else { return }
let comparator: NSComparisonResult = sortd.ascending ? .OrderedAscending : .OrderedDescending
sections.sortInPlace { $0.keyPath.localizedCaseInsensitiveCompare($1.keyPath) == comparator }
}
/**
Transforms a SortDescriptor into a NSSortDescriptor that can be applied to NSMutableArray
:param: sort SortDescriptor object
:returns: NSSortDescriptor
*/
private func toNSSortDescriptor(sort: SortDescriptor) -> NSSortDescriptor {
return NSSortDescriptor(key: sort.property, ascending: sort.ascending)
}
}
|
mit
|
8011cbd7c85bff36591370c43407062a
| 35.557143 | 133 | 0.642536 | 4.968932 | false | false | false | false |
googleprojectzero/fuzzilli
|
Sources/Fuzzilli/Base/Contributor.swift
|
1
|
4655
|
// Copyright 2020 Google LLC
//
// 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
//
// https://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.
/// Something that contributes to the creation of a program.
/// This class is used to compute detailed statistics about correctness and timeout rates as well as the number of interesting or crashing programs generated, etc.
public class Contributor {
// Number of valid programs produced (i.e. programs that run to completion)
private var validSamples = 0
// Number of interesting programs produces (i.e. programs that triggered new interesting behavior). All interesting programs are also valid.
private var interestingSamples = 0
// Number of invalid programs produced (i.e. programs that raised an exception or timed out)
private var invalidSamples = 0
// Number of produced programs that resulted in a timeout.
private var timedOutSamples = 0
// Number of crashing programs produced.
private var crashingSamples = 0
// Number of times this instance failed to generate/mutate code.
private var failures = 0
// Total number of instructions added to programs by this contributor.
private var totalInstructionProduced = 0
func generatedValidSample() {
validSamples += 1
}
func generatedInterestingSample() {
interestingSamples += 1
}
func generatedInvalidSample() {
invalidSamples += 1
}
func generatedTimeOutSample() {
timedOutSamples += 1
}
func generatedCrashingSample() {
crashingSamples += 1
}
func addedInstructions(_ n: Int) {
totalInstructionProduced += n
}
func failedToGenerate() {
failures += 1
}
public var crashesFound: Int {
return crashingSamples
}
public var totalSamples: Int {
return validSamples + interestingSamples + invalidSamples + timedOutSamples + crashingSamples
}
public var correctnessRate: Double {
guard totalSamples > 0 else { return 1.0 }
return Double(validSamples + interestingSamples) / Double(totalSamples)
}
public var interestingSamplesRate: Double {
guard totalSamples > 0 else { return 0.0 }
return Double(interestingSamples) / Double(totalSamples)
}
public var timeoutRate: Double {
guard totalSamples > 0 else { return 0.0 }
return Double(timedOutSamples) / Double(totalSamples)
}
public var failureRate: Double {
let totalAttempts = totalSamples + failures
guard totalAttempts > 0 else { return 0.0 }
return Double(failures) / Double(totalAttempts)
}
// Note: even if for example a CodeGenerator always generates exactly one instruction, this number may be
// slightly higher than one as the same CodeGenerator may run multiple times to generate one program.
public var avgNumberOfInstructionsGenerated: Double {
guard totalSamples > 0 else { return 0.0 }
return Double(totalInstructionProduced) / Double(totalSamples)
}
}
/// All "things" (Mutators, CodeGenerators, ProgramTemplates, ...) that contributed directly (i.e. not including parent programs) to the creation of a particular program.
public struct Contributors {
private var chain = [Contributor]()
public init() {}
public mutating func add(_ contributor: Contributor) {
// The chains should be pretty short, so a linear search is probably faster than using an additional Set.
if !chain.contains(where: { $0 === contributor}) {
chain.append(contributor)
}
}
public func generatedValidSample() {
chain.forEach { $0.generatedValidSample() }
}
public func generatedInterestingSample() {
chain.forEach { $0.generatedInterestingSample() }
}
public func generatedInvalidSample() {
chain.forEach { $0.generatedInvalidSample() }
}
public func generatedCrashingSample() {
chain.forEach { $0.generatedCrashingSample() }
}
public func generatedTimeOutSample() {
chain.forEach { $0.generatedTimeOutSample() }
}
public mutating func removeAll() {
chain.removeAll()
}
}
|
apache-2.0
|
fc46af64146d78e8ac13c8a1ca1e7c0b
| 32.978102 | 170 | 0.690226 | 4.813857 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformUIKit/Components/DigitPad/DigitPadButtonView.swift
|
1
|
1936
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import RxCocoa
import RxSwift
import UIKit
final class DigitPadButtonView: UIView {
// MARK: - UI Properties
@IBOutlet private var backgroundView: UIView!
@IBOutlet private var button: UIButton!
// MARK: - Rx
private let disposeBag = DisposeBag()
// MARK: - Injected
var viewModel: DigitPadButtonViewModel! {
didSet {
backgroundView.layer.cornerRadius = viewModel.background.cornerRadius
switch viewModel.content {
case .image(type: let image, tint: let color):
button.setImage(image.image, for: .normal)
button.imageView?.tintColor = color
case .label(text: let value, tint: let color):
button.setTitle(value, for: .normal)
button.setTitleColor(color, for: .normal)
case .none:
break
}
button.accessibility = viewModel.content.accessibility
// Bind button taps to the view model tap relay
button.rx.tap
.bindAndCatch(weak: self) { (self) in
self.viewModel.tap()
}
.disposed(by: disposeBag)
}
}
// MARK: - Setup
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
fromNib(in: .module)
button.titleLabel?.font = .main(.medium, 32)
backgroundView.clipsToBounds = true
backgroundColor = .clear
}
// MARK: - Button touches
@IBAction private func touchDown() {
backgroundView.backgroundColor = viewModel.background.highlightColor
}
@IBAction private func touchUp() {
backgroundView.backgroundColor = .clear
}
}
|
lgpl-3.0
|
4602b6fe153e34ea73966617bfc4783a
| 25.506849 | 81 | 0.58553 | 4.911168 | false | false | false | false |
yarshure/Surf
|
Surf/RecentReqViewController.swift
|
1
|
10462
|
//
// RecnetReqViewController.swift
// Surf
//
// Created by yarshure on 16/2/14.
// Copyright © 2016年 yarshure. All rights reserved.
//
import UIKit
import NetworkExtension
import SwiftyJSON
import SFSocket
import XRuler
import Xcon
import XProxy
class RecenetReqViewController: SFTableViewController {
var results:[SFRequestInfo] = []
var resultsFin:[SFRequestInfo] = []
var dbURL:URL?
let report:SFVPNStatistics = SFVPNStatistics.shared
var session:String = ""
var refreshTime = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: 0), queue: DispatchQueue.main)
func installTimer(){
refreshTime.schedule(deadline: .now(), repeating: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.seconds(1))
refreshTime.setEventHandler {
[weak self] in
let data = SFTCPConnectionManager.shared.recentRequestData()
self?.processData(data: data)
//self?.reportTask()
}
refreshTime.setCancelHandler {
print("timer cancel......")
}
refreshTime.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Recent Requests"
recent()
installTimer()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
let item = UIBarButtonItem.init(image: UIImage.init(named: "760-refresh-3-toolbar"), style: .plain, target: self, action: #selector(RecenetReqViewController.refreshAction(_:)))
self.navigationItem.setRightBarButtonItems([item], animated: false)
}
//sharedb feature 废弃,使用session 中的share
@objc func refreshAction(_ sender:AnyObject){
recent()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !verifyReceipt(.Analyze) {
changeToBuyPage()
return
}
}
func requests() {
if ProxyGroupSettings.share.historyEnable{
//resultsFin.removeAll()
if !session.isEmpty {
dbURL = RequestHelper.shared.openForApp(session)
}
resultsFin = RequestHelper.shared.fetchAll()
}
}
func test() {
let path = Bundle.main.path(forResource: "1.txt", ofType: nil)
if let _ = NSData.init(contentsOfFile: path!) {
}
}
func recent(){
// Send a simple IPC message to the provider, handle the response.
//AxLogger.log("send Hello Provider")
//var rpc = false
if let m = SFVPNManager.shared.manager {
let date = Date()
let me = SFVPNXPSCommand.RECNETREQ.rawValue + "|\(date)"
if let session = m.connection as? NETunnelProviderSession,
let message = me.data(using: .utf8), m.connection.status == .connected
{
do {
//rpc = true
try session.sendProviderMessage(message) {[weak self] response in
guard let s = self else {return}
if response != nil {
//let responseString = NSString(data: response!, encoding: NSUTF8StringEncoding)
//mylog("Received response from the provider: \(responseString)")
s.processData(data: response!)
//self.registerStatus()
} else {
s.alertMessageAction("Got a nil response from the provider",complete: nil)
}
}
} catch {
alertMessageAction("Failed to send a message to the provider",complete: nil)
}
}
}
}
func processData(data:Data) {
results.removeAll()
//let responseString = NSString(data: response!, encoding: NSUTF8StringEncoding)
let obj = try! JSON.init(data: data)
if obj.error == nil {
let count = obj["count"]
self.session = obj["session"].stringValue
//print("recent request count:\(count.stringValue)")
if count.intValue != 0 {
//alertMessageAction("Don't have Record yet!",complete: nil)
//return
let result = obj["data"]
if result.type == .array {
for item in result {
let json = item.1
let r = SFRequestInfo.init(rID: 0)
r.map(json)
results.append(r)
}
}
if results.count > 0 {
results.sort(by: { $0.sTime.compare($1.sTime as Date) == ComparisonResult.orderedDescending })
}
}
}
requests()
tableView.reloadData()
//mmlog("Received response from the provider: \(responseString)")
//self.registerStatus()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
if ProxyGroupSettings.share.historyEnable{
return 2
}
return 1
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if ProxyGroupSettings.share.historyEnable{
if section == 0 {
return "Active REQUESTS"
}
return "RENCENT REQUESTS"
}else {
return "Active REQUESTS"
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0 {
if results.count == 0 {
return 1
}
return results.count
}else {
return resultsFin.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "recent", for: indexPath)
cell.updateStandUI()
// Configure the cell...
var request:SFRequestInfo?
if indexPath.section == 0 {
if indexPath.row < results.count {
request = results[indexPath.row]
}
}else {
request = resultsFin[indexPath.row]
}
if let request = request{
cell.detailTextLabel?.textColor = UIColor.lightGray
cell.textLabel?.text = request.url //+ " " + String(request.reqID) + " " + String(request.subID)
cell.detailTextLabel?.attributedText = request.detailString()
}else {
cell.textLabel?.text = "Session Not Start".localized
if let m = SFVPNManager.shared.manager {
if m.connection.status == .connected {
cell.textLabel?.text = "Session Running"
}
}
cell.detailTextLabel?.text = ""
}
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
if segue.identifier == "requestDetail" {
guard let detail = segue.destination as? RequestDetailViewController else{return}
guard let indexPath = self.tableView.indexPath(for: sender as! UITableViewCell) else {return }
var request:SFRequestInfo
if indexPath.section == 0 {
if results.count == 0 {
return
}else {
request = results[indexPath.row]
}
}else {
request = resultsFin[indexPath.row]
}
if request.url.isEmpty {
alertMessageAction("Request url empty", complete: nil)
}else {
detail.request = request
}
}
}
}
|
bsd-3-clause
|
bb0f106901745e6d101bbc4b799155b1
| 33.700997 | 184 | 0.555864 | 5.331802 | false | false | false | false |
EugeneVegner/sws-copyleaks-sdk-test
|
PlagiarismChecker/Classes/Copyleaks.swift
|
1
|
3105
|
/*
* The MIT License(MIT)
*
* Copyright(c) 2016 Copyleaks LTD (https://copyleaks.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
public class Copyleaks: NSObject {
/**
You can test the integration with Copyleaks API for free using the sandbox mode.
You will be able to submit content to scan and get back mock results, simulating
the way Copyleaks will work.
*/
private var _sandboxMode: Bool = false
public var sandboxMode: Bool {
get {
return _sandboxMode
}
}
/* Product type */
private var _productType: CopyleaksProductType?
public var productType: CopyleaksProductType? {
get {
return _productType
}
}
/* Default Accept Language */
private var _acceptLanguage: String?
public var acceptLanguage: String? {
get {
return _acceptLanguage
}
}
class var sharedSDK: Copyleaks {
struct Static {
static var instance: Copyleaks?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = Copyleaks()
}
return Static.instance!
}
public class func configure(
sandboxMode mode: Bool,
product: CopyleaksProductType,
preferLanguage: String = CopyleaksConst.defaultAcceptLanguage)
{
self.sharedSDK._sandboxMode = mode
self.sharedSDK._productType = product
self.sharedSDK._acceptLanguage = preferLanguage
}
public class func setProduct(product: CopyleaksProductType) {
self.sharedSDK._productType = product
}
/* Logout and clear Token info. */
public class func logout(success: () -> Void) {
CopyleaksToken.clear()
success()
}
public class func isAuthorized() -> Bool {
guard let token = CopyleaksToken.getAccessToken() else {
return false
}
return token.isValid()
}
}
|
mit
|
bb8968851b63a2f8d839aeffcbbae446
| 28.292453 | 85 | 0.651852 | 4.866771 | false | false | false | false |
venkatamacha/google_password_manager
|
google_password_manager/google_password_manager/UserPassword.swift
|
1
|
2724
|
//
// UserPassword.swift
// google_password_manager
//
// Created by Venkata Macha on 8/14/16.
// Copyright © 2016 Venkata Macha. All rights reserved.
//
import Foundation
class UserPassword: NSObject {
var uuid: String
var service: String
var user: String?
var pass: String?
var notes: String?
init(uuid: String?, service: String, user: String?, pass: String?, notes: String?){
self.uuid = uuid ?? NSUUID().UUIDString
self.service = service
self.user = user
self.pass = pass
self.notes = notes
}
func textVersion() -> String{
if service == "" {
service = "Untitled"
}
if user == "" {
user = "!@#$%^&*()"
}
if pass == "" {
pass = "!@#$%^&*()"
}
if notes == "" {
notes = "!@#$%^&*()"
}
return (uuid + "," +
service + "," +
user! + "," +
pass! + "," +
notes!)
}
func deleteSelfFromFile(vc: PasswordsViewController){
var userPasswordTexts = vc.fileText.characters.split{$0 == ";"}.map(String.init)
userPasswordTexts = userPasswordTexts.filter{!$0.hasPrefix(uuid)}
vc.fileText = userPasswordTexts.joinWithSeparator(";")
}
func insertSelfIntoFile(vc: PasswordsViewController){
var userPasswordTexts = vc.fileText.characters.split{$0 == ";"}.map(String.init)
userPasswordTexts.append(textVersion())
vc.fileText = userPasswordTexts.joinWithSeparator(";")
}
static func generatePasswordDictionary(vc: PasswordsViewController) -> [Character: [UserPassword]]{
var passwordDictionary: [Character: [UserPassword]] = [:]
let userPasswordTexts = vc.fileText.characters.split{$0 == ";"}.map(String.init)
for text in userPasswordTexts {
let userPasswordFields = text.characters.split{$0 == ","}.map(String.init).map{(s1: String) -> String? in if s1 == "!@#$%^&*()" {return nil} else {return s1}}
let userPassword = UserPassword.init(uuid: userPasswordFields[0]!, service: userPasswordFields[1]!, user: userPasswordFields[2], pass: userPasswordFields[3], notes: userPasswordFields[4])
let firstCharacter = userPassword.service.uppercaseString[userPassword.service.startIndex]
if passwordDictionary[firstCharacter] != nil {
passwordDictionary[firstCharacter]!.append(userPassword)
} else {
passwordDictionary[firstCharacter] = [userPassword]
}
}
return passwordDictionary
}
}
|
mit
|
ba12b9e1352c69f30ac107ef9bab0533
| 33.05 | 199 | 0.569592 | 4.576471 | false | false | false | false |
pvbaleeiro/movie-aholic
|
movieaholic/movieaholic/controller/base/BaseTableViewController.swift
|
1
|
6347
|
//
// BaseTableViewController.swift
// movieaholic
//
// Created by Victor Baleeiro on 24/09/17.
// Copyright © 2017 Victor Baleeiro. All rights reserved.
//
import UIKit
//-------------------------------------------------------------------------------------------------------------
// MARK: Delegate
//-------------------------------------------------------------------------------------------------------------
protocol BaseTableControllerDelegate {
var headerViewHeightConstraint: NSLayoutConstraint? { get set }
var headerView: ExploreHeaderView { get set }
var maxHeaderHeight: CGFloat { get }
var midHeaderHeight: CGFloat { get }
var minHeaderHeight: CGFloat { get }
func layoutViews()
func updateStatusBar()
}
class BaseTableController: UIViewController {
//-------------------------------------------------------------------------------------------------------------
// MARK: Propriedades
//-------------------------------------------------------------------------------------------------------------
var headerDelegate: BaseTableControllerDelegate!
var previousScrollOffset: CGFloat = 0
var isHiddenStatusBar: Bool = false
var statusBarStyle: UIStatusBarStyle = .lightContent
//-------------------------------------------------------------------------------------------------------------
// MARK: Ciclo de vida
//-------------------------------------------------------------------------------------------------------------
override func didMove(toParentViewController parent: UIViewController?) {
if let del = parent as? BaseTableControllerDelegate {
self.headerDelegate = del
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.statusBarStyle = .default
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .fade
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return statusBarStyle
}
override var prefersStatusBarHidden: Bool {
return isHiddenStatusBar
}
func setStatusBarHidden(_ isHidden: Bool, withStyle style: UIStatusBarStyle) {
if isHidden != isHiddenStatusBar || statusBarStyle != style {
statusBarStyle = style
isHiddenStatusBar = isHidden
UIView.animate(withDuration: 0.5, animations: {
self.headerDelegate.updateStatusBar()
})
}
}
func updateStatusBar() {
let curHeight = headerDelegate.headerViewHeightConstraint!.constant
if curHeight == headerDelegate.minHeaderHeight {
setStatusBarHidden(false, withStyle: .default)
} else if curHeight > headerDelegate.minHeaderHeight, curHeight < headerDelegate.midHeaderHeight {
setStatusBarHidden(true, withStyle: .lightContent)
} else {
setStatusBarHidden(false, withStyle: .lightContent)
}
}
}
//-------------------------------------------------------------------------------------------------------------
// MARK: UITableViewDelegate
//-------------------------------------------------------------------------------------------------------------
extension BaseTableController: UITableViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let absoluteTop: CGFloat = 0
let absoluteBottom: CGFloat = max(0, scrollView.contentSize.height - scrollView.frame.height)
let scrollDif = scrollView.contentOffset.y - previousScrollOffset
let isScrollUp = scrollDif < 0 && scrollView.contentOffset.y < absoluteBottom // swipe down - header expands
let isScrollDown = scrollDif > 0 && scrollView.contentOffset.y > absoluteTop // swipe up - header shrinks
var newHeight = headerDelegate.headerViewHeightConstraint!.constant
if isScrollUp {
newHeight = min(headerDelegate.maxHeaderHeight, (headerDelegate.headerViewHeightConstraint!.constant + abs(scrollDif)))
} else if isScrollDown {
newHeight = max(headerDelegate.minHeaderHeight, (headerDelegate.headerViewHeightConstraint!.constant - abs(scrollDif)))
}
if newHeight != headerDelegate.headerViewHeightConstraint!.constant {
headerDelegate.headerViewHeightConstraint?.constant = newHeight
headerDelegate.headerView.updateHeader(newHeight: newHeight, offset: scrollDif)
setScrollPosition(scrollView, toPosition: previousScrollOffset)
updateStatusBar()
}
previousScrollOffset = scrollView.contentOffset.y
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollViewDidStopScrolling(scrollView)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
scrollViewDidStopScrolling(scrollView)
}
}
func setScrollPosition(_ scrollView: UIScrollView, toPosition position: CGFloat) {
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: position)
}
func scrollViewDidStopScrolling(_ scrollView: UIScrollView) {
let curHeight = headerDelegate.headerViewHeightConstraint!.constant
if curHeight < headerDelegate.midHeaderHeight {
setHeaderHeight(scrollView, height: headerDelegate.minHeaderHeight)
} else if curHeight < headerDelegate.maxHeaderHeight - headerDelegate.headerView.headerInputHeight {
setHeaderHeight(scrollView, height: headerDelegate.midHeaderHeight)
} else {
setHeaderHeight(scrollView, height: headerDelegate.maxHeaderHeight)
}
updateStatusBar()
}
func setHeaderHeight(_ scrollView: UIScrollView, height: CGFloat) {
self.headerDelegate.layoutViews()
UIView.animate(withDuration: 0.2, animations: {
self.headerDelegate.headerViewHeightConstraint?.constant = height
self.headerDelegate.headerView.updateHeader(newHeight: height, offset: scrollView.contentOffset.y - self.previousScrollOffset)
self.headerDelegate.layoutViews()
})
}
}
|
mit
|
90bf666fcdaa90b411db230d201ed816
| 40.75 | 138 | 0.586354 | 6.258383 | false | false | false | false |
rsmoz/swift-corelibs-foundation
|
Foundation/NSProcessInfo.swift
|
1
|
5560
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
import CoreFoundation
public struct NSOperatingSystemVersion {
public var majorVersion: Int
public var minorVersion: Int
public var patchVersion: Int
public init() {
self.init(majorVersion: 0, minorVersion: 0, patchVersion: 0)
}
public init(majorVersion: Int, minorVersion: Int, patchVersion: Int) {
self.majorVersion = majorVersion
self.minorVersion = minorVersion
self.patchVersion = patchVersion
}
}
public extension NSOperatingSystemVersion : Comparable {
public init(_ majorVersion: Int, _ minorVersion: Int, _ patchVersion: Int) {
self.init(majorVersion: majorVersion, minorVersion: minorVersion, patchVersion: patchVersion)
}
}
public func ==(lhs: NSOperatingSystemVersion, rhs: NSOperatingSystemVersion) -> Bool {
let lhsTuple = (lhs.majorVersion, lhs.minorVersion, lhs.patchVersion)
let rhsTuple = (rhs.majorVersion, rhs.minorVersion, rhs.patchVersion)
return lhsTuple == rhsTuple
}
public func <(lhs: NSOperatingSystemVersion, rhs: NSOperatingSystemVersion) -> Bool {
let lhsTuple = (lhs.majorVersion, lhs.minorVersion, lhs.patchVersion)
let rhsTuple = (rhs.majorVersion, rhs.minorVersion, rhs.patchVersion)
return lhsTuple < rhsTuple
}
public class NSProcessInfo : NSObject {
internal static let _processInfo = NSProcessInfo()
public class func processInfo() -> NSProcessInfo {
return _processInfo
}
internal override init() {
}
internal static var _environment: [String : String] = {
let dict = __CFGetEnvironment()._nsObject
var env = [String : String]()
dict.enumerateKeysAndObjectsUsingBlock { key, value, stop in
env[(key as! NSString)._swiftObject] = (value as! NSString)._swiftObject
}
return env
}()
public var environment: [String : String] {
return NSProcessInfo._environment
}
public var arguments: [String] {
return Process.arguments // seems reasonable to flip the script here...
}
public var hostName: String {
get {
if let name = NSHost.currentHost().name {
return name
} else {
return "localhost"
}
}
}
public var processName: String = _CFProcessNameString()._swiftObject
public var processIdentifier: Int32 {
get {
return __CFGetPid()
}
}
public var globallyUniqueString: String {
get {
let uuid = CFUUIDCreate(kCFAllocatorSystemDefault)
return CFUUIDCreateString(kCFAllocatorSystemDefault, uuid)._swiftObject
}
}
public var operatingSystemVersionString: String {
get {
return CFCopySystemVersionString()?._swiftObject ?? "Unknown"
}
}
public var operatingSystemVersion: NSOperatingSystemVersion {
get {
// The following fallback values match Darwin Foundation
let fallbackMajor = -1
let fallbackMinor = 0
let fallbackPatch = 0
guard let systemVersionDictionary = _CFCopySystemVersionDictionary() else {
return NSOperatingSystemVersion(majorVersion: fallbackMajor, minorVersion: fallbackMinor, patchVersion: fallbackPatch)
}
let productVersionKey = unsafeBitCast(_kCFSystemVersionProductVersionKey, UnsafePointer<Void>.self)
guard let productVersion = unsafeBitCast(CFDictionaryGetValue(systemVersionDictionary, productVersionKey), NSString!.self) else {
return NSOperatingSystemVersion(majorVersion: fallbackMajor, minorVersion: fallbackMinor, patchVersion: fallbackPatch)
}
let versionComponents = productVersion._swiftObject.characters.split(".").flatMap(String.init).flatMap({ Int($0) })
let majorVersion = versionComponents.dropFirst(0).first ?? fallbackMajor
let minorVersion = versionComponents.dropFirst(1).first ?? fallbackMinor
let patchVersion = versionComponents.dropFirst(2).first ?? fallbackPatch
return NSOperatingSystemVersion(majorVersion: majorVersion, minorVersion: minorVersion, patchVersion: patchVersion)
}
}
internal let _processorCount = __CFProcessorCount()
public var processorCount: Int {
get {
return Int(_processorCount)
}
}
internal let _activeProcessorCount = __CFActiveProcessorCount()
public var activeProcessorCount: Int {
get {
return Int(_activeProcessorCount)
}
}
internal let _physicalMemory = __CFMemorySize()
public var physicalMemory: UInt64 {
get {
return _physicalMemory
}
}
public func isOperatingSystemAtLeastVersion(version: NSOperatingSystemVersion) -> Bool {
return operatingSystemVersion >= version
}
public var systemUptime: NSTimeInterval {
get {
return CFGetSystemUptime()
}
}
}
|
apache-2.0
|
44d624405198318abc90f5ad485a9f48
| 31.899408 | 141 | 0.651259 | 5.235405 | false | false | false | false |
byu-oit/ios-byuSuite
|
byuSuite/Apps/Vending/controller/VendingCategoriesViewController.swift
|
1
|
961
|
//
// VendingCategoriesViewController.swift
// byuSuite
//
// Created by Alex Boswell on 1/4/18.
// Copyright © 2018 Brigham Young University. All rights reserved.
//
import UIKit
class VendingCategoriesViewController: ByuTableDataViewController {
override func viewDidLoad() {
super.viewDidLoad()
VendingClient.getAllCategories { (categories, error) in
self.spinner?.stopAnimating()
if let categories = categories {
self.tableData = TableData(rows: categories.map { Row(text: $0.desc, object: $0) })
self.tableView.reloadData()
} else {
super.displayAlert(error: error)
}
}
tableView.hideEmptyCells()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToProducts",
let vc = segue.destination as? VendingProductsViewController,
let category: VendingCategory = objectForSender(tableView: tableView, cellSender: sender) {
vc.category = category
}
}
}
|
apache-2.0
|
3b912dc6c929e7180337159453472a23
| 25.666667 | 94 | 0.719792 | 3.779528 | false | false | false | false |
coinbase/coinbase-ios-sdk
|
Example/Source/ViewControllers/Authorization/Views/GradientView/GradientView.swift
|
1
|
1199
|
//
// GradientView.swift
// iOS Example
//
// Copyright © 2018 Coinbase All rights reserved.
//
import UIKit
class GradientView: UIView {
// MARK: - Properties
public var gradientColors: GradientColors? {
didSet {
backgroundColor = gradientColors?.middleColor
}
}
private var gradientLayer: CAGradientLayer?
// MARK: - Lifecycle Methods
override func layoutSubviews() {
super.layoutSubviews()
if gradientLayer == nil {
addGradientLayer()
}
gradientLayer?.frame = bounds
}
// MARK: - Private Methods
private func addGradientLayer() {
gradientLayer = CAGradientLayer()
createGradientLayer()
layer.insertSublayer(gradientLayer!, at: 0)
}
private func createGradientLayer() {
gradientLayer = CAGradientLayer()
if let gradientColors = gradientColors {
gradientLayer?.colors = [gradientColors.start.cgColor, gradientColors.end.cgColor]
}
gradientLayer?.startPoint = CGPoint(x: 0, y: 0)
gradientLayer?.endPoint = CGPoint(x: 0, y: 1)
}
}
|
apache-2.0
|
0fb6b63d9b3a34fd2f405d7c08436f87
| 22.490196 | 94 | 0.592654 | 5.277533 | false | false | false | false |
pauljohanneskraft/Math
|
CoreMath/Classes/Functions/TrigonometricFunction.swift
|
1
|
2617
|
//
// TrigonometricFunction.swift
// Math
//
// Created by Paul Kraft on 13.12.17.
// Copyright © 2017 pauljohanneskraft. All rights reserved.
//
import Foundation
extension TrigonometricFunction {
public enum Kind {
case sin, sinh
case cos, cosh
public var function: (Double) -> Double {
switch self {
case .sin:
return Darwin.sin
case .cos:
return Darwin.cos
case .sinh:
return Darwin.sinh
case .cosh:
return Darwin.cosh
}
}
var integral: (sign: Bool, kind: Kind) {
switch self {
case .sin:
return (true, .cos)
case .cos:
return (false, .sin)
case .sinh:
return (false, .cosh)
case .cosh:
return (false, .sinh)
}
}
var derivative: (sign: Bool, kind: Kind) {
switch self {
case .sin:
return (false, .cos)
case .cos:
return (true, .sin)
case .sinh:
return (false, .cosh)
case .cosh:
return (false, .sinh)
}
}
func call(content: Double) -> Double {
return self.function(content)
}
}
}
public struct TrigonometricFunction {
public var content: Function
public var kind: Kind
public init(content: Function, kind: Kind) {
self.content = content
self.kind = kind
}
}
extension TrigonometricFunction: Function {
public var integral: Function {
let (sign, int) = kind.integral
return (sign ? -1 : 1.0) * TrigonometricFunction(content: content, kind: int) / content.derivative
}
public var derivative: Function {
let (sign, der) = kind.derivative
return (sign ? -1 : 1.0) * TrigonometricFunction(content: content, kind: der) * content.derivative
}
public var reduced: Function {
return self
}
public func call(x: Double) -> Double {
let c = content.call(x: x)
return kind.call(content: c)
}
public func equals(to: Function) -> Bool {
guard let other = to as? TrigonometricFunction else { return false }
return other.kind == kind && other.content == content
}
}
extension TrigonometricFunction: CustomStringConvertible {
public var description: String {
return "\(kind)(\(content))"
}
}
|
mit
|
87b9bf4b2e2c9b3b2ed0e0e431db1b21
| 24.90099 | 106 | 0.51682 | 4.525952 | false | false | false | false |
PumpMagic/ostrich
|
gameboy/gameboy/Source/CPUs/Instructions/SLA.swift
|
1
|
1940
|
//
// SLA.swift
// ostrichframework
//
// Created by Ryan Conway on 4/21/16.
// Copyright © 2016 Ryan Conway. All rights reserved.
//
import Foundation
/// Arithmetic left shift into carry flag
struct SLA<T: Writeable & Readable & OperandType>: Z80Instruction, LR35902Instruction where T.ReadType == T.WriteType, T.ReadType == UInt8
{
let op: T
let cycleCount = 0
fileprivate func runCommon(_ cpu: Intel8080Like) -> (UInt8, UInt8) {
let oldValue = op.read()
let newValue = shiftLeft(oldValue)
op.write(newValue)
return (oldValue, newValue)
}
func runOn(_ cpu: Z80) {
let (oldValue, newValue) = runCommon(cpu)
modifyFlags(cpu, oldValue: oldValue, newValue: newValue)
}
func runOn(_ cpu: LR35902) {
let (oldValue, newValue) = runCommon(cpu)
modifyFlags(cpu, oldValue: oldValue, newValue: newValue)
}
fileprivate func modifyCommonFlags(_ cpu: Intel8080Like, oldValue: UInt8, newValue: UInt8) {
// Z is set if result is 0; otherwise, it is reset.
// H is reset.
// N is reset.
// C is data from bit 7.
cpu.ZF.write(newValue == 0x00)
cpu.HF.write(false)
cpu.NF.write(false)
cpu.CF.write(bitIsHigh(oldValue, bit: 7))
}
fileprivate func modifyFlags(_ cpu: Z80, oldValue: UInt8, newValue: UInt8) {
modifyCommonFlags(cpu, oldValue: oldValue, newValue: newValue)
// S is set if result is negative; otherwise, it is reset.
// P/V is set if parity is even; otherwise, it is reset.
cpu.SF.write(numberIsNegative(newValue))
cpu.PVF.write(parity(newValue))
}
fileprivate func modifyFlags(_ cpu: LR35902, oldValue: UInt8, newValue: UInt8) {
modifyCommonFlags(cpu, oldValue: oldValue, newValue: newValue)
}
}
|
mit
|
83330bfe2a85ec871da86eae81447e10
| 27.940299 | 138 | 0.604951 | 3.870259 | false | false | false | false |
soapyigu/LeetCode_Swift
|
Stack/TernaryExpressionParser.swift
|
1
|
950
|
/**
* Question Link: https://leetcode.com/problems/ternary-expression-parser/
* Primary idea: Use a stack and go from right to left, pop when peek is "?"
* Time Complexity: O(n), Space Complexity: O(n)
*/
class TernaryExpressionParser {
func parseTernary(_ expression: String) -> String {
var stack = [Character]()
for char in expression.characters.reversed() {
if !stack.isEmpty && stack.last! == "?" {
stack.removeLast()
let first = stack.removeLast()
stack.removeLast()
let second = stack.removeLast()
if char == "T" {
stack.append(first)
} else {
stack.append(second)
}
} else {
stack.append(char)
}
}
return stack.isEmpty ? "" : String(stack.last!)
}
}
|
mit
|
4c0cd15bfa9098caa716e94bb38178eb
| 29.677419 | 76 | 0.485263 | 4.846939 | false | false | false | false |
yeziahehe/CYSwiftFramework
|
CYSwiftFramework/Utils/Extension/UIColor+CY.swift
|
1
|
4089
|
//
// UIColor+CY.swift
// CYSwiftFramework
//
// Created by JF on 16/5/19.
// Copyright © 2016年 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
/**
Create non-autoreleased color with in the given hex string
Alpha will be set as 1 by default
- parameter hexString:
- returns: color with the given hex string
*/
public convenience init?(hexString: String) {
self.init(hexString: hexString, alpha: 1.0)
}
/**
Create non-autoreleased color with in the given hex string and alpha
- parameter hexString:
- parameter alpha:
- returns: color with the given hex string and alpha
*/
public convenience init?(hexString: String, alpha: Float) {
var hex = hexString
// Check for hash and remove the hash
if hex.hasPrefix("#") {
hex = hex.substringFromIndex(hex.startIndex.advancedBy(1))
}
//if let match = hex.rangeOfString("(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .RegularExpressionSearch) {
if let _ = hex.rangeOfString("(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .RegularExpressionSearch) {
// Deal with 3 character Hex strings
if hex.characters.count == 3 {
let redHex = hex.substringToIndex(hex.startIndex.advancedBy(1))
//let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(1), end: hex.startIndex.advancedBy(2)))
let greenHex = hex.substringWithRange(hex.startIndex.advancedBy(1) ..< hex.startIndex.advancedBy(2))
let blueHex = hex.substringFromIndex(hex.startIndex.advancedBy(2))
hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex
}
let redHex = hex.substringToIndex(hex.startIndex.advancedBy(2))
// let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(2), end: hex.startIndex.advancedBy(4)))
let greenHex = hex.substringWithRange(hex.startIndex.advancedBy(2) ..< hex.startIndex.advancedBy(4))
// let blueHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(4), end: hex.startIndex.advancedBy(6)))
let blueHex = hex.substringWithRange(hex.startIndex.advancedBy(4) ..< hex.startIndex.advancedBy(6))
var redInt: CUnsignedInt = 0
var greenInt: CUnsignedInt = 0
var blueInt: CUnsignedInt = 0
NSScanner(string: redHex).scanHexInt(&redInt)
NSScanner(string: greenHex).scanHexInt(&greenInt)
NSScanner(string: blueHex).scanHexInt(&blueInt)
self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: CGFloat(alpha))
}
else {
// Note:
// The swift 1.1 compiler is currently unable to destroy partially initialized classes in all cases,
// so it disallows formation of a situation where it would have to. We consider this a bug to be fixed
// in future releases, not a feature. -- Apple Forum
self.init()
return nil
}
}
/**
Create non-autoreleased color with in the given hex value
Alpha will be set as 1 by default
- parameter hex:
- returns: color with the given hex value
*/
public convenience init?(hex: Int) {
self.init(hex: hex, alpha: 1.0)
}
/**
Create non-autoreleased color with in the given hex value and alpha
- parameter hex:
- parameter alpha:
- returns: color with the given hex value and alpha
*/
public convenience init?(hex: Int, alpha: Float) {
let hexString = NSString(format: "%2X", hex)
self.init(hexString: hexString as String , alpha: alpha)
}
}
|
mit
|
a219ed8e33df2b55fdb86bce69a866b8
| 40.282828 | 156 | 0.605972 | 4.465574 | false | false | false | false |
suzp1984/IOS-ApiDemo
|
ApiDemo-Swift/ApiDemo-Swift/ScrollSamplesViewController.swift
|
1
|
2614
|
//
// ScrollSamplesViewController.swift
// ApiDemo-Swift
//
// Created by Jacob su on 7/26/16.
// Copyright © 2016 [email protected]. All rights reserved.
//
import UIKit
class ScrollSamplesViewController: UIViewController, UINavigationControllerDelegate,
UITableViewDelegate, UITableViewDataSource {
let cellIdentifier = "ScrollsSample"
let demos: [String] = ["AutoSizeable ScrollView", "AutoLayout ScrollView", "Content ScrollView"]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Scroll Views"
let table = UITableView(frame: self.view.bounds)
table.delegate = self
table.dataSource = self
table.backgroundColor = UIColor.cyan
self.view.addSubview(table)
self.navigationItem.leftItemsSupplementBackButton = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return demos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell : UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil {
cell = UITableViewCell(style:.default, reuseIdentifier:cellIdentifier)
cell.textLabel!.textColor = UIColor.white
let v2 = UIView() // no need to set frame
v2.backgroundColor = UIColor.blue.withAlphaComponent(0.2)
cell.selectedBackgroundView = v2
// next line didn't work until iOS 7!
cell.backgroundColor = UIColor.red
}
cell.textLabel!.text = demos[(indexPath as NSIndexPath).row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch demos[(indexPath as NSIndexPath).row] {
case demos[0]:
self.navigationController?.pushViewController(AutoResizeScrollViewController(), animated: true)
case demos[1]:
self.navigationController?.pushViewController(AutoLayoutScrollViewController(), animated: true)
case demos[2]:
self.navigationController?.pushViewController(ContentScrollViewController(), animated: true)
default:
break
}
}
}
|
apache-2.0
|
857dbbf7f564313f4d90178bfc6b712a
| 33.84 | 107 | 0.645235 | 5.489496 | false | false | false | false |
siejkowski/one60sms
|
onesixty/Source/TestingHelpers/TestDependencyProvider.swift
|
2
|
1543
|
import Foundation
@testable
import onesixty
struct TestDependencyProvider: DependencyProvider {
typealias AnyType = Any.Type
let types: [AnyType]
let initializers: [() -> Any]
init(types: [AnyType], initializers: [() -> Any]) {
self.types = types
self.initializers = initializers
}
func initializeIfPossible<Service>(serviceType: Service.Type) -> Service? {
guard let index = self.types.indexOf({ elem in serviceType == elem }) else { return .None }
let closure: (() -> Any)? = self.initializers[index]
return closure.map { $0() as! Service }
}
func resolveWithError<Service>(serviceType: Service.Type) throws -> Service {
guard let service = initializeIfPossible(serviceType) else { throw InjectionError("") }
return service
}
func resolveWithError<Service>(serviceType: Service.Type, name: String?) throws -> Service {
throw InjectionError("")
}
func resolveWithError<Service, Arg1>(serviceType: Service.Type, argument: Arg1) throws -> Service {
throw InjectionError("")
}
func provide<Service>(serviceType: Service.Type) -> Service {
return try! resolveWithError(serviceType)
}
func provide<Service>(serviceType: Service.Type, name: String?) -> Service {
return try! resolveWithError(serviceType, name: name)
}
func provide<Service, Arg1>(serviceType: Service.Type, argument: Arg1) -> Service {
return try! resolveWithError(serviceType, argument: argument)
}
}
|
mit
|
6187a7d7da8c3e85f784a94f94e379a5
| 34.090909 | 103 | 0.666235 | 4.446686 | false | false | false | false |
kouky/MavlinkPrimaryFlightDisplay
|
Sources/iOS/PeripheralTableViewController.swift
|
1
|
2593
|
//
// PeripheralTableViewController.swift
// MavlinkPrimaryFlightDisplay
//
// Created by Michael Koukoullis on 31/03/2016.
// Copyright © 2016 Michael Koukoullis. All rights reserved.
//
import UIKit
import ReactiveCocoa
import Result
import CoreBluetooth
class PeripheralTableViewController: UITableViewController {
private var peripherals = [CBPeripheral]()
private let peripheralsProducer: SignalProducer<[CBPeripheral], NoError>
private let bleScanner: BLEScanner
private let bleConnector: BLEConnector
init(producer: SignalProducer<[CBPeripheral], NoError>, scanner: BLEScanner, connector: BLEConnector) {
peripheralsProducer = producer
bleScanner = scanner
bleConnector = connector
super.init(style: .Plain)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Table view data source
override func viewDidLoad() {
self.tableView.registerClass(PeripheralTableViewCell.self, forCellReuseIdentifier: "peripheral")
peripheralsProducer.start { [weak self] event in
guard let `self` = self else { return }
switch event {
case .Next(let peripherals):
self.peripherals = peripherals
self.tableView.reloadData()
default:
return
}
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return peripherals.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier("peripheral", forIndexPath: indexPath)
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let peripheral = peripherals[indexPath.row]
cell.textLabel?.text = "BLE Mini"
cell.detailTextLabel?.text = "UUID: \(peripheral.identifier.UUIDString)"
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
bleConnector(peripheralForIndexPath(indexPath))
dismissViewControllerAnimated(true, completion: nil)
}
private func peripheralForIndexPath(indexPath: NSIndexPath) -> CBPeripheral {
return peripherals[indexPath.row]
}
}
|
mit
|
2dffb6808a7f75739a5f95627ac23768
| 33.56 | 134 | 0.689429 | 5.526652 | false | false | false | false |
HongliYu/DPSlideMenuKit-Swift
|
DPSlideMenuKitDemo/SideContent/DPChannelViewModel.swift
|
1
|
1304
|
//
// DPChannelViewModel.swift
// DPSlideMenuKitDemo
//
// Created by Hongli Yu on 8/18/16.
// Copyright © 2016 Hongli Yu. All rights reserved.
//
import UIKit
class DPChannelSectionViewModel {
private(set) var title: String?
private(set) var height: CGFloat?
private(set) var actionBlock:(()->Void)?
init(title: String?,
height: CGFloat?,
actionBlock: (()->Void)?) {
self.title = title
self.height = height
self.actionBlock = actionBlock
}
}
class DPChannelCellViewModel {
private(set) var color: UIColor?
private(set) var title: String?
private(set) var cellHeight: CGFloat?
private(set) var actionBlock:(()->Void)?
init(color: UIColor?,
title: String?,
cellHeight: CGFloat?,
actionBlock: (()->Void)?) {
self.color = color
self.title = title
self.cellHeight = cellHeight
self.actionBlock = actionBlock
}
}
class DPChannelViewModel {
var channelCellViewModels: [DPChannelCellViewModel]?
var channelSectionViewModel: DPChannelSectionViewModel?
init(channelCellViewModels: [DPChannelCellViewModel]?,
channelSectionViewModel: DPChannelSectionViewModel?) {
self.channelCellViewModels = channelCellViewModels
self.channelSectionViewModel = channelSectionViewModel
}
}
|
mit
|
fea964b5e5e6ec336f36389c3a386135
| 21.859649 | 61 | 0.693016 | 4.508651 | false | false | false | false |
scottkawai/sendgrid-swift
|
Tests/SendGridTests/Helpers/EncodingTester.swift
|
1
|
2231
|
@testable import SendGrid
import XCTest
protocol EncodingTester: class {
associatedtype EncodableObject: Encodable
func encode(_ obj: EncodableObject, strategy: EncodingStrategy) throws -> Data
func XCTAssertEncodedObject(_ encodableObject: EncodableObject, equals dictionary: [String: Any])
func XCTAssertDeepEquals(_ lhs: Any?, _ rhs: Any?)
}
extension EncodingTester {
func encode(_ obj: EncodableObject, strategy: EncodingStrategy = EncodingStrategy()) throws -> Data {
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = strategy.data
encoder.dateEncodingStrategy = strategy.dates
return try encoder.encode(obj)
}
func XCTAssertEncodedObject(_ encodableObject: EncodableObject, equals dictionary: [String: Any]) {
do {
let json = try encode(encodableObject)
guard let parsed = (try JSONSerialization.jsonObject(with: json)) as? [String: Any] else {
XCTFail("Expected encoded object to be a dictionary, but received something else.")
return
}
XCTAssertDeepEquals(parsed, dictionary)
} catch {
XCTFail("\(error)")
}
}
func XCTAssertDeepEquals(_ lhs: Any?, _ rhs: Any?) {
if let lDict = lhs as? [AnyHashable: Any], let rDict = rhs as? [AnyHashable: Any] {
XCTAssertEqual(lDict.count, rDict.count)
for (key, value) in lDict {
XCTAssertDeepEquals(value, rDict[key])
}
for (key, value) in rDict {
XCTAssertDeepEquals(value, lDict[key])
}
} else if let lArray = lhs as? [Any], let rArray = rhs as? [Any] {
XCTAssertEqual(lArray.count, rArray.count)
for item in lArray.enumerated() {
XCTAssertDeepEquals(item.element, rArray[item.offset])
}
} else if let lBool = lhs as? Bool, let rBool = rhs as? Bool {
XCTAssertEqual(lBool, rBool)
} else if let left = lhs, let right = rhs {
XCTAssertEqual("\(left)", "\(right)")
} else {
XCTAssertNotNil(lhs)
XCTAssertNotNil(rhs)
}
}
}
|
mit
|
0b7a06fc523aa8da873efc9e3d709a82
| 37.465517 | 105 | 0.598386 | 4.638254 | false | true | false | false |
kay-kim/stitch-examples
|
todo/ios/Pods/ExtendedJson/ExtendedJson/ExtendedJson/Source/ExtendedJson/BsonTimestamp+ExtendedJson.swift
|
1
|
2260
|
//
// BsonTimestamp+ExtendedJson.swift
// ExtendedJson
//
// Created by Jason Flax on 10/3/17.
// Copyright © 2017 MongoDB. All rights reserved.
//
import Foundation
extension Timestamp: ExtendedJsonRepresentable {
enum CodingKeys: String, CodingKey {
case timestamp = "$timestamp", t, i
}
public static func fromExtendedJson(xjson: Any) throws -> ExtendedJsonRepresentable {
guard let json = xjson as? [String: Any],
let timestampJson = json[ExtendedJsonKeys.timestamp.rawValue] as? [String: Int64],
let timestamp = timestampJson["t"],
let increment = timestampJson["i"],
timestampJson.count == 2 else {
throw BsonError.parseValueFailure(value: xjson, attemptedType: Timestamp.self)
}
return Timestamp(time: TimeInterval(timestamp), increment: Int(increment))
}
public var toExtendedJson: Any {
return [
ExtendedJsonKeys.timestamp.rawValue: [
"t": Int64(self.time.timeIntervalSince1970),
"i": increment
]
]
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let nestedContainer = try container.nestedContainer(keyedBy: CodingKeys.self,
forKey: CodingKeys.timestamp)
self.init(time: TimeInterval(try nestedContainer.decode(Int64.self, forKey: CodingKeys.t)),
increment: try nestedContainer.decode(Int.self, forKey: CodingKeys.i))
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var nestedContainer = container.nestedContainer(keyedBy: CodingKeys.self,
forKey: CodingKeys.timestamp)
try nestedContainer.encode(Int64(self.time.timeIntervalSince1970), forKey: CodingKeys.t)
try nestedContainer.encode(increment, forKey: CodingKeys.i)
}
public func isEqual(toOther other: ExtendedJsonRepresentable) -> Bool {
if let other = other as? Timestamp {
return self == other
}
return false
}
}
|
apache-2.0
|
84ee3ab0ff5d9959fe79cf90d6179932
| 36.65 | 99 | 0.625055 | 4.837259 | false | false | false | false |
q231950/appwatch
|
AppWatchLogic/AppWatchLogic/TimeWarehouses/FileTimeWarehouse.swift
|
1
|
1044
|
//
// FileTimeWarehouse.swift
// AppWatch
//
// Created by Martin Kim Dung-Pham on 16.08.15.
// Copyright © 2015 Martin Kim Dung-Pham. All rights reserved.
//
import Foundation
public class FileTimeWarehouse : TimeWarehouse {
var file: String?
public init(filePath: String) {
do {
file = try String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding)
} catch _ {
}
}
public func timeBoxes(from: NSDate, to: NSDate, completion: ([TimeBox]?, NSError?) -> Void) {
if let file = self.file as String! {
let lines = file.componentsSeparatedByString("\n")
var timeBoxes = [TimeBox]()
for line in lines {
let timeBox = TimeBox(withString: line)
if timeBox.endDate.endedWithinRange(from, to: to) || timeBox.startDate.beganWithinRange(from, to: to) {
timeBoxes.append(timeBox)
}
}
completion(timeBoxes, nil)
}
}
}
|
mit
|
f5561c50e1d335da344cfde525f01ce3
| 28 | 119 | 0.568552 | 4.205645 | false | false | false | false |
Yurssoft/QuickFile
|
Pods/DeviceKit/Source/Device.generated.swift
|
2
|
28038
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the DeviceKit open source project
//
// Copyright © 2014 - 2017 Dennis Weissmann and the DeviceKit project authors
//
// License: https://github.com/dennisweissmann/DeviceKit/blob/master/LICENSE
// Contributors: https://github.com/dennisweissmann/DeviceKit#contributors
//
//===----------------------------------------------------------------------===//
import UIKit
// MARK: - Device
/// This enum is a value-type wrapper and extension of
/// [`UIDevice`](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDevice_Class/).
///
/// Usage:
///
/// let device = Device()
///
/// print(device) // prints, for example, "iPhone 6 Plus"
///
/// if device == .iPhone6Plus {
/// // Do something
/// } else {
/// // Do something else
/// }
///
/// ...
///
/// if device.batteryState == .full || device.batteryState >= .charging(75) {
/// print("Your battery is happy! 😊")
/// }
///
/// ...
///
/// if device.batteryLevel >= 50 {
/// install_iOS()
/// } else {
/// showError()
/// }
///
public enum Device {
#if os(iOS)
/// Device is an [iPod Touch (5th generation)](https://support.apple.com/kb/SP657)
///
/// 
case iPodTouch5
/// Device is an [iPod Touch (6th generation)](https://support.apple.com/kb/SP720)
///
/// 
case iPodTouch6
/// Device is an [iPhone 4](https://support.apple.com/kb/SP587)
///
/// 
case iPhone4
/// Device is an [iPhone 4s](https://support.apple.com/kb/SP643)
///
/// 
case iPhone4s
/// Device is an [iPhone 5](https://support.apple.com/kb/SP655)
///
/// 
case iPhone5
/// Device is an [iPhone 5c](https://support.apple.com/kb/SP684)
///
/// 
case iPhone5c
/// Device is an [iPhone 5s](https://support.apple.com/kb/SP685)
///
/// 
case iPhone5s
/// Device is an [iPhone 6](https://support.apple.com/kb/SP705)
///
/// 
case iPhone6
/// Device is an [iPhone 6 Plus](https://support.apple.com/kb/SP706)
///
/// 
case iPhone6Plus
/// Device is an [iPhone 6s](https://support.apple.com/kb/SP726)
///
/// 
case iPhone6s
/// Device is an [iPhone 6s Plus](https://support.apple.com/kb/SP727)
///
/// 
case iPhone6sPlus
/// Device is an [iPhone 7](https://support.apple.com/kb/SP743)
///
/// 
case iPhone7
/// Device is an [iPhone 7 Plus](https://support.apple.com/kb/SP744)
///
/// 
case iPhone7Plus
/// Device is an [iPhone SE](https://support.apple.com/kb/SP738)
///
/// 
case iPhoneSE
/// Device is an [iPhone 8](https://support.apple.com/kb/SP767)
///
/// 
case iPhone8
/// Device is an [iPhone 8 Plus](https://support.apple.com/kb/SP768)
///
/// 
case iPhone8Plus
/// Device is an [iPhone X](https://support.apple.com/kb/SP770)
///
/// 
case iPhoneX
/// Device is an [iPad 2](https://support.apple.com/kb/SP622)
///
/// 
case iPad2
/// Device is an [iPad (3rd generation)](https://support.apple.com/kb/SP647)
///
/// 
case iPad3
/// Device is an [iPad (4th generation)](https://support.apple.com/kb/SP662)
///
/// 
case iPad4
/// Device is an [iPad Air](https://support.apple.com/kb/SP692)
///
/// 
case iPadAir
/// Device is an [iPad Air 2](https://support.apple.com/kb/SP708)
///
/// 
case iPadAir2
/// Device is an [iPad 5](https://support.apple.com/kb/SP751)
///
/// 
case iPad5
/// Device is an [iPad Mini](https://support.apple.com/kb/SP661)
///
/// 
case iPadMini
/// Device is an [iPad Mini 2](https://support.apple.com/kb/SP693)
///
/// 
case iPadMini2
/// Device is an [iPad Mini 3](https://support.apple.com/kb/SP709)
///
/// 
case iPadMini3
/// Device is an [iPad Mini 4](https://support.apple.com/kb/SP725)
///
/// 
case iPadMini4
/// Device is an [iPad Pro](https://support.apple.com/kb/SP739)
///
/// 
case iPadPro9Inch
/// Device is an [iPad Pro](https://support.apple.com/kb/sp723)
///
/// 
case iPadPro12Inch
/// Device is an [iPad Pro](https://support.apple.com/kb/SP761)
///
/// 
case iPadPro12Inch2
/// Device is an [iPad Pro 10.5](https://support.apple.com/kb/SP762)
///
/// 
case iPadPro10Inch
/// Device is a [HomePod](https://www.apple.com/homepod/)
///
/// 
case homePod
#elseif os(tvOS)
/// Device is an [Apple TV 4](https://support.apple.com/kb/SP724)
///
/// 
case appleTV4
/// Device is an [Apple TV 4K](https://support.apple.com/kb/SP769)
///
/// 
case appleTV4K
#endif
/// Device is [Simulator](https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/iOS_Simulator_Guide/Introduction/Introduction.html)
///
/// 
indirect case simulator(Device)
/// Device is not yet known (implemented)
/// You can still use this enum as before but the description equals the identifier (you can get multiple identifiers for the same product class
/// (e.g. "iPhone6,1" or "iPhone 6,2" do both mean "iPhone 5s"))
case unknown(String)
/// Initializes a `Device` representing the current device this software runs on.
public init() {
self = Device.mapToDevice(identifier: Device.identifier)
}
/// Gets the identifier from the system, such as "iPhone7,1".
public static var identifier: String {
var systemInfo = utsname()
uname(&systemInfo)
let mirror = Mirror(reflecting: systemInfo.machine)
let identifier = mirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
return identifier
}
/// Maps an identifier to a Device. If the identifier can not be mapped to an existing device, `UnknownDevice(identifier)` is returned.
///
/// - parameter identifier: The device identifier, e.g. "iPhone7,1". Can be obtained from `Device.identifier`.
///
/// - returns: An initialized `Device`.
public static func mapToDevice(identifier: String) -> Device { // swiftlint:disable:this cyclomatic_complexity
#if os(iOS)
switch identifier {
case "iPod5,1": return iPodTouch5
case "iPod7,1": return iPodTouch6
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return iPhone4
case "iPhone4,1": return iPhone4s
case "iPhone5,1", "iPhone5,2": return iPhone5
case "iPhone5,3", "iPhone5,4": return iPhone5c
case "iPhone6,1", "iPhone6,2": return iPhone5s
case "iPhone7,2": return iPhone6
case "iPhone7,1": return iPhone6Plus
case "iPhone8,1": return iPhone6s
case "iPhone8,2": return iPhone6sPlus
case "iPhone9,1", "iPhone9,3": return iPhone7
case "iPhone9,2", "iPhone9,4": return iPhone7Plus
case "iPhone8,4": return iPhoneSE
case "iPhone10,1", "iPhone10,4": return iPhone8
case "iPhone10,2", "iPhone10,5": return iPhone8Plus
case "iPhone10,3", "iPhone10,6": return iPhoneX
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return iPad2
case "iPad3,1", "iPad3,2", "iPad3,3": return iPad3
case "iPad3,4", "iPad3,5", "iPad3,6": return iPad4
case "iPad4,1", "iPad4,2", "iPad4,3": return iPadAir
case "iPad5,3", "iPad5,4": return iPadAir2
case "iPad6,11", "iPad6,12": return iPad5
case "iPad2,5", "iPad2,6", "iPad2,7": return iPadMini
case "iPad4,4", "iPad4,5", "iPad4,6": return iPadMini2
case "iPad4,7", "iPad4,8", "iPad4,9": return iPadMini3
case "iPad5,1", "iPad5,2": return iPadMini4
case "iPad6,3", "iPad6,4": return iPadPro9Inch
case "iPad6,7", "iPad6,8": return iPadPro12Inch
case "iPad7,1", "iPad7,2": return iPadPro12Inch2
case "iPad7,3", "iPad7,4": return iPadPro10Inch
case "AudioAccessory1,1": return homePod
case "i386", "x86_64": return simulator(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))
default: return unknown(identifier)
}
#elseif os(tvOS)
switch identifier {
case "AppleTV5,3": return appleTV4
case "AppleTV6,2": return appleTV4K
case "i386", "x86_64": return simulator(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))
default: return unknown(identifier)
}
#endif
}
#if os(iOS)
/// All iPods
public static var allPods: [Device] {
return [.iPodTouch5, .iPodTouch6]
}
/// All iPhones
public static var allPhones: [Device] {
return [.iPhone4, .iPhone4s, .iPhone5, .iPhone5c, .iPhone5s, .iPhone6, .iPhone6Plus, .iPhone6s, .iPhone6sPlus, .iPhone7, .iPhone7Plus, .iPhoneSE, .iPhone8, .iPhone8Plus, .iPhoneX]
}
/// All iPads
public static var allPads: [Device] {
return [.iPad2, .iPad3, .iPad4, .iPadAir, .iPadAir2, .iPad5, .iPadMini, .iPadMini2, .iPadMini3, .iPadMini4, .iPadPro9Inch, .iPadPro12Inch, .iPadPro12Inch2, .iPadPro10Inch]
}
/// All Plus-Sized Devices
public static var allPlusSizedDevices: [Device] {
return [.iPhone6Plus, .iPhone6sPlus, .iPhone7Plus, .iPhone8Plus]
}
/// All Plus-Sized Devices
public static var allProDevices: [Device] {
return [.iPadPro9Inch, .iPadPro12Inch, .iPadPro12Inch2, .iPadPro10Inch]
}
/// All simulator iPods
public static var allSimulatorPods: [Device] {
return allPods.map(Device.simulator)
}
/// All simulator iPhones
public static var allSimulatorPhones: [Device] {
return allPhones.map(Device.simulator)
}
/// All simulator iPads
public static var allSimulatorPads: [Device] {
return allPads.map(Device.simulator)
}
/// Returns whether the device is an iPod (real or simulator)
public var isPod: Bool {
return isOneOf(Device.allPods) || isOneOf(Device.allSimulatorPods)
}
/// Returns whether the device is an iPhone (real or simulator)
public var isPhone: Bool {
return isOneOf(Device.allPhones) || isOneOf(Device.allSimulatorPhones) || UIDevice.current.userInterfaceIdiom == .phone
}
/// Returns whether the device is an iPad (real or simulator)
public var isPad: Bool {
return isOneOf(Device.allPads) || isOneOf(Device.allSimulatorPads) || UIDevice.current.userInterfaceIdiom == .pad
}
/// Returns whether the device is any of the simulator
/// Useful when there is a need to check and skip running a portion of code (location request or others)
public var isSimulator: Bool {
return isOneOf(Device.allSimulators)
}
public var isZoomed: Bool {
if Int(UIScreen.main.scale.rounded()) == 3 {
// Plus-sized
return UIScreen.main.nativeScale > 2.7
} else {
return UIScreen.main.nativeScale > UIScreen.main.scale
}
}
/// Returns diagonal screen length in inches
public var diagonal: Double {
switch self {
case .iPodTouch5: return 4
case .iPodTouch6: return 4
case .iPhone4: return 3.5
case .iPhone4s: return 3.5
case .iPhone5: return 4
case .iPhone5c: return 4
case .iPhone5s: return 4
case .iPhone6: return 4.7
case .iPhone6Plus: return 5.5
case .iPhone6s: return 4.7
case .iPhone6sPlus: return 5.5
case .iPhone7: return 4.7
case .iPhone7Plus: return 5.5
case .iPhoneSE: return 4
case .iPhone8: return 4.7
case .iPhone8Plus: return 5.5
case .iPhoneX: return 5.8
case .iPad2: return 9.7
case .iPad3: return 9.7
case .iPad4: return 9.7
case .iPadAir: return 9.7
case .iPadAir2: return 9.7
case .iPad5: return 9.7
case .iPadMini: return 7.9
case .iPadMini2: return 7.9
case .iPadMini3: return 7.9
case .iPadMini4: return 7.9
case .iPadPro9Inch: return 9.7
case .iPadPro12Inch: return 12.9
case .iPadPro12Inch2: return 12.9
case .iPadPro10Inch: return 10.5
case .homePod: return -1
case .simulator(let model): return model.diagonal
case .unknown: return -1
}
}
/// Returns screen ratio as a tuple
public var screenRatio: (width: Double, height: Double) {
switch self {
case .iPodTouch5: return (width: 9, height: 16)
case .iPodTouch6: return (width: 9, height: 16)
case .iPhone4: return (width: 2, height: 3)
case .iPhone4s: return (width: 2, height: 3)
case .iPhone5: return (width: 9, height: 16)
case .iPhone5c: return (width: 9, height: 16)
case .iPhone5s: return (width: 9, height: 16)
case .iPhone6: return (width: 9, height: 16)
case .iPhone6Plus: return (width: 9, height: 16)
case .iPhone6s: return (width: 9, height: 16)
case .iPhone6sPlus: return (width: 9, height: 16)
case .iPhone7: return (width: 9, height: 16)
case .iPhone7Plus: return (width: 9, height: 16)
case .iPhoneSE: return (width: 9, height: 16)
case .iPhone8: return (width: 9, height: 16)
case .iPhone8Plus: return (width: 9, height: 16)
case .iPhoneX: return (width: 9, height: 19.5)
case .iPad2: return (width: 3, height: 4)
case .iPad3: return (width: 3, height: 4)
case .iPad4: return (width: 3, height: 4)
case .iPadAir: return (width: 3, height: 4)
case .iPadAir2: return (width: 3, height: 4)
case .iPad5: return (width: 3, height: 4)
case .iPadMini: return (width: 3, height: 4)
case .iPadMini2: return (width: 3, height: 4)
case .iPadMini3: return (width: 3, height: 4)
case .iPadMini4: return (width: 3, height: 4)
case .iPadPro9Inch: return (width: 3, height: 4)
case .iPadPro12Inch: return (width: 3, height: 4)
case .iPadPro12Inch2: return (width: 3, height: 4)
case .iPadPro10Inch: return (width: 3, height: 4)
case .homePod: return (width: 4, height: 5)
case .simulator(let model): return model.screenRatio
case .unknown: return (width: -1, height: -1)
}
}
#elseif os(tvOS)
/// All TVs
public static var allTVs: [Device] {
return [.appleTV4, .appleTV4K]
}
/// All simulator TVs
public static var allSimulatorTVs: [Device] {
return allTVs.map(Device.simulator)
}
#endif
/// All real devices (i.e. all devices except for all simulators)
public static var allRealDevices: [Device] {
#if os(iOS)
return allPods + allPhones + allPads
#elseif os(tvOS)
return allTVs
#endif
}
/// All simulators
public static var allSimulators: [Device] {
return allRealDevices.map(Device.simulator)
}
/**
This method saves you in many cases from the need of updating your code with every new device.
Most uses for an enum like this are the following:
```
switch Device() {
case .iPodTouch5, .iPodTouch6: callMethodOnIPods()
case .iPhone4, iPhone4s, .iPhone5, .iPhone5s, .iPhone6, .iPhone6Plus, .iPhone6s, .iPhone6sPlus, .iPhone7, .iPhone7Plus, .iPhoneSE, .iPhone8, .iPhone8Plus, .iPhoneX: callMethodOnIPhones()
case .iPad2, .iPad3, .iPad4, .iPadAir, .iPadAir2, .iPadMini, .iPadMini2, .iPadMini3, .iPadMini4, .iPadPro: callMethodOnIPads()
default: break
}
```
This code can now be replaced with
```
let device = Device()
if device.isOneOf(Device.allPods) {
callMethodOnIPods()
} else if device.isOneOf(Device.allPhones) {
callMethodOnIPhones()
} else if device.isOneOf(Device.allPads) {
callMethodOnIPads()
}
```
- parameter devices: An array of devices.
- returns: Returns whether the current device is one of the passed in ones.
*/
public func isOneOf(_ devices: [Device]) -> Bool {
return devices.contains(self)
}
/// The name identifying the device (e.g. "Dennis' iPhone").
public var name: String {
return UIDevice.current.name
}
/// The name of the operating system running on the device represented by the receiver (e.g. "iOS" or "tvOS").
public var systemName: String {
return UIDevice.current.systemName
}
/// The current version of the operating system (e.g. 8.4 or 9.2).
public var systemVersion: String {
return UIDevice.current.systemVersion
}
/// The model of the device (e.g. "iPhone" or "iPod Touch").
public var model: String {
return UIDevice.current.model
}
/// The model of the device as a localized string.
public var localizedModel: String {
return UIDevice.current.localizedModel
}
/// PPI (Pixels per Inch) on the current device's screen (if applicable). When the device is not applicable this property returns nil.
public var ppi: Int? {
#if os(iOS)
switch self {
case .iPodTouch5: return 326
case .iPodTouch6: return 326
case .iPhone4: return 326
case .iPhone4s: return 326
case .iPhone5: return 326
case .iPhone5c: return 326
case .iPhone5s: return 326
case .iPhone6: return 326
case .iPhone6Plus: return 401
case .iPhone6s: return 326
case .iPhone6sPlus: return 401
case .iPhone7: return 326
case .iPhone7Plus: return 401
case .iPhoneSE: return 326
case .iPhone8: return 326
case .iPhone8Plus: return 401
case .iPhoneX: return 458
case .iPad2: return 132
case .iPad3: return 264
case .iPad4: return 264
case .iPadAir: return 264
case .iPadAir2: return 264
case .iPad5: return 264
case .iPadMini: return 163
case .iPadMini2: return 326
case .iPadMini3: return 326
case .iPadMini4: return 326
case .iPadPro9Inch: return 264
case .iPadPro12Inch: return 264
case .iPadPro12Inch2: return 264
case .iPadPro10Inch: return 264
case .homePod: return -1
case .simulator(let model): return model.ppi
case .unknown: return nil
}
#elseif os(tvOS)
return nil
#endif
}
}
// MARK: - CustomStringConvertible
extension Device: CustomStringConvertible {
/// A textual representation of the device.
public var description: String {
#if os(iOS)
switch self {
case .iPodTouch5: return "iPod Touch 5"
case .iPodTouch6: return "iPod Touch 6"
case .iPhone4: return "iPhone 4"
case .iPhone4s: return "iPhone 4s"
case .iPhone5: return "iPhone 5"
case .iPhone5c: return "iPhone 5c"
case .iPhone5s: return "iPhone 5s"
case .iPhone6: return "iPhone 6"
case .iPhone6Plus: return "iPhone 6 Plus"
case .iPhone6s: return "iPhone 6s"
case .iPhone6sPlus: return "iPhone 6s Plus"
case .iPhone7: return "iPhone 7"
case .iPhone7Plus: return "iPhone 7 Plus"
case .iPhoneSE: return "iPhone SE"
case .iPhone8: return "iPhone 8"
case .iPhone8Plus: return "iPhone 8 Plus"
case .iPhoneX: return "iPhone X"
case .iPad2: return "iPad 2"
case .iPad3: return "iPad 3"
case .iPad4: return "iPad 4"
case .iPadAir: return "iPad Air"
case .iPadAir2: return "iPad Air 2"
case .iPad5: return "iPad 5"
case .iPadMini: return "iPad Mini"
case .iPadMini2: return "iPad Mini 2"
case .iPadMini3: return "iPad Mini 3"
case .iPadMini4: return "iPad Mini 4"
case .iPadPro9Inch: return "iPad Pro (9.7-inch)"
case .iPadPro12Inch: return "iPad Pro (12.9-inch)"
case .iPadPro12Inch2: return "iPad Pro (12.9-inch) 2"
case .iPadPro10Inch: return "iPad Pro (10.5-inch)"
case .homePod: return "HomePod"
case .simulator(let model): return "Simulator (\(model))"
case .unknown(let identifier): return identifier
}
#elseif os(tvOS)
switch self {
case .appleTV4: return "Apple TV 4"
case .appleTV4K: return "Apple TV 4K"
case .simulator(let model): return "Simulator (\(model))"
case .unknown(let identifier): return identifier
}
#endif
}
}
// MARK: - Equatable
extension Device: Equatable {
/// Compares two devices
///
/// - parameter lhs: A device.
/// - parameter rhs: Another device.
///
/// - returns: `true` iff the underlying identifier is the same.
public static func == (lhs: Device, rhs: Device) -> Bool {
return lhs.description == rhs.description
}
}
#if os(iOS)
// MARK: - Battery
extension Device {
/**
This enum describes the state of the battery.
- Full: The device is plugged into power and the battery is 100% charged or the device is the iOS Simulator.
- Charging: The device is plugged into power and the battery is less than 100% charged.
- Unplugged: The device is not plugged into power; the battery is discharging.
*/
public enum BatteryState: CustomStringConvertible, Equatable {
/// The device is plugged into power and the battery is 100% charged or the device is the iOS Simulator.
case full
/// The device is plugged into power and the battery is less than 100% charged.
/// The associated value is in percent (0-100).
case charging(Int)
/// The device is not plugged into power; the battery is discharging.
/// The associated value is in percent (0-100).
case unplugged(Int)
fileprivate init() {
UIDevice.current.isBatteryMonitoringEnabled = true
let batteryLevel = Int(round(UIDevice.current.batteryLevel * 100)) // round() is actually not needed anymore since -[batteryLevel] seems to always return a two-digit precision number
// but maybe that changes in the future.
switch UIDevice.current.batteryState {
case .charging: self = .charging(batteryLevel)
case .full: self = .full
case .unplugged:self = .unplugged(batteryLevel)
case .unknown: self = .full // Should never happen since `batteryMonitoring` is enabled.
}
UIDevice.current.isBatteryMonitoringEnabled = false
}
/// Provides a textual representation of the battery state.
/// Examples:
/// ```
/// Battery level: 90%, device is plugged in.
/// Battery level: 100 % (Full), device is plugged in.
/// Battery level: \(batteryLevel)%, device is unplugged.
/// ```
public var description: String {
switch self {
case .charging(let batteryLevel): return "Battery level: \(batteryLevel)%, device is plugged in."
case .full: return "Battery level: 100 % (Full), device is plugged in."
case .unplugged(let batteryLevel): return "Battery level: \(batteryLevel)%, device is unplugged."
}
}
}
/// The state of the battery
public var batteryState: BatteryState {
return BatteryState()
}
/// Battery level ranges from 0 (fully discharged) to 100 (100% charged).
public var batteryLevel: Int {
switch BatteryState() {
case .charging(let value): return value
case .full: return 100
case .unplugged(let value): return value
}
}
}
// MARK: - Device.Batterystate: Comparable
extension Device.BatteryState: Comparable {
/// Tells if two battery states are equal.
///
/// - parameter lhs: A battery state.
/// - parameter rhs: Another battery state.
///
/// - returns: `true` iff they are equal, otherwise `false`
public static func == (lhs: Device.BatteryState, rhs: Device.BatteryState) -> Bool {
return lhs.description == rhs.description
}
/// Compares two battery states.
///
/// - parameter lhs: A battery state.
/// - parameter rhs: Another battery state.
///
/// - returns: `true` if rhs is `.Full`, `false` when lhs is `.Full` otherwise their battery level is compared.
public static func < (lhs: Device.BatteryState, rhs: Device.BatteryState) -> Bool {
switch (lhs, rhs) {
case (.full, _): return false // return false (even if both are `.Full` -> they are equal)
case (_, .full): return true // lhs is *not* `.Full`, rhs is
case (.charging(let lhsLevel), .charging(let rhsLevel)): return lhsLevel < rhsLevel
case (.charging(let lhsLevel), .unplugged(let rhsLevel)): return lhsLevel < rhsLevel
case (.unplugged(let lhsLevel), .charging(let rhsLevel)): return lhsLevel < rhsLevel
case (.unplugged(let lhsLevel), .unplugged(let rhsLevel)): return lhsLevel < rhsLevel
default: return false // compiler won't compile without it, though it cannot happen
}
}
}
#endif
|
mit
|
f3a05163cfb51fd7e44efaa45849f2b6
| 38.428973 | 190 | 0.648284 | 3.535183 | false | false | false | false |
Velhotes/Vinyl
|
VinylTests/Arbitrary.swift
|
1
|
3420
|
//
// Arbitrary.swift
// Vinyl
//
// Created by Robert Widmann on 2/20/16.
// Copyright © 2016 Velhotes. All rights reserved.
//
import Foundation
import SwiftCheck
/// Generates an array of lowercase alphabetic `Character`s.
let lowerStringGen =
Gen<Character>.fromElements(in: "a"..."z")
.proliferateNonEmpty
.map { String($0) }
/// Generates a URL of the form `(http|https)://<domain>.com`.
let urlStringGen : Gen<String> = sequence([
Gen<String>.fromElements(of: ["http://", "https://"]),
lowerStringGen,
Gen.pure(".com"),
])
.map { $0.reduce("", +) }
// Generates a JSON string of the form '"string"'
let jsonString: Gen<String> = lowerStringGen.map { "\"" + $0 + "\""}
// Generates a JSON string pair of the form '"key":"value"'
let jsonStringPair: Gen<String> = sequence([
jsonString,
Gen.pure(":"),
jsonString])
.map { $0.reduce("", +) }
// Split into two steps as otherwise causes compiler error:
// "expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions"
let jsonStringPairsArray: Gen<[String]> = Gen.sized { sz in
return jsonStringPair.proliferate(withSize: sz + 1)
}
// Generates a JSON string pair of the form '"key":"value", "key1":"value1" ....'
let jsonStringPairs: Gen<String> = jsonStringPairsArray.map { xs in
return xs.reduce("") { $0 == "" ? $1 : $0 + "," + $1
}
}
// Generates a JSON of the form '{"key":"value", "key1":"value1" .... }'
let basicJSONDic : Gen<AnyObject> = sequence([
Gen.pure("{"),
jsonStringPairs,
Gen.pure("}")
])
.map { $0.reduce("", +) }
.map { $0.data(using: .utf8)! }
.map { try! JSONSerialization.jsonObject(with: $0, options: .allowFragments) as AnyObject }
/// Generates a path of the form `<some>/<path>/<to>/.../<somewhere>`.
let urlPathGen: Gen<String> = lowerStringGen
.ap(Gen.pure("/")
.map(curry(+)))
.proliferate
.map { $0.reduce("", +) }
/// Generates an array of parameters of the form `<param>=<arg>`,
let parameterGen : Gen<String> = sequence([
lowerStringGen,
Gen.pure("="),
lowerStringGen,
])
.map { $0.reduce("", +) }
// Split into two steps as otherwise causes compiler error:
// "expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions"
let pathParameterGenArray: Gen<[String]> = Gen.sized { sz in
return parameterGen.proliferate(withSize: sz + 1)
}
/// Generates a set of parameters.
let pathParameterGen: Gen<String> = pathParameterGenArray.map { xs in
return xs.reduce("?") {
switch $0 {
case "?":
return $0 + $1
default:
return $0 + "&" + $1
}
}
}
func pathParameterGenArrayMinimumSize(_ minimumSize: Int) -> Gen<[String]> {
return Gen.sized { sz in
return parameterGen.proliferate(withSize: max(sz + 1, minimumSize))
}
}
func pathParameterGenMinimumSize(_ minimumSize: Int) -> Gen<String> {
return pathParameterGenArrayMinimumSize(minimumSize).map { xs in
return xs.reduce("?") {
switch $0 {
case "?":
return $0 + $1
default:
return $0 + "&" + $1
}
}
}
}
private func curry<A, B, C>(_ f : @escaping (A, B) -> C) -> (A) -> (B) -> C {
return { a in { b in f(a, b) } }
}
|
mit
|
47d58a8688e9dc6b817bb71ce2f2f6b6
| 29.256637 | 130 | 0.605733 | 3.680301 | false | false | false | false |
28stephlim/Heartbeat-Analyser
|
VoiceMemos/View/VoiceTableViewCell.swift
|
7
|
1723
|
//
// VoiceTableViewCell.swift
// VoiceMemos
//
// Created by Zhouqi Mo on 2/21/15.
// Copyright (c) 2015 Zhouqi Mo. All rights reserved.
//
import UIKit
class VoiceTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var durationLabel: UILabel!
@IBOutlet weak var playbackProgressPlaceholderView: UIView!
@IBOutlet weak var leadingConstraint: NSLayoutConstraint!
@IBOutlet weak var trailingConstraint: NSLayoutConstraint!
var tableView: UIView!
//This seems to be a bug the preferredMaxLayoutWidth property of the UILabel is not automatically calculated correctly.
//The workaround is to manually set the preferredMaxLayoutWidth on the label based on its actual width.
//See https://github.com/MoZhouqi/iOS8SelfSizingCells for details.
var maxLayoutWidth: CGFloat {
let CellTrailingToContentViewTrailingConstant: CGFloat = 48.0
// Minus the left/right padding for the label
let maxLayoutWidth = CGRectGetWidth(tableView.frame) - leadingConstraint.constant - trailingConstraint.constant - CellTrailingToContentViewTrailingConstant
return maxLayoutWidth
}
func updateFonts()
{
titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
dateLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleFootnote)
durationLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
}
override func layoutSubviews() {
super.layoutSubviews()
if tableView != nil {
titleLabel.preferredMaxLayoutWidth = maxLayoutWidth
}
}
}
|
mit
|
a5ef8a3e7ac007500c5c653409b1ec2e
| 35.659574 | 163 | 0.725479 | 5.334365 | false | false | false | false |
THECALLR/sdk-ios
|
ThecallrApi/ThecallrApi/ThecallrApi.swift
|
1
|
4490
|
//
// Api.swift
// ThecallrApi
//
// Created by THECALLR on 22/09/14.
// Copyright (c) 2014 THECALLR. All rights reserved.
//
import Foundation
class ThecallrApi {
private let login, password: String!
init(login: String, password: String) {
self.login = login
self.password = password
}
func call(method: String, params: AnyObject...) -> ThecallrApiRequestHandler {
return self.send(method, params: params, id: 0)
}
func send(method: String, params: Array<AnyObject>) -> ThecallrApiRequestHandler {
return self.send(method, params: params, id: 0)
}
func send(method: String, params: Array<AnyObject>, id: Int) -> ThecallrApiRequestHandler {
// create Dictionary to be converted to json
let dictionary: [String: AnyObject] = [
"jsonrpc": "2.0",
"id": id != 0 ? id : NSInteger(100 + arc4random_uniform(900)),
"method": method,
"params": params
]
// convert dictionary to json string
var err: NSError?
let data: NSData! = NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions(0), error: &err)
// encode login/password to basicAuth format
let auth: NSData! = "\(self.login):\(self.password)".dataUsingEncoding(NSUTF8StringEncoding)
let basicAuth: NSString = auth.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromMask(0))
// create and return new instance for request
return ThecallrApiRequestHandler(data: data, basicAuth: basicAuth).exec()
}
}
class ThecallrApiRequestHandler : NSObject {
private let API = "https://api.thecallr.com"
private var successCallback: ((AnyObject) -> Void)?
private var failureCallback: ((AnyObject) -> Void)?
private let dataOut: NSData!
private var dataIn: NSMutableData = NSMutableData()
private let basicAuth: NSString!
private var statusCode: Int = 0
init(data: NSData!, basicAuth: NSString!) {
self.dataOut = data
self.basicAuth = basicAuth
}
// prepare and send request
internal func exec(Void) -> ThecallrApiRequestHandler {
let req = NSMutableURLRequest(URL: NSURL(string: self.API))
req.setValue("Basic \(basicAuth)", forHTTPHeaderField: "Authorization")
req.setValue("application/json-rpc; charset=utf-8", forHTTPHeaderField: "Content-Type")
req.setValue(String(dataOut.length), forHTTPHeaderField: "Content-Length")
req.HTTPMethod = "POST"
req.HTTPBody = dataOut
NSURLConnection(request: req, delegate: self, startImmediately: true)
return self
}
// Request response headers
private func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSHTTPURLResponse!) {
statusCode = response.statusCode
}
// Request response data
private func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
dataIn.appendData(conData)
}
// Request failed
private func connection(connection: NSURLConnection!, didFailWithError: NSError!) {
if (failureCallback != nil) {
let error: [String:AnyObject] = [
"code": didFailWithError.code,
"message": "HTTP_EXCEPTION",
"NSError": didFailWithError
]
failureCallback!(error)
}
}
// Request ended
// Begin data processing
private func connectionDidFinishLoading(connection: NSURLConnection!) -> Void {
// Check response code
if statusCode != 200 && failureCallback != nil {
let error: [String:AnyObject] = [
"code": statusCode,
"message": "HTTP_CODE_ERROR"
]
return failureCallback!(error)
}
// Convert (json) string to dictionary
// It will fail if string is not json and "err" will be != nil
var error: NSError?
let json: NSDictionary? = NSJSONSerialization.JSONObjectWithData(dataIn, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
// check for error
if error == nil && json != nil && json!["result"] != nil {
if successCallback != nil {
return successCallback!(json!["result"]!)
}
return ;
}
else if failureCallback != nil && error == nil && json != nil && json!["error"] != nil {
return failureCallback!(json!["error"]!)
}
else {
if (failureCallback != nil) {
let error: [String:String] = [
"code": "-1",
"message": "INVALID_RESPONSE"
]
return failureCallback!(error)
}
}
}
// Callback setter
func success(callback: ((AnyObject) -> Void)!) -> ThecallrApiRequestHandler {
self.successCallback = callback
return self
}
func failure(callback: ((AnyObject) -> Void)!) -> ThecallrApiRequestHandler {
self.failureCallback = callback
return self
}
}
|
mit
|
c3346ba9beb8aa680bb7b30e603fa764
| 27.967742 | 155 | 0.705791 | 3.757322 | false | false | false | false |
coolryze/YZPlayer
|
YZPlayerDemo/YZPlayerDemo/View/Others/YZVideoCommentCell.swift
|
1
|
3545
|
//
// YZVideoCommentCell.swift
// Mov
//
// Created by heyuze on 2016/11/26.
// Copyright © 2016年 heyuze. All rights reserved.
//
import UIKit
class YZVideoCommentCell: UITableViewCell {
// MARK: - init
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Set up
private func setupUI() {
backgroundColor = WHITE
contentView.backgroundColor = WHITE
selectionStyle = .none
contentView.addSubview(iconView)
contentView.addSubview(nameLabel)
contentView.addSubview(timeLabel)
contentView.addSubview(likeNumberLabel)
contentView.addSubview(likeBtn)
contentView.addSubview(commentLabel)
iconView.snp.makeConstraints { (make) in
make.top.equalTo(contentView).offset(10)
make.leading.equalTo(contentView).offset(15)
make.width.height.equalTo(36)
}
nameLabel.snp.makeConstraints { (make) in
make.top.equalTo(contentView).offset(15)
make.leading.equalTo(iconView.snp.trailing).offset(10)
make.height.equalTo(13)
}
timeLabel.snp.makeConstraints { (make) in
make.leading.equalTo(nameLabel)
make.top.equalTo(nameLabel.snp.bottom).offset(7)
make.height.equalTo(11)
}
likeNumberLabel.snp.makeConstraints { (make) in
make.trailing.equalTo(contentView).offset(-15)
make.centerY.equalTo(nameLabel)
}
likeBtn.snp.makeConstraints { (make) in
make.trailing.equalTo(likeNumberLabel.snp.leading).offset(-5)
make.centerY.equalTo(likeNumberLabel)
}
commentLabel.snp.makeConstraints { (make) in
make.top.equalTo(timeLabel.snp.bottom).offset(12)
make.leading.equalTo(nameLabel)
make.trailing.equalTo(contentView).offset(-15)
}
let lineView = UIView()
lineView.backgroundColor = BACKGROUND_COLOR
contentView.addSubview(lineView)
lineView.snp.makeConstraints { (make) in
make.leading.trailing.bottom.equalTo(contentView)
make.height.equalTo(1)
}
}
// MARK: - Action
@objc private func like() {
print("like")
}
// MARK: - Lazy Load
private lazy var iconView: UIImageView = {
let iconView = UIImageView()
iconView.image = UIImage(named: "jinx")
return iconView
}()
private lazy var nameLabel = UILabel(text: "Name", textColor: BLACK, fontSize: 13)
private lazy var timeLabel = UILabel(text: "1分钟前", textColor: GRAY_99, fontSize: 11)
private lazy var likeNumberLabel = UILabel(text: "0", textColor: GRAY_99, fontSize: 11)
private lazy var likeBtn: UIButton = {
let likeBtn = UIButton()
likeBtn.setImage(UIImage(named: "video_comment_like"), for: .normal)
likeBtn.addTarget(self, action: #selector(self.like), for: .touchUpInside)
return likeBtn
}()
private lazy var commentLabel: UILabel = {
let commentLabel = UILabel(text: "Comment...", textColor: BLACK, fontSize: 13)
commentLabel.numberOfLines = 0
return commentLabel
}()
}
|
mit
|
8b72af9c27ae0a7a641b5e515b1abdec
| 30.292035 | 91 | 0.612839 | 4.562581 | false | false | false | false |
vincent-cheny/DailyRecord
|
DailyRecord/CheckAndSumSettingViewController.swift
|
1
|
3741
|
//
// CheckAndSumSettingViewController.swift
// DailyRecord
//
// Created by ChenYong on 16/4/22.
// Copyright © 2016年 LazyPanda. All rights reserved.
//
import UIKit
class CheckAndSumSettingViewController: UIViewController {
let defaults = NSUserDefaults.standardUserDefaults()
@IBOutlet weak var blackSwitch: UISwitch!
@IBOutlet weak var whiteSwitch: UISwitch!
@IBOutlet weak var dailySummarySwitch: UISwitch!
@IBOutlet weak var summaryTimeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
blackSwitch.on = defaults.boolForKey(Utils.needBlackCheck)
whiteSwitch.on = defaults.boolForKey(Utils.needWhiteCheck)
dailySummarySwitch.on = defaults.boolForKey(Utils.needDailySummary)
summaryTimeLabel.text = Utils.getHourAndMinute(getSummaryComponents())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
@IBAction func switchBlackCheck(sender: AnyObject) {
defaults.setBool(blackSwitch.on, forKey: Utils.needBlackCheck)
}
@IBAction func switchWhiteCheck(sender: AnyObject) {
defaults.setBool(whiteSwitch.on, forKey: Utils.needWhiteCheck)
}
@IBAction func switchDailySummary(sender: UISwitch) {
defaults.setBool(dailySummarySwitch.on, forKey: Utils.needDailySummary)
if sender.on {
openNotification()
} else {
cancelNotification()
}
}
func cancelNotification() {
let application = UIApplication.sharedApplication()
let notifications = application.scheduledLocalNotifications!
for notification in notifications {
if notification.category == Utils.dailySummaryCategory {
//Cancelling local notification
application.cancelLocalNotification(notification)
}
}
}
func openNotification() {
let notification = UILocalNotification()
notification.alertBody = "每日总结" // text that will be displayed in the notification
notification.soundName = UILocalNotificationDefaultSoundName // play default sound
notification.category = Utils.dailySummaryCategory
notification.repeatInterval = .Day
notification.fireDate = Utils.getFireDate(getSummaryComponents())
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
@IBAction func setSummaryTime(sender: AnyObject) {
DatePickerDialog().show("请选择时间", doneButtonTitle: "确定", cancelButtonTitle: "取消", defaultDate: NSCalendar.currentCalendar().dateFromComponents(getSummaryComponents())!, datePickerMode: .Time) {
(date) -> Void in
let components = NSCalendar.currentCalendar().components([.Hour, .Minute], fromDate: date)
self.summaryTimeLabel.text = Utils.getHourAndMinute(components)
self.defaults.setObject([components.hour, components.minute], forKey: Utils.summaryTime)
if self.dailySummarySwitch.on {
self.cancelNotification()
self.openNotification()
}
}
}
func getSummaryComponents() -> NSDateComponents {
let components = NSDateComponents()
let summaryTime = defaults.objectForKey(Utils.summaryTime) as! [Int]
components.hour = summaryTime[0]
components.minute = summaryTime[1]
return components
}
}
|
gpl-2.0
|
00f6c7f8d800d2a095ed6cdb1bd35fb8
| 37.677083 | 200 | 0.678341 | 5.235543 | false | false | false | false |
chengxianghe/MissGe
|
MissGe/MissGe/Class/Project/UI/Controller/Home/HomeViewController.swift
|
1
|
13208
|
//
// HomeViewController.swift
// MissLi
//
// Created by chengxianghe on 16/7/18.
// Copyright © 2016年 cn. All rights reserved.
//
import UIKit
import MJRefresh
import XHPhotoBrowser
class HomeViewController: BaseViewController, ScrollDrectionChangeProtocol, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
// scrollprotocol
var weakScrollView: UIScrollView! = nil
var lastOffsetY: CGFloat = 0
var isUp: Bool = false
var scrollBlock: ScrollDirectionChangeBlock?
var dataSource = [MLHomePageModel]()
var bannerSource = [MLHomeBannerModel]()
let homeRequest = HomePageRequest()
let bannerRequest = HomePageBannerRequest()
var currentIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
self.checkAdView()
print("login:\(MLNetConfig.isUserLogin())")
self.setWeakScrollView(self.tableView)
self.setWeakScrollDirectionChangeBlock { (isUp) in
if isUp {
print("isUp")
} else {
print("isDown")
}
}
let scrollAdView = GMBScrollAdView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kisIPad() ? 300 : 200), images: nil, autoPlay: true, delay: 3.0) { (index) in
let banner = self.bannerSource[index]
if banner.weibo_type == 2 {
// 跳到新的页面
self.performSegue(withIdentifier: "BannerToSubject", sender: banner)
} else if banner.weibo_type == 0 {
// 进入文章详情
self.performSegue(withIdentifier: "HomeCellToDetail", sender: banner.weibo_id)
} else {
print("未知类型: id:\(banner.weibo_id), type:\(banner.weibo_type)")
}
}
self.tableView.tableHeaderView = scrollAdView
self.configRefresh()
}
func checkAdView() {
// 1.判断沙盒中是否存在广告图片,如果存在,直接显示
let filePath = self.getFilePathWithImageName(imageName: adImageName);
let isExist = FileManager.default.fileExists(atPath: filePath)
if isExist {
let advertiseView = AdvertiseView(frame: UIApplication.shared.keyWindow!.bounds)
advertiseView.filePath = filePath
advertiseView.setAdDismiss(nil, save: {
//保存图片
PhotoAlbumHelper.saveImageToAlbum(UIImage(contentsOfFile: filePath)!, completion: { (result: PhotoAlbumHelperResult, err: NSError?) in
if result == .success {
self.showSuccess("保存成功!")
} else {
self.showError(err?.localizedDescription ?? "保存出错")
}
})
})
advertiseView.show()
}
// 2.无论沙盒中是否存在广告图片,都需要重新调用广告接口,判断广告是否更新
self.refreshImageUrl()
}
func refreshImageUrl() {
let startRequest = MLAPPStartRequest()
startRequest.send(success: { (base, res) in
guard let url = startRequest.adModel?.path?.absoluteString else {
return
}
let lastUrl = UserDefaults.standard.value(forKey: adUrl) as? String ?? ""
if url != lastUrl {
YYWebImageManager.shared().requestImage(with: startRequest.adModel!.path!, options: YYWebImageOptions.ignoreDiskCache, progress: nil, transform: nil, completion: { (image, imageUrl, from, stage, error) in
DispatchQueue.global().async(execute: {
let data = image!.yy_imageDataRepresentation()
try? data?.write(to: URL.init(fileURLWithPath: self.getFilePathWithImageName(imageName: adImageName)))
UserDefaults.standard.set(url, forKey: adUrl)
UserDefaults.standard.synchronize()
})
})
}
}) { (base, err) in
print(err)
}
}
func getFilePathWithImageName(imageName: String) -> String {
let filePath = kCachesPath().appending("/\(imageName)")
return filePath;
}
//MARK: - 刷新
func configRefresh() {
self.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[unowned self] () -> Void in
if self.tableView.mj_footer.isRefreshing {
return
}
self.loadData(1)
})
self.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[unowned self] () -> Void in
if self.tableView.mj_header.isRefreshing {
return
}
self.loadData(self.currentIndex + 1)
})
(self.tableView.mj_footer as! MJRefreshAutoNormalFooter).huaBanFooterConfig()
(self.tableView.mj_header as! MJRefreshNormalHeader).huaBanHeaderConfig()
self.tableView.mj_header.beginRefreshing()
}
//MARK: - 数据请求
func loadData(_ page: Int){
if page == 1 {
//
bannerRequest.send(success: {[unowned self] (baseRequest, responseObject) in
guard let dict = responseObject as? NSDictionary else {
return
}
guard let content = dict["content"] as? [[String:Any]] else {
return
}
let array = content.map({ MLHomeBannerModel(JSON: $0) }) as! [MLHomeBannerModel]
self.bannerSource.removeAll()
self.bannerSource.append(contentsOf: array)
let urls = array.flatMap({ $0.path })
let scrollAdView = self.tableView.tableHeaderView as! GMBScrollAdView
scrollAdView.updateImages(urls, titles: nil)
}) { (baseRequest, error) in
print(error)
}
}
homeRequest.page = page
homeRequest.send(success: {[unowned self] (baseRequest, responseObject) in
self.tableView.mj_header.endRefreshing()
var array: [MLHomePageModel]? = nil
if let list = ((responseObject as! NSDictionary)["content"] as! NSDictionary)["artlist"] as? [[String:Any]] {
array = list.map({ MLHomePageModel(JSON: $0) }) as? [MLHomePageModel]
}
if (array?.count)! > 0 {
if page == 1 {
self.dataSource.removeAll()
self.dataSource.append(contentsOf: array!)
self.tableView.reloadData()
} else {
self.tableView.beginUpdates()
let lastItem = self.dataSource.count
self.dataSource.append(contentsOf: array!)
let indexPaths = (lastItem..<self.dataSource.count).map { IndexPath(row: $0, section: 0) }
self.tableView.insertRows(at: indexPaths, with: UITableViewRowAnimation.fade)
self.tableView.endUpdates()
}
if array!.count < 20 {
self.tableView.mj_footer.endRefreshingWithNoMoreData()
} else {
self.currentIndex = page
self.tableView.mj_footer.endRefreshing()
}
} else {
if page == 1 {
self.dataSource.removeAll()
self.tableView.reloadData()
}
self.tableView.mj_footer.endRefreshingWithNoMoreData()
}
}) { (baseRequest, error) in
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
print(error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = self.dataSource[(indexPath as NSIndexPath).row] as MLHomePageModel
if model.type == 5 {
let cell = tableView.dequeueReusableCell(withIdentifier: "MLHomePageAlbumCell") as? MLHomePageAlbumCell
cell?.setInfo(self.dataSource[(indexPath as NSIndexPath).row]);
return cell!
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "MLHomePageCell") as? MLHomePageCell
cell?.setInfo(self.dataSource[(indexPath as NSIndexPath).row]);
return cell!
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let model = self.dataSource[(indexPath as NSIndexPath).row]
if model.type == 5 {
self.performSegue(withIdentifier: "HomeAlbumCellToDetail", sender: model)
} else {
self.performSegue(withIdentifier: "HomeCellToDetail", sender: model.tid)
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let model = self.dataSource[(indexPath as NSIndexPath).row] as MLHomePageModel
if model.type == 5 {
return MLHomePageAlbumCell.height(model)
}
return 100
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "HomeCellToDetail" {
let vc = segue.destination as! MLHomeDetailController
vc.aid = sender as! String
let aids = (self.dataSource.filter({ $0.type == 1 })).map({ $0.tid })
vc.nextClosure = { (aid: String!) -> String? in
if let index = aids.index(of: aid) {
if index < aids.count - 1 {
return aids[index + 1]
}
}
return nil
}
} else if segue.identifier == "HomeAlbumCellToDetail" {
let vc = segue.destination as! XHPhotoBrowserController
let models = (sender as! MLHomePageModel).album!
var groupItems = [XHPhotoItem]()
let title = (sender as! MLHomePageModel).title
for model in models {
let item = XHPhotoItem()
item.caption = title
item.largeImageURL = model.url
groupItems.append(item)
}
vc.groupItems = groupItems
// vc.title =
vc.rightImage = UIImage(named: "atlas_review_btn_sel_30x30_")
vc.moreBlock = {[aid = (sender as! MLHomePageModel).tid, _self = self] in
let commentVC = kLoadVCFromSB("MLHomeCommentController", stroyBoard: "HomeComment") as! MLHomeCommentController
commentVC.aid = aid
_self.navigationController?.pushViewController(commentVC, animated: true)
}
} else if segue.identifier == "BannerToSubject" {
let vc = segue.destination as! MLHomeSubjectController
vc.tag_id = (sender as! MLHomeBannerModel).weibo_id
vc.path = (sender as! MLHomeBannerModel).path
vc.subjectType = .banner
}
}
}
extension HomeViewController {
// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// if (!_fpsLabel) { return; }
let offsetY = scrollView.contentOffset.y;
//|| _fpsLabel.alpha == 0
if (weakScrollView != scrollView || offsetY < offsetChangeBegin || scrollView.contentSize.height - offsetY - UIScreen.main.bounds.height < 0) {
return;
}
if (lastOffsetY - offsetY > offsetChange) { // 上移
if (self.isUp == true) {
self.isUp = false;
self.scrollBlock?(self.isUp);
}
}
if (offsetY - lastOffsetY > offsetChange) {
if (self.isUp == false) {
self.isUp = true;
self.scrollBlock?(self.isUp);
}
}
lastOffsetY = offsetY;
}
}
|
mit
|
d1dae4e0af497aa5b9af25d31a8b3711
| 36.197143 | 220 | 0.54551 | 5.095499 | false | false | false | false |
creatubbles/ctb-api-swift
|
CreatubblesAPIClient/Sources/Network/ParametersEncoder.swift
|
1
|
3249
|
//
// ParametersEncoder.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
class ParametersEncoder: NSObject {
func encode(_ 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: "&")
}
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 value = value as? NSNumber {
if value.isBool {
components.append((escape(key), escape((value.boolValue ? "1" : "0"))))
} else {
components.append((escape(key), escape("\(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
}
private func escape(_ string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
}
}
extension NSNumber {
fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) }
}
|
mit
|
7cf4953633c5a954f342f226637a82aa
| 40.126582 | 108 | 0.639581 | 4.648069 | false | false | false | false |
banDedo/BDModules
|
HarnessModules/UserDefaults/UserDefaults.swift
|
1
|
1783
|
//
// UserDefaults.swift
// BDModules
//
// Created by Patrick Hogan on 10/24/14.
// Copyright (c) 2014 bandedo. All rights reserved.
//
import Foundation
import MapKit
private let kUserDefaultsLastUserLocationKey = "lastUserLocation"
private let kUserDefaultsLoggerSettingsKey = "loggerSettings"
public let kUserDefaultsLastUserLocationLatitudeKey = "latitude"
public let kUserDefaultsLastUserLocationLongitudeKey = "longitude"
public class UserDefaults {
// MARK:- Injectable
public lazy var suiteName: String = ""
// MARK:- Defaults
public var lastUserLocation: NSDictionary? {
get {
return userDefaults.objectForKey(kUserDefaultsLastUserLocationKey) as? NSDictionary
}
set {
userDefaults.setObject(newValue, forKey: kUserDefaultsLastUserLocationKey)
userDefaults.synchronize()
}
}
public var loggerSettings: LoggerSettings {
get {
if let data = userDefaults.objectForKey(kUserDefaultsLoggerSettingsKey) as? NSData {
let loggerSettings = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! LoggerSettings
return loggerSettings
} else {
return LoggerSettings()
}
}
set {
let data = NSKeyedArchiver.archivedDataWithRootObject(newValue)
userDefaults.setObject(data, forKey: kUserDefaultsLoggerSettingsKey)
userDefaults.synchronize()
}
}
// MARK:- Private properties
private lazy var userDefaults: NSUserDefaults = {
let userDefaults = count(self.suiteName) > 0 ?
NSUserDefaults(suiteName: self.suiteName)! :
NSUserDefaults()
return userDefaults
}()
}
|
apache-2.0
|
0e0b5ff475a2e8f1b5e0f89f8300d10d
| 28.229508 | 103 | 0.65788 | 5.435976 | false | false | false | false |
sdhzwm/BaiSI-Swift-
|
BaiSi/BaiSi/Classes/Essence(精华)/View/WMSubscribedCell.swift
|
1
|
1312
|
//
// WMSubscribedCell.swift
// BaiSi
//
// Created by 王蒙 on 15/7/25.
// Copyright © 2015年 wm. All rights reserved.
//
import UIKit
import SDWebImage
class WMSubscribedCell: UITableViewCell {
@IBOutlet weak var subNuber: UILabel!
@IBOutlet weak var subName: UILabel!
@IBOutlet weak var subImageView: UIImageView!
var subscribed:WMSubscribedTag?{
didSet{
if let subTag = subscribed{
self.subImageView.sd_setImageWithURL(NSURL(string: subTag.image_list), placeholderImage: UIImage(named: "defaultUserIcon"))
self.subName.text = subTag.theme_name
var count:Float = 0.0
if subTag.subscribeNumber > 10000{
count = Float(subTag.subscribeNumber) / Float(10000.0)
self.subNuber.text = String(format: "%.1f万人关注",count)
}else{
self.subNuber.text = String(format: "%ld人关注",subTag.subscribeNumber)
}
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.frame.origin.x += 10
contentView.frame.size.width -= 20
contentView.frame.size.height -= 1
}
}
|
apache-2.0
|
cff537c2bd0275e9f7d3054866bd8442
| 29.738095 | 139 | 0.565453 | 4.391156 | false | false | false | false |
anthonyApptist/Poplur
|
Poplur/AAPLCameraFunctions.swift
|
1
|
7416
|
//
// AAPLCameraFunctions.swift
// PoplurDemo
//
// Created by Anthony Ma on 12/11/2016.
// Copyright © 2016 Anthony Ma. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
extension CameraVCCopy {
func cameraAuthorization() {
previewView.session = session
/*
Check video authorization status. Video access is required and audio
access is optionvar If audio access is denied, audio is not recorded
during movie recording.
*/
switch AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) {
case .authorized:
// The user has previously granted access to the camera.
break
case .notDetermined:
/*
The user has not yet been presented with the option to grant
video access. We suspend the session queue to delay session
setup until the access request has completed.
Note that audio access will be implicitly requested when we
create an AVCaptureDeviceInput for audio during session setup.
*/
sessionQueue.suspend()
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { [unowned self] granted in
if !granted {
self.setupResult = .notAuthorized
}
self.sessionQueue.resume()
})
default:
// The user has previously denied access.
setupResult = .notAuthorized
}
}
func videoOutputSetup() {
if setupResult != .success {
return
}
session.beginConfiguration()
// Add video input.
do {
var defaultVideoDevice: AVCaptureDevice?
// Choose the back dual camera if available, otherwise default to a wide angle camera.
if let dualCameraDevice = AVCaptureDevice.defaultDevice(withDeviceType: .builtInDuoCamera, mediaType: AVMediaTypeVideo, position: .back) {
defaultVideoDevice = dualCameraDevice
}
else if let backCameraDevice = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .back) {
// If the back dual camera is not available, default to the back wide angle camera.
defaultVideoDevice = backCameraDevice
}
else if let frontCameraDevice = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .front) {
// In some cases where users break their phones, the back wide angle camera is not available. In this case, we should default to the front wide angle camera.
defaultVideoDevice = frontCameraDevice
}
let videoDeviceInput = try AVCaptureDeviceInput(device: defaultVideoDevice)
if session.canAddInput(videoDeviceInput) {
session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput
DispatchQueue.main.async {
/*
Why are we dispatching this to the main queue?
Because AVCaptureVideoPreviewLayer is the backing layer for PreviewView and UIView
can only be manipulated on the main thread.
Note: As an exception to the above rule, it is not necessary to serialize video orientation changes
on the AVCaptureVideoPreviewLayer’s connection with other session manipulation.
Use the status bar orientation as the initial video orientation. Subsequent orientation changes are
handled by CameraViewController.viewWillTransition(to:with:).
*/
let statusBarOrientation = UIApplication.shared.statusBarOrientation
var initialVideoOrientation: AVCaptureVideoOrientation = .portrait
if statusBarOrientation != .unknown {
if let videoOrientation = statusBarOrientation.videoOrientation {
initialVideoOrientation = videoOrientation
}
}
self.previewView.videoPreviewLayer.connection.videoOrientation = initialVideoOrientation
}
}
else {
print("Could not add video device input to the session")
setupResult = .configurationFailed
session.commitConfiguration()
return
}
}
catch {
print("Could not create video device input: \(error)")
setupResult = .configurationFailed
session.commitConfiguration()
return
}
// Add audio input.
do {
let audioDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio)
let audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice)
if session.canAddInput(audioDeviceInput) {
session.addInput(audioDeviceInput)
}
else {
print("Could not add audio device input to the session")
}
}
catch {
print("Could not create audio device input: \(error)")
}
// Add movie output
do {
// let videoDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
// let videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice)
//
// session.addInput(videoDeviceInput)
sessionQueue.async { [unowned self] in
let movieFileOutput = AVCaptureMovieFileOutput()
if self.session.canAddOutput(movieFileOutput) {
// self.session.beginConfiguration()
self.session.addOutput(movieFileOutput)
self.session.sessionPreset = AVCaptureSessionPresetHigh
if let connection = movieFileOutput.connection(withMediaType: AVMediaTypeVideo) {
if connection.isVideoStabilizationSupported {
connection.preferredVideoStabilizationMode = .auto
}
}
self.session.commitConfiguration()
self.movieFileOutput = movieFileOutput
DispatchQueue.main.async { [unowned self] in
// self.recordButton.isEnabled = true
}
}
else {
print("Could not add output")
}
}
}
// catch {
// print("Could not create video device input: \(error)")
// }
}
func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
}
}
|
apache-2.0
|
c1f725e06f7409dabf3e4c9efee85c39
| 39.955801 | 173 | 0.563604 | 6.844875 | false | false | false | false |
frootloops/swift
|
test/Constraints/dictionary_literal.swift
|
3
|
5244
|
// RUN: %target-typecheck-verify-swift
final class DictStringInt : ExpressibleByDictionaryLiteral {
typealias Key = String
typealias Value = Int
init(dictionaryLiteral elements: (String, Int)...) { }
}
final class Dictionary<K, V> : ExpressibleByDictionaryLiteral {
typealias Key = K
typealias Value = V
init(dictionaryLiteral elements: (K, V)...) { }
}
func useDictStringInt(_ d: DictStringInt) {}
func useDict<K, V>(_ d: Dictionary<K,V>) {}
// Concrete dictionary literals.
useDictStringInt(["Hello" : 1])
useDictStringInt(["Hello" : 1, "World" : 2])
useDictStringInt(["Hello" : 1, "World" : 2.5]) // expected-error{{cannot convert value of type 'Double' to expected dictionary value type 'Int'}}
useDictStringInt([4.5 : 2]) // expected-error{{cannot convert value of type 'Double' to expected dictionary key type 'String'}}
useDictStringInt([nil : 2]) // expected-error{{nil is not compatible with expected dictionary key type 'String'}}
useDictStringInt([7 : 1, "World" : 2]) // expected-error{{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
// Generic dictionary literals.
useDict(["Hello" : 1])
useDict(["Hello" : 1, "World" : 2])
useDict(["Hello" : 1.5, "World" : 2])
useDict([1 : 1.5, 3 : 2.5])
// Fall back to Dictionary<K, V> if no context is otherwise available.
var a = ["Hello" : 1, "World" : 2]
var a2 : Dictionary<String, Int> = a
var a3 = ["Hello" : 1]
var b = [1 : 2, 1.5 : 2.5]
var b2 : Dictionary<Double, Double> = b
var b3 = [1 : 2.5]
// <rdar://problem/22584076> QoI: Using array literal init with dictionary produces bogus error
// expected-note @+1 {{did you mean to use a dictionary literal instead?}}
var _: Dictionary<String, (Int) -> Int>? = [ // expected-error {{dictionary of type 'Dictionary<String, (Int) -> Int>' cannot be initialized with array literal}}
"closure_1" as String, {(Int) -> Int in 0},
"closure_2", {(Int) -> Int in 0}]
var _: Dictionary<String, Int>? = ["foo", 1] // expected-error {{dictionary of type 'Dictionary<String, Int>' cannot be initialized with array literal}}
// expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}}
var _: Dictionary<String, Int>? = ["foo", 1, "bar", 42] // expected-error {{dictionary of type 'Dictionary<String, Int>' cannot be initialized with array literal}}
// expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}} {{51-52=:}}
var _: Dictionary<String, Int>? = ["foo", 1.0, 2] // expected-error {{cannot convert value of type '[Any]' to specified type 'Dictionary<String, Int>?'}}
var _: Dictionary<String, Int>? = ["foo" : 1.0] // expected-error {{cannot convert value of type 'Double' to expected dictionary value type 'Int'}}
// <rdar://problem/24058895> QoI: Should handle [] in dictionary contexts better
var _: [Int: Int] = [] // expected-error {{use [:] to get an empty dictionary literal}} {{22-22=:}}
class A { }
class B : A { }
class C : A { }
func testDefaultExistentials() {
let _ = ["a" : 1, "b" : 2.5, "c" : "hello"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<String, Any>'; add explicit type annotation if this is intentional}}{{46-46= as Dictionary<String, Any>}}
let _: [String : Any] = ["a" : 1, "b" : 2.5, "c" : "hello"]
let _ = ["a" : 1, "b" : nil, "c" : "hello"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<String, Any?>'; add explicit type annotation if this is intentional}}{{46-46= as Dictionary<String, Any?>}}
let _: [String : Any?] = ["a" : 1, "b" : nil, "c" : "hello"]
let d2 = [:]
// expected-error@-1{{empty collection literal requires an explicit type}}
let _: Int = d2 // expected-error{{value of type 'Dictionary<AnyHashable, Any>'}}
let _ = ["a": 1,
"b": ["a", 2, 3.14159],
"c": ["a": 2, "b": 3.5]]
// expected-error@-3{{heterogeneous collection literal could only be inferred to 'Dictionary<String, Any>'; add explicit type annotation if this is intentional}}
let d3 = ["b" : B(), "c" : C()]
let _: Int = d3 // expected-error{{value of type 'Dictionary<String, A>'}}
let _ = ["a" : B(), 17 : "seventeen", 3.14159 : "Pi"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<AnyHashable, Any>'}}
let _ = ["a" : "hello", 17 : "string"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<AnyHashable, String>'}}
}
// SR-4952, rdar://problem/32330004 - Assertion failure during swift::ASTVisitor<::FailureDiagnosis,...>::visit
func rdar32330004_1() -> [String: Any] {
return ["a""one": 1, "two": 2, "three": 3] // expected-note {{did you mean to use a dictionary literal instead?}}
// expected-error@-1 2 {{expected ',' separator}}
// expected-error@-2 {{dictionary of type '[String : Any]' cannot be used with array literal}}
}
func rdar32330004_2() -> [String: Any] {
return ["a", 0, "one", 1, "two", 2, "three", 3]
// expected-error@-1 {{dictionary of type '[String : Any]' cannot be used with array literal}}
// expected-note@-2 {{did you mean to use a dictionary literal instead?}} {{14-15=:}} {{24-25=:}} {{34-35=:}} {{46-47=:}}
}
|
apache-2.0
|
f3cd74fe8781159282b6072a73fa2a7a
| 45.821429 | 202 | 0.650267 | 3.475149 | false | false | false | false |
kshala-ford/sdl_ios
|
SmartDeviceLink_Example/ConnectionIAPTableViewController.swift
|
2
|
2229
|
//
// ConnectionIAPTableViewController.swift
// SmartDeviceLink-ExampleSwift
//
// Copyright © 2017 smartdevicelink. All rights reserved.
//
import UIKit
class ConnectionIAPTableViewController: UITableViewController, ProxyManagerDelegate {
@IBOutlet weak var connectTableViewCell: UITableViewCell!
@IBOutlet weak var table: UITableView!
@IBOutlet weak var connectButton: UIButton!
var state: ProxyState = .stopped
override func viewDidLoad() {
super.viewDidLoad()
ProxyManager.sharedManager.delegate = self
table.keyboardDismissMode = .onDrag
table.isScrollEnabled = false
initButton()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func initButton() {
self.connectTableViewCell.backgroundColor = UIColor.red
self.connectButton.setTitle("Connect", for: .normal)
self.connectButton.setTitleColor(.white, for: .normal)
}
// MARK: - IBActions
@IBAction func connectButtonWasPressed(_ sender: UIButton) {
switch state {
case .stopped:
ProxyManager.sharedManager.start(with: .iap)
case .searching:
ProxyManager.sharedManager.resetConnection()
case .connected:
ProxyManager.sharedManager.resetConnection()
}
}
// MARK: - Delegate Functions
func didChangeProxyState(_ newState: ProxyState) {
state = newState
var newColor: UIColor? = nil
var newTitle: String? = nil
switch newState {
case .stopped:
newColor = UIColor.red
newTitle = "Connect"
case .searching:
newColor = UIColor.blue
newTitle = "Stop Searching"
case .connected:
newColor = UIColor.green
newTitle = "Disconnect"
}
if (newColor != nil) || (newTitle != nil) {
DispatchQueue.main.async(execute: {[weak self]() -> Void in
self?.connectTableViewCell.backgroundColor = newColor
self?.connectButton.setTitle(newTitle, for: .normal)
self?.connectButton.setTitleColor(.white, for: .normal)
})
}
}
}
|
bsd-3-clause
|
9b281af833bf96c9d145a4f6367ada09
| 29.944444 | 85 | 0.62702 | 5.063636 | false | false | false | false |
mapsme/omim
|
iphone/Maps/Bookmarks/Catalog/Dialogs/SubscriptionSuccessViewController.swift
|
4
|
1210
|
class SubscriptionSuccessViewController: UIViewController {
private let transitioning = FadeTransitioning<AlertPresentationController>()
private let onOk: MWMVoidBlock
private let screenType: SubscriptionGroupType
@IBOutlet private var titleLabel: UILabel!
@IBOutlet private var textLabel: UILabel!
init(_ screenType: SubscriptionGroupType, onOk: @escaping MWMVoidBlock) {
self.onOk = onOk
self.screenType = screenType
super.init(nibName: nil, bundle: nil)
transitioningDelegate = transitioning
modalPresentationStyle = .custom
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
switch screenType {
case .city:
titleLabel.text = L("subscription_success_dialog_title_sightseeing_pass")
textLabel.text = L("subscription_success_dialog_message_sightseeing_pass")
case .allPass:
titleLabel.text = L("subscription_success_dialog_title")
textLabel.text = L("subscription_success_dialog_message")
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func onOk(_ sender: UIButton) {
onOk()
}
}
|
apache-2.0
|
8e6550341d6caf0cae8a63b4e017a069
| 29.25 | 80 | 0.72314 | 4.498141 | false | false | false | false |
tottakai/RxSwift
|
RxExample/RxExample/Examples/TableViewWithEditingCommands/RandomUserAPI.swift
|
8
|
1699
|
//
// RandomUserAPI.swift
// RxExample
//
// Created by carlos on 28/5/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
class RandomUserAPI {
static let sharedAPI = RandomUserAPI()
private init() {}
func getExampleUserResultSet() -> Observable<[User]> {
let url = URL(string: "http://api.randomuser.me/?results=20")!
return URLSession.shared.rx.json(url: url)
.map { json in
guard let json = json as? [String: AnyObject] else {
throw exampleError("Casting to dictionary failed")
}
return try self.parseJSON(json)
}
}
private func parseJSON(_ json: [String: AnyObject]) throws -> [User] {
guard let results = json["results"] as? [[String: AnyObject]] else {
throw exampleError("Can't find results")
}
let userParsingError = exampleError("Can't parse user")
let searchResults: [User] = try results.map { user in
let name = user["name"] as? [String: String]
let pictures = user["picture"] as? [String: String]
guard let firstName = name?["first"], let lastName = name?["last"], let imageURL = pictures?["medium"] else {
throw userParsingError
}
let returnUser = User(
firstName: firstName.capitalized,
lastName: lastName.capitalized,
imageURL: imageURL
)
return returnUser
}
return searchResults
}
}
|
mit
|
0de8118bc10bc58be8e43953357081f8
| 28.789474 | 121 | 0.545347 | 4.810198 | false | false | false | false |
ludagoo/Perfect
|
PerfectLib/PerfectObjectHandler.swift
|
2
|
2392
|
//
// PerfectObjectHandler.swift
// PerfectLib
//
// Created by Kyle Jessup on 2015-08-18.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// 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 Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
public class PerfectObjectHandler: PageHandler {
public var action: HandlerAction = .None
public var params = [String:String]()
public init() {}
public func valuesForResponse(context: MustacheEvaluationContext, collector: MustacheEvaluationOutputCollector) throws -> MustacheEvaluationContext.MapType {
// determine the action
let param = context.webResponse!.request.param(actionParamName) ?? HandlerAction.None.asString()
self.action = HandlerAction.fromString(param)
// pull in the meaningful parameters
if let rawParams = context.webResponse!.request.params() {
// ignore "meta"
for (n, v) in rawParams where !n.hasPrefix("_") && !n.hasPrefix("$") {
self.params[n] = v
}
}
context.webResponse!.replaceHeader("Content-type", value: "application/json")
collector.defaultEncodingFunc = {
(s:String) -> String in
var outS = ""
for char in s.characters.generate() {
switch char {
case "\\":
outS.appendContentsOf("\\\\")
case "\"":
outS.appendContentsOf("\\\"")
case "\n":
outS.appendContentsOf("\\n")
case "\r":
outS.appendContentsOf("\\n")
case "\t":
outS.appendContentsOf("\\t")
default:
outS.append(char)
}
}
return outS
}
return MustacheEvaluationContext.MapType()
}
}
|
agpl-3.0
|
8bf337965101d6677cfbf52295743811
| 30.064935 | 158 | 0.702759 | 3.839486 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker
|
Pods/HXPHPicker/Sources/HXPHPicker/Editor/View/EditorChartletViewCell.swift
|
1
|
3862
|
//
// EditorChartletViewCell.swift
// HXPHPicker
//
// Created by Slience on 2021/8/25.
//
import UIKit
#if canImport(Kingfisher)
import Kingfisher
#endif
class EditorChartletViewCell: UICollectionViewCell {
lazy var selectedBgView: UIVisualEffectView = {
let effect = UIBlurEffect(style: .dark)
let view = UIVisualEffectView(effect: effect)
view.isHidden = true
view.layer.cornerRadius = 5
view.layer.masksToBounds = true
return view
}()
lazy var imageView: ImageView = {
let view = ImageView()
view.imageView.contentMode = .scaleAspectFit
return view
}()
var editorType: EditorController.EditorType = .photo
var downloadCompletion = false
var titleChartlet: EditorChartletTitle! {
didSet {
selectedBgView.isHidden = !titleChartlet.isSelected
#if canImport(Kingfisher)
setupImage(image: titleChartlet.image, url: titleChartlet.url)
#else
setupImage(image: titleChartlet.image)
#endif
}
}
var isSelectedTitle: Bool = false {
didSet {
titleChartlet.isSelected = isSelectedTitle
selectedBgView.isHidden = !titleChartlet.isSelected
}
}
var showSelectedBgView: Bool = false {
didSet {
selectedBgView.isHidden = !showSelectedBgView
}
}
var chartlet: EditorChartlet! {
didSet {
selectedBgView.isHidden = true
#if canImport(Kingfisher)
setupImage(image: chartlet.image, url: chartlet.url)
#else
setupImage(image: chartlet.image)
#endif
}
}
func setupImage(image: UIImage?, url: URL? = nil) {
downloadCompletion = false
imageView.image = nil
#if canImport(Kingfisher)
if let image = image {
imageView.image = image
downloadCompletion = true
}else if let url = url {
imageView.my.kf.indicatorType = .activity
(imageView.my.kf.indicator?.view as? UIActivityIndicatorView)?.color = .white
let processor = DownsamplingImageProcessor(
size: CGSize(
width: width * 2,
height: height * 2
)
)
let options: KingfisherOptionsInfo
if url.isGif && editorType == .video {
options = [.memoryCacheExpiration(.expired)]
}else {
options = [
.cacheOriginalImage,
.processor(processor),
.backgroundDecode
]
}
imageView.my.kf.setImage(
with: url,
options: options
) { [weak self] result in
switch result {
case .success(_):
self?.downloadCompletion = true
default:
break
}
}
}
#else
if let image = image {
imageView.image = image
}
#endif
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(selectedBgView)
contentView.addSubview(imageView)
}
override func layoutSubviews() {
super.layoutSubviews()
selectedBgView.frame = bounds
if titleChartlet != nil {
imageView.size = CGSize(width: 25, height: 25)
imageView.center = CGPoint(x: width * 0.5, y: height * 0.5)
}else {
imageView.frame = CGRect(x: 5, y: 5, width: width - 10, height: height - 10)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
27695d5810cf54cd4be73ad50b471048
| 28.707692 | 89 | 0.540394 | 5.041775 | false | false | false | false |
fitpay/wearable-test-harness
|
Wearable Test Harness/FitpayBleServiceConstants.swift
|
1
|
1921
|
//
// FitpayBleServiceConstants.swift
// Wearable Test Harness
//
// Created by Tim Shanahan on 3/16/16.
// Copyright © 2016 Scott Stevelinck. All rights reserved.
//
import Foundation
import CoreBluetooth
enum FitpayServiceUUID: String {
case PaymentServiceUUID = "d7cc1dc2-3603-4e71-bce6-e3b1551633e0"
case DeviceInfoServiceUUID = "0000180a-0000-1000-8000-00805f9b34fb"
}
enum FitpayPaymentCharacteristicUUID: String {
case APDUControlCharacteristic = "0761f49b-5f56-4008-b203-fd2406db8c20"
case APDUResultCharacteristic = "840f2622-ff4a-4a56-91ab-b1e6dd977db4"
case ContinuationControlCharacteristic = "cacc2825-0a2b-4cf2-a1a4-b9db27691382"
case ContinuationPacketCharacteristic = "52d26993-6d10-4080-8166-35d11cf23c8c"
case SecureElementIdCharacteristic = "1251697c-0826-4166-a3c0-72704954c32d"
case NotificationCharacteristic = "37051cf0-d70e-4b3c-9e90-0f8e9278b4d3"
case SecurityWriteCharacteristic = "e4bbb38f-5aaa-4056-8cf0-57461082d598"
case SecurityStateCharacteristic = "ab1fe5e7-4e9d-4b8c-963f-5265dc7de466"
case DeviceControlCharacteristic = "50b50f72-d10a-444b-945d-d574bd67ec91"
case ApplicationStatusCharacteristic = "6fea71ab-14ca-4921-b166-e8742e349975"
}
enum FitpayDeviceInfoCharacteristicUUID: String {
case CHARACTERISTIC_MANUFACTURER_NAME_STRING = "00002a29-0000-1000-8000-00805f9b34fb"
case CHARACTERISTIC_MODEL_NUMBER_STRING = "00002a24-0000-1000-8000-00805f9b34fb"
case CHARACTERISTIC_SERIAL_NUMBER_STRING = "00002a25-0000-1000-8000-00805f9b34fb"
case CHARACTERISTIC_FIRMWARE_REVISION_STRING = "00002a26-0000-1000-8000-00805f9b34fb"
case CHARACTERISTIC_HARDWARE_REVISION_STRING = "00002a27-0000-1000-8000-00805f9b34fb"
case CHARACTERISTIC_SOFTWARE_REVISION_STRING = "00002a28-0000-1000-8000-00805f9b34fb"
case CHARACTERISTIC_SYSTEM_ID = "00002a23-0000-1000-8000-00805f9b34fb"
}
|
mit
|
21c41a2a205a8126be2c9e9a1ae01396
| 40.73913 | 89 | 0.781771 | 2.750716 | false | false | false | false |
prebid/prebid-mobile-ios
|
InternalTestApp/PrebidMobileDemoRendering/ViewControllers/Adapters/Prebid/MAX/PrebidMAXNativeController.swift
|
1
|
7382
|
/* Copyright 2018-2021 Prebid.org, 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 PrebidMobile
import AppLovinSDK
import PrebidMobileMAXAdapters
class PrebidMAXNativeController: NSObject, AdaptedController {
public var maxAdUnitId = ""
public var prebidConfigId = ""
public var storedAuctionResponse = ""
public var nativeAssets: [NativeAsset]?
public var eventTrackers: [NativeEventTracker]?
private var nativeAdUnit: MediationNativeAdUnit!
private var mediationDelegate: MAXMediationNativeUtils!
private var nativeAdLoader: MANativeAdLoader?
private var loadedNativeAd: MAAd?
private weak var rootController: AdapterViewController?
private let fetchDemandFailedButton = EventReportContainer()
private let didLoadNativeAdButton = EventReportContainer()
private let didFailToLoadNativeAdButton = EventReportContainer()
private let didClickNativeAdButton = EventReportContainer()
required init(rootController: AdapterViewController) {
super.init()
self.rootController = rootController
setupActions(rootController: rootController)
}
deinit {
Prebid.shared.storedAuctionResponse = nil
}
func loadAd() {
Prebid.shared.storedAuctionResponse = storedAuctionResponse
setUpBannerArea(rootController: rootController!)
nativeAdLoader = MANativeAdLoader(adUnitIdentifier: maxAdUnitId)
nativeAdLoader?.nativeAdDelegate = self
mediationDelegate = MAXMediationNativeUtils(nativeAdLoader: nativeAdLoader!)
nativeAdUnit = MediationNativeAdUnit(configId: prebidConfigId, mediationDelegate: mediationDelegate)
nativeAdUnit.setContextType(ContextType.Social)
nativeAdUnit.setPlacementType(PlacementType.FeedContent)
nativeAdUnit.setContextSubType(ContextSubType.Social)
if let nativeAssets = nativeAssets {
nativeAdUnit.addNativeAssets(nativeAssets)
}
if let eventTrackers = eventTrackers {
nativeAdUnit.addEventTracker(eventTrackers)
}
if let userData = AppConfiguration.shared.userData {
for dataPair in userData {
let appData = PBMORTBContentData()
appData.ext = [dataPair.key: dataPair.value]
nativeAdUnit?.addUserData([appData])
}
}
if let appData = AppConfiguration.shared.appContentData {
for dataPair in appData {
let appData = PBMORTBContentData()
appData.ext = [dataPair.key: dataPair.value]
nativeAdUnit?.addAppContentData([appData])
}
}
nativeAdUnit.fetchDemand { [weak self] result in
guard let self = self else { return }
if result != .prebidDemandFetchSuccess {
self.fetchDemandFailedButton.isEnabled = true
}
self.nativeAdLoader?.loadAd(into: self.createNativeAdView())
}
}
private func setUpBannerArea(rootController: AdapterViewController) {
guard let bannerView = rootController.bannerView else {
return
}
let bannerConstraints = bannerView.constraints
bannerView.removeConstraint(bannerConstraints.first { $0.firstAttribute == .width }!)
bannerView.removeConstraint(bannerConstraints.first { $0.firstAttribute == .height }!)
if let bannerParent = bannerView.superview {
let bannerHeightConstraint = bannerView.heightAnchor.constraint(equalToConstant: 200)
bannerHeightConstraint.priority = .defaultLow
let bannerWidthConstraint = NSLayoutConstraint(item: bannerView,
attribute: .width,
relatedBy: .lessThanOrEqual,
toItem: bannerParent,
attribute: .width,
multiplier: 1,
constant: -10)
NSLayoutConstraint.activate([bannerWidthConstraint, bannerHeightConstraint])
}
}
private func createNativeAdView() -> MANativeAdView {
let nativeAdViewNib = UINib(nibName: "MAXNativeAdView", bundle: Bundle.main)
let nativeAdView = nativeAdViewNib.instantiate(withOwner: nil, options: nil).first! as! MANativeAdView?
let adViewBinder = MANativeAdViewBinder.init(builderBlock: { (builder) in
builder.iconImageViewTag = 1
builder.titleLabelTag = 2
builder.bodyLabelTag = 3
builder.advertiserLabelTag = 4
builder.callToActionButtonTag = 5
builder.mediaContentViewTag = 123
})
nativeAdView!.bindViews(with: adViewBinder)
return nativeAdView!
}
private func setupActions(rootController: AdapterViewController) {
rootController.setupAction(fetchDemandFailedButton, "fetchDemandFailed called")
rootController.setupAction(didLoadNativeAdButton, "didLoadNativeAd called")
rootController.setupAction(didFailToLoadNativeAdButton, "didFailToLoadNativeAd called")
rootController.setupAction(didClickNativeAdButton, "didClickNativeAd called")
}
}
extension PrebidMAXNativeController: MANativeAdDelegate {
func didLoadNativeAd(_ nativeAdView: MANativeAdView?, for ad: MAAd) {
didLoadNativeAdButton.isEnabled = true
if let nativeAd = loadedNativeAd {
nativeAdLoader?.destroy(nativeAd)
}
guard let bannerView = rootController?.bannerView else {
return
}
rootController?.showButton.isHidden = true
bannerView.backgroundColor = .clear
loadedNativeAd = ad
nativeAdView?.translatesAutoresizingMaskIntoConstraints = false
bannerView.addSubview(nativeAdView!)
bannerView.heightAnchor.constraint(equalTo: nativeAdView!.heightAnchor).isActive = true
bannerView.topAnchor.constraint(equalTo: nativeAdView!.topAnchor).isActive = true
bannerView.leftAnchor.constraint(equalTo: nativeAdView!.leftAnchor).isActive = true
bannerView.rightAnchor.constraint(equalTo: nativeAdView!.rightAnchor).isActive = true
}
func didFailToLoadNativeAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) {
didFailToLoadNativeAdButton.isEnabled = true
}
func didClickNativeAd(_ ad: MAAd) {
didClickNativeAdButton.isEnabled = true
}
}
|
apache-2.0
|
cb4c7ee5d935105ea8e137a82bbdfa0e
| 39.278689 | 111 | 0.652557 | 5.74961 | false | false | false | false |
dnseitz/YAPI
|
project-alpha/project-alpha/ViewController.swift
|
1
|
1325
|
//
// ViewController.swift
// project-alpha
//
// Created by Daniel Seitz on 11/12/17.
// Copyright © 2017 freebird. All rights reserved.
//
import UIKit
import YAPI
class ViewController: UIViewController {
private func getKeys() -> [String: String] {
guard
let path = Bundle.main.path(forResource: "secrets", ofType: "plist"),
let keys = NSDictionary(contentsOfFile: path) as? [String: String]
else {
assertionFailure("Unable to load secrets property list, contact [email protected] if you need the file")
return [:]
}
return keys
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let keys = getKeys()
guard
let appId = keys["APP_ID"],
let clientSecret = keys["CLIENT_SECRET"]
else {
assertionFailure("Unable to retrieve appId or clientSecret from file")
return
}
YelpAPIFactory.V3.authenticate(appId: appId, clientSecret: clientSecret) { error in
if let error = error {
print("\(error)")
}
else {
print("Authenticated")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
302c932de0545812da7f1e140cedac77
| 23.072727 | 112 | 0.636707 | 4.428094 | false | false | false | false |
kevinli194/CancerCenterPrototype
|
CancerInstituteDemo/CancerInstituteDemo/Resources/TravelDetailViewController.swift
|
1
|
994
|
//
// TravelDetailViewController.swift
// CancerInstituteDemo
//
// Created by Anna Benson on 11/9/15.
// Copyright © 2015 KAG. All rights reserved.
//
import UIKit
class TravelDetailViewController: UIViewController {
var myTitle: String?
var myDescription: String?
var myImage: String?
@IBOutlet weak var curTitle: UILabel!
@IBOutlet weak var curDescription: UILabel!
@IBOutlet weak var curImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "blueGradient.jpg")!)
curTitle.text = myTitle
curDescription.text = myDescription
curImage.image = UIImage(named: myImage!)
//make images circular
curImage.layer.cornerRadius = curImage.frame.size.width/2
curImage.clipsToBounds = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
mit
|
2e42324cfb0dbada72fc139b21f2d908
| 25.131579 | 94 | 0.669688 | 4.513636 | false | false | false | false |
proversity-org/edx-app-ios
|
Source/Dictionary+SafeAccess.swift
|
2
|
2072
|
//
// Dictionary+SafeAccess.swift
// edX
//
// Created by Kyle McCormick on 7/10/17.
// Copyright (c) 2017 edX. All rights reserved.
//
import Foundation
extension NSMutableDictionary {
/// Variant of setObject:forKey: that doesn't crash if the object is nil.
/// Instead, it will just do nothing.
/// This is for cases where you may or may not have an object.
/// Contrast with NSMutableDictionary.setSafeObject:forKey:
@objc public func setObjectOrNil(_ object: Value?, forKey: Key) {
if let obj = object {
self[forKey] = obj
}
}
/// Variant of setObject:forKey: that doesn't crash if the object is nil.
/// Instead, it will assert on DEBUG builds and console log on RELEASE builds
/// This is for cases where you're expecting to have an object
/// but you don't want to crash if for some reason you don't.
/// Contrast with NSMutableDictionary.setObjectOrNil:forKey:
@objc public func setSafeObject(_ object: Value?, forKey: Key) {
setObjectOrNil(object, forKey: forKey)
if object == nil {
#if DEBUG
assert(false, "Expecting object for key: \(forKey)");
#else
Logger.logError("FOUNDATION", "Expecting object for key: \(forKey)");
#endif
}
}
}
extension Dictionary {
/// Same as NSMutableDictionary.setObjectOrNil:forKey:, but for
/// Swift dictionaries
public mutating func setObjectOrNil(_ object: Value?, forKey: Key) {
if let obj = object {
self[forKey] = obj
}
}
/// Same as NSMutableDictionary.setSafeObject:forKey:, but for
/// Swift dictionaries
public mutating func setSafeObject(_ object: Value?, forKey: Key) {
setObjectOrNil(object, forKey: forKey)
if object == nil {
#if DEBUG
assert(false, "Expecting object for key: \(forKey)");
#else
Logger.logError("FOUNDATION", "Expecting object for key: \(forKey)");
#endif
}
}
}
|
apache-2.0
|
c353676f9dfa9995ac852ce50b4af5d0
| 33.533333 | 85 | 0.612452 | 4.514161 | false | false | false | false |
nheagy/WordPress-iOS
|
WordPress/Classes/Networking/Remote Objects/RemoteBlogSettings.swift
|
1
|
5184
|
import Foundation
/// This class encapsulates all of the *remote* settings available for a Blog entity
///
public class RemoteBlogSettings : NSObject
{
// MARK: - General
/// Represents the Blog Name.
///
var name : String?
/// Stores the Blog's Tagline setting.
///
var tagline : String?
/// Stores the Blog's Privacy Preferences Settings
///
var privacy : NSNumber?
/// Stores the Blog's Language ID Setting
///
var languageID : NSNumber?
// MARK: - Writing
/// Contains the Default Category ID. Used when creating new posts.
///
var defaultCategoryID : NSNumber?
/// Contains the Default Post Format. Used when creating new posts.
///
var defaultPostFormat : String?
// MARK: - Discussion
/// Represents whether comments are allowed, or not.
///
var commentsAllowed : NSNumber?
/// Contains a list of words that would automatically blacklist a comment.
///
var commentsBlacklistKeys : String?
/// If true, comments will be automatically closed after the number of days, specified by `commentsCloseAutomaticallyAfterDays`.
///
var commentsCloseAutomatically : NSNumber?
/// Represents the number of days comments will be enabled, granted that the `commentsCloseAutomatically`
/// property is set to true.
///
var commentsCloseAutomaticallyAfterDays : NSNumber?
/// When enabled, comments from known users will be whitelisted.
///
var commentsFromKnownUsersWhitelisted : NSNumber?
/// Indicates the maximum number of links allowed per comment. When a new comment exceeds this number,
/// it'll be held in queue for moderation.
///
var commentsMaximumLinks : NSNumber?
/// Contains a list of words that cause a comment to require moderation.
///
var commentsModerationKeys : String?
/// If true, comment pagination will be enabled.
///
var commentsPagingEnabled : NSNumber?
/// Specifies the number of comments per page. This will be used only if the property `commentsPagingEnabled`
/// is set to true.
///
var commentsPageSize : NSNumber?
/// When enabled, new comments will require Manual Moderation, before showing up.
///
var commentsRequireManualModeration : NSNumber?
/// If set to true, commenters will be required to enter their name and email.
///
var commentsRequireNameAndEmail : NSNumber?
/// Specifies whether commenters should be registered or not.
///
var commentsRequireRegistration : NSNumber?
/// Indicates the sorting order of the comments. Ascending / Descending, based on the date.
///
var commentsSortOrder : String?
/// Indicates the number of levels allowed per comment.
///
var commentsThreadingDepth : NSNumber?
/// When enabled, comment threading will be supported.
///
var commentsThreadingEnabled : NSNumber?
/// If set to true, 3rd party sites will be allowed to post pingbacks.
///
var pingbackInboundEnabled : NSNumber?
/// When Outbound Pingbacks are enabled, 3rd party sites that get linked will be notified.
///
var pingbackOutboundEnabled : NSNumber?
// MARK: - Related Posts
/// When set to true, Related Posts will be allowed.
///
var relatedPostsAllowed : NSNumber?
/// When set to true, Related Posts will be enabled.
///
var relatedPostsEnabled : NSNumber?
/// Indicates whether related posts should show a headline.
///
var relatedPostsShowHeadline : NSNumber?
/// Indicates whether related posts should show thumbnails.
///
var relatedPostsShowThumbnails : NSNumber?
// MARK: - Sharing
/// Indicates the style to use for the sharing buttons on a particular blog..
///
var sharingButtonStyle : String?
/// The title of the sharing label on the user's blog.
///
var sharingLabel : String?
/// Indicates the twitter username to use when sharing via Twitter
///
var sharingTwitterName : String?
/// Indicates whether related posts should show thumbnails.
///
var sharingCommentLikesEnabled : NSNumber?
/// Indicates whether sharing via post likes has been disabled
///
var sharingDisabledLikes : NSNumber?
/// Indicates whether sharing by reblogging has been disabled
///
var sharingDisabledReblogs : NSNumber?
// MARK: - Helpers
/// Computed property, meant to help conversion from Remote / String-Based values, into their Integer counterparts
///
var commentsSortOrderAscending : Bool {
set {
commentsSortOrder = newValue ? RemoteBlogSettings.AscendingStringValue : RemoteBlogSettings.DescendingStringValue
}
get {
return commentsSortOrder == RemoteBlogSettings.AscendingStringValue
}
}
// MARK: - Private
private static let AscendingStringValue = "asc"
private static let DescendingStringValue = "desc"
}
|
gpl-2.0
|
0710018d761ec21f0025687ae584695a
| 27.8 | 132 | 0.6549 | 5.23108 | false | false | false | false |
fhacktory/SoundPoll
|
SoundPool/SoundPool/Librairies/Alamofire-SwiftyJSON/Alamofire.swift
|
2
|
69144
|
// Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire (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
import UIKit.UIImage
/// Alamofire errors
public let AlamofireErrorDomain = "com.alamofire.error"
/**
HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
/**
Used to specify the way in which a set of parameters are applied to a URL request.
*/
public enum ParameterEncoding {
/**
A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
*/
case URL
/**
Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
*/
case JSON
/**
Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
*/
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
/**
Uses the associated closure value to construct a new request given an existing request and parameters.
*/
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
:param: URLRequest The request to have parameters applied
:param: parameters The parameters to apply
:returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
*/
public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (URLRequest.URLRequest, nil)
}
var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
let method = Method(rawValue: mutableURLRequest.HTTPMethod)
if method != nil && encodesParametersInURL(method!) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parameters!)
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON:
let options = NSJSONWritingOptions.allZeros
if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .Custom(let closure):
return closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, error)
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escape(key), escape("\(value)"))])
}
return components
}
func escape(string: String) -> String {
let legalURLCharactersToBeEscaped: CFStringRef = ":/?&=;+!@#$()',*"
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue)
}
}
// MARK: - URLStringConvertible
/**
Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests.
*/
public protocol URLStringConvertible {
/// The URL string.
var URLString: String { get }
}
extension String: URLStringConvertible {
public var URLString: String {
return self
}
}
extension NSURL: URLStringConvertible {
public var URLString: String {
return absoluteString!
}
}
extension NSURLComponents: URLStringConvertible {
public var URLString: String {
return URL!.URLString
}
}
extension NSURLRequest: URLStringConvertible {
public var URLString: String {
return URL.URLString
}
}
// MARK: - URLRequestConvertible
/**
Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
*/
public protocol URLRequestConvertible {
/// The URL request.
var URLRequest: NSURLRequest { get }
}
extension NSURLRequest: URLRequestConvertible {
public var URLRequest: NSURLRequest {
return self
}
}
// MARK: -
/**
Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
When finished with a manager, be sure to call either `session.finishTasksAndInvalidate()` or `session.invalidateAndCancel()` before deinitialization.
*/
public class Manager {
/**
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly for any ad hoc requests.
*/
public class var sharedInstance: Manager {
struct Singleton {
static var configuration: NSURLSessionConfiguration = {
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders()
return configuration
}()
static let instance = Manager(configuration: configuration)
}
return Singleton.instance
}
/**
Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
:returns: The default header values.
*/
public class func defaultHTTPHeaders() -> [String: String] {
// Accept-Encoding HTTP Header; see http://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 http://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage: String = {
var components: [String] = []
for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as [String]) {
let q = 1.0 - (Double(index) * 0.1)
components.append("\(languageCode);q=\(q)")
if q <= 0.5 {
break
}
}
return join(",", components)
}()
// User-Agent Header; see http://tools.ietf.org/html/rfc7231#section-5.5.3
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject = info[kCFBundleExecutableKey] ?? "Unknown"
let bundle: AnyObject = info[kCFBundleIdentifierKey] ?? "Unknown"
let version: AnyObject = info[kCFBundleVersionKey] ?? "Unknown"
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
return mutableUserAgent as NSString
}
}
return "Alamofire"
}()
return ["Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent]
}
private let delegate: SessionDelegate
private let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
/// The underlying session.
public let session: NSURLSession
/// Whether to start requests immediately after being constructed. `true` by default.
public var startRequestsImmediately: Bool = true
/**
:param: configuration The configuration used to construct the managed session.
*/
required public init(configuration: NSURLSessionConfiguration? = nil) {
self.delegate = SessionDelegate()
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
}
// MARK: -
/**
Creates a request for the specified method, URL string, parameters, and parameter encoding.
:param: method The HTTP method.
:param: URLString The URL string.
:param: parameters The parameters. `nil` by default.
:param: encoding The parameter encoding. `.URL` by default.
:returns: The created request.
*/
public func request(method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
return request(encoding.encode(URLRequest(method, URLString), parameters: parameters).0)
}
/**
Creates a request for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
var dataTask: NSURLSessionDataTask?
dispatch_sync(queue) {
dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest)
}
let request = Request(session: session, task: dataTask!)
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
private subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) {
subdelegate = self.subdelegates[task.taskIdentifier]
}
return subdelegate
}
set {
dispatch_barrier_async(subdelegateQueue) {
self.subdelegates[task.taskIdentifier] = newValue
}
}
}
var sessionDidBecomeInvalidWithError: ((NSURLSession!, NSError!) -> Void)?
var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession!) -> Void)?
var sessionDidReceiveChallenge: ((NSURLSession!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
required override init() {
self.subdelegates = Dictionary()
super.init()
}
// MARK: NSURLSessionDelegate
func URLSession(session: NSURLSession!, didBecomeInvalidWithError error: NSError!) {
sessionDidBecomeInvalidWithError?(session, error)
}
func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
if sessionDidReceiveChallenge != nil {
completionHandler(sessionDidReceiveChallenge!(session, challenge))
} else {
completionHandler(.PerformDefaultHandling, nil)
}
}
func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession!) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
var redirectRequest = request
if taskWillPerformHTTPRedirection != nil {
redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
} else {
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
self[task] = nil
}
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
var disposition: NSURLSessionResponseDisposition = .Allow
if dataTaskDidReceiveResponse != nil {
disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
dataTaskDidReceiveData?(session, dataTask, data)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
var cachedResponse = proposedResponse
if dataTaskWillCacheResponse != nil {
cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
}
downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
}
downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
}
// MARK: NSObject
override func respondsToSelector(selector: Selector) -> Bool {
switch selector {
case "URLSession:didBecomeInvalidWithError:":
return (sessionDidBecomeInvalidWithError != nil)
case "URLSession:didReceiveChallenge:completionHandler:":
return (sessionDidReceiveChallenge != nil)
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return (sessionDidFinishEventsForBackgroundURLSession != nil)
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
return (taskWillPerformHTTPRedirection != nil)
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return (dataTaskDidReceiveResponse != nil)
case "URLSession:dataTask:willCacheResponse:completionHandler:":
return (dataTaskWillCacheResponse != nil)
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
// MARK: -
/**
Responsible for sending a request and receiving the response and associated data from the server, as well as managing its underlying `NSURLSessionTask`.
*/
public class Request {
private let delegate: TaskDelegate
/// The underlying task.
public var task: NSURLSessionTask { return delegate.task }
/// The session belonging to the underlying task.
public let session: NSURLSession
/// The request sent or to be sent to the server.
public var request: NSURLRequest { return task.originalRequest }
/// The response received from the server, if any.
public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
/// The progress of the request lifecycle.
public var progress: NSProgress? { return delegate.progress }
private init(session: NSURLSession, task: NSURLSessionTask) {
self.session = session
switch task {
case is NSURLSessionUploadTask:
self.delegate = UploadTaskDelegate(task: task)
case is NSURLSessionDataTask:
self.delegate = DataTaskDelegate(task: task)
case is NSURLSessionDownloadTask:
self.delegate = DownloadTaskDelegate(task: task)
default:
self.delegate = TaskDelegate(task: task)
}
}
// MARK: Authentication
/**
Associates an HTTP Basic credential with the request.
:param: user The user.
:param: password The password.
:returns: The request.
*/
public func authenticate(#user: String, password: String) -> Self {
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
return authenticate(usingCredential: credential)
}
/**
Associates a specified credential with the request.
:param: credential The credential.
:returns: The request.
*/
public func authenticate(usingCredential credential: NSURLCredential) -> Self {
delegate.credential = credential
return self
}
// MARK: Progress
/**
Sets a closure to be called periodically during the lifecycle of the request as data is written to or read from the server.
- For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected to write.
- For downloads, the progress closure returns the bytes read, total bytes read, and total bytes expected to write.
:param: closure The code to be executed periodically during the lifecycle of the request.
:returns: The request.
*/
public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
if let uploadDelegate = delegate as? UploadTaskDelegate {
uploadDelegate.uploadProgress = closure
} else if let dataDelegate = delegate as? DataTaskDelegate {
dataDelegate.dataProgress = closure
} else if let downloadDelegate = delegate as? DownloadTaskDelegate {
downloadDelegate.downloadProgress = closure
}
return self
}
// MARK: Response
/**
A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
*/
public typealias Serializer = (NSURLRequest, NSHTTPURLResponse?, NSData?) -> (AnyObject?, NSError?)
/**
Creates a response serializer that returns the associated data as-is.
:returns: A data response serializer.
*/
public class func responseDataSerializer() -> Serializer {
return { (request, response, data) in
return (data, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(Request.responseDataSerializer(), completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: queue The queue on which the completion handler is dispatched.
:param: serializer The closure responsible for serializing the request, response, and data.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(queue: dispatch_queue_t? = nil, serializer: Serializer, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
dispatch_async(delegate.queue) {
let (responseObject: AnyObject?, serializationError: NSError?) = serializer(self.request, self.response, self.delegate.data)
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, responseObject, self.delegate.error ?? serializationError)
}
}
return self
}
/**
Suspends the request.
*/
public func suspend() {
task.suspend()
}
/**
Resumes the request.
*/
public func resume() {
task.resume()
}
/**
Cancels the request.
*/
public func cancel() {
if let downloadDelegate = delegate as? DownloadTaskDelegate {
downloadDelegate.downloadTask.cancelByProducingResumeData { (data) in
downloadDelegate.resumeData = data
}
} else {
task.cancel()
}
}
class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
let task: NSURLSessionTask
let queue: dispatch_queue_t
let progress: NSProgress
var data: NSData? { return nil }
private(set) var error: NSError?
var credential: NSURLCredential?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
init(task: NSURLSessionTask) {
self.task = task
self.progress = NSProgress(totalUnitCount: 0)
self.queue = {
let label: String = "com.alamofire.task-\(task.taskIdentifier)"
let queue = dispatch_queue_create((label as NSString).UTF8String, DISPATCH_QUEUE_SERIAL)
dispatch_suspend(queue)
return queue
}()
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
var redirectRequest = request
if taskWillPerformHTTPRedirection != nil {
redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if taskDidReceiveChallenge != nil {
(disposition, credential) = taskDidReceiveChallenge!(session, task, challenge)
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
} else {
switch challenge.protectionSpace.authenticationMethod! {
case NSURLAuthenticationMethodServerTrust:
credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
default:
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
}
if credential != nil {
disposition = .UseCredential
}
}
}
completionHandler(disposition, credential)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
var bodyStream: NSInputStream?
if taskNeedNewBodyStream != nil {
bodyStream = taskNeedNewBodyStream!(session, task)
}
completionHandler(bodyStream)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
if error != nil {
self.error = error
}
dispatch_resume(queue)
}
}
class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
var dataTask: NSURLSessionDataTask! { return task as NSURLSessionDataTask }
private var mutableData: NSMutableData
override var data: NSData? {
return mutableData
}
private var expectedContentLength: Int64?
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
override init(task: NSURLSessionTask) {
self.mutableData = NSMutableData()
super.init(task: task)
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
var disposition: NSURLSessionResponseDisposition = .Allow
expectedContentLength = response.expectedContentLength
if dataTaskDidReceiveResponse != nil {
disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
dataTaskDidBecomeDownloadTask?(session, dataTask)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
dataTaskDidReceiveData?(session, dataTask, data)
mutableData.appendData(data)
if let expectedContentLength = dataTask?.response?.expectedContentLength {
dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: Int64(mutableData.length), totalBytesExpectedToReceive: expectedContentLength)
}
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
var cachedResponse = proposedResponse
if dataTaskWillCacheResponse != nil {
cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
}
// MARK: - Validation
extension Request {
/**
A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid.
*/
public typealias Validation = (NSURLRequest, NSHTTPURLResponse) -> (Bool)
/**
Validates the request, using the specified closure.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: validation A closure to validate the request.
:returns: The request.
*/
public func validate(validation: Validation) -> Self {
dispatch_async(delegate.queue) {
if self.response != nil && self.delegate.error == nil {
if !validation(self.request, self.response!) {
self.delegate.error = NSError(domain: AlamofireErrorDomain, code: -1, userInfo: nil)
}
}
}
return self
}
// MARK: Status Code
private class func response(response: NSHTTPURLResponse, hasAcceptableStatusCode statusCodes: [Int]) -> Bool {
return contains(statusCodes, response.statusCode)
}
/**
Validates that the response has a status code in the specified range.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: range The range of acceptable status codes.
:returns: The request.
*/
public func validate(statusCode range: Range<Int>) -> Self {
return validate { (_, response) in
return Request.response(response, hasAcceptableStatusCode: range.map({$0}))
}
}
/**
Validates that the response has a status code in the specified array.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: array The acceptable status codes.
:returns: The request.
*/
public func validate(statusCode array: [Int]) -> Self {
return validate { (_, response) in
return Request.response(response, hasAcceptableStatusCode: array)
}
}
// MARK: Content-Type
private struct MIMEType {
let type: String
let subtype: String
init(_ string: String) {
let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex).componentsSeparatedByString("/")
self.type = components.first!
self.subtype = components.last!
}
func matches(MIME: MIMEType) -> Bool {
switch (type, subtype) {
case ("*", "*"), ("*", MIME.subtype), (MIME.type, "*"), (MIME.type, MIME.subtype):
return true
default:
return false
}
}
}
private class func response(response: NSHTTPURLResponse, hasAcceptableContentType contentTypes: [String]) -> Bool {
if response.MIMEType != nil {
let responseMIMEType = MIMEType(response.MIMEType!)
for acceptableMIMEType in contentTypes.map({MIMEType($0)}) {
if acceptableMIMEType.matches(responseMIMEType) {
return true
}
}
}
return false
}
/**
Validates that the response has a content type in the specified array.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: contentType The acceptable content types, which may specify wildcard types and/or subtypes.
:returns: The request.
*/
public func validate(contentType array: [String]) -> Self {
return validate {(_, response) in
return Request.response(response, hasAcceptableContentType: array)
}
}
// MARK: Automatic
/**
Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field.
If validation fails, subsequent calls to response handlers will have an associated error.
:returns: The request.
*/
public func validate() -> Self {
let acceptableStatusCodes: Range<Int> = 200..<300
let acceptableContentTypes: [String] = {
if let accept = self.request.valueForHTTPHeaderField("Accept") {
return accept.componentsSeparatedByString(",")
}
return ["*/*"]
}()
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
}
}
// MARK: - Upload
extension Manager {
private enum Uploadable {
case Data(NSURLRequest, NSData)
case File(NSURLRequest, NSURL)
case Stream(NSURLRequest, NSInputStream)
}
private func upload(uploadable: Uploadable) -> Request {
var uploadTask: NSURLSessionUploadTask!
var HTTPBodyStream: NSInputStream?
switch uploadable {
case .Data(let request, let data):
uploadTask = session.uploadTaskWithRequest(request, fromData: data)
case .File(let request, let fileURL):
uploadTask = session.uploadTaskWithRequest(request, fromFile: fileURL)
case .Stream(let request, var stream):
uploadTask = session.uploadTaskWithStreamedRequest(request)
HTTPBodyStream = stream
}
let request = Request(session: session, task: uploadTask)
if HTTPBodyStream != nil {
request.delegate.taskNeedNewBodyStream = { _, _ in
return HTTPBodyStream
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: File
/**
Creates a request for uploading a file to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: file The file to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
return upload(.File(URLRequest.URLRequest, file))
}
// MARK: Data
/**
Creates a request for uploading data to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: data The data to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
return upload(.Data(URLRequest.URLRequest, data))
}
// MARK: Stream
/**
Creates a request for uploading a stream to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: stream The stream to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
return upload(.Stream(URLRequest.URLRequest, stream))
}
}
extension Request {
class UploadTaskDelegate: DataTaskDelegate {
var uploadTask: NSURLSessionUploadTask! { return task as NSURLSessionUploadTask }
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
progress.totalUnitCount = totalBytesExpectedToSend
progress.completedUnitCount = totalBytesSent
uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
}
}
// MARK: - Download
extension Manager {
private enum Downloadable {
case Request(NSURLRequest)
case ResumeData(NSData)
}
private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request {
var downloadTask: NSURLSessionDownloadTask!
switch downloadable {
case .Request(let request):
downloadTask = session.downloadTaskWithRequest(request)
case .ResumeData(let resumeData):
downloadTask = session.downloadTaskWithResumeData(resumeData)
}
let request = Request(session: session, task: downloadTask)
if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { (session, downloadTask, URL) in
return destination(URL, downloadTask.response as NSHTTPURLResponse)
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: Request
/**
Creates a request for downloading from the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
return download(.Request(URLRequest.URLRequest), destination: destination)
}
// MARK: Resume Data
/**
Creates a request for downloading from the resume data produced from a previous request cancellation.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
return download(.ResumeData(resumeData), destination: destination)
}
}
extension Request {
/**
A closure executed once a request has successfully completed in order to determine where to move the temporary file written to during the download process. The closure takes two arguments: the temporary file URL and the URL response, and returns a single argument: the file URL where the temporary file should be moved.
*/
public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> (NSURL)
/**
Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask.
:param: directory The search path directory. `.DocumentDirectory` by default.
:param: domain The search path domain mask. `.UserDomainMask` by default.
:returns: A download file destination closure.
*/
public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> DownloadFileDestination {
return { (temporaryURL, response) -> (NSURL) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain)[0] as? NSURL {
return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
}
return temporaryURL
}
}
class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
var downloadTask: NSURLSessionDownloadTask! { return task as NSURLSessionDownloadTask }
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: NSData?
override var data: NSData? { return resumeData }
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if downloadTaskDidFinishDownloadingToURL != nil {
let destination = downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
var fileManagerError: NSError?
NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
if fileManagerError != nil {
error = fileManagerError
}
}
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
}
}
}
// MARK: - Printable
extension Request: Printable {
/// The textual representation used when written to an `OutputStreamType`, which includes the HTTP method and URL, as well as the response status code if a response has been received.
public var description: String {
var components: [String] = []
if request.HTTPMethod != nil {
components.append(request.HTTPMethod!)
}
components.append(request.URL.absoluteString!)
if response != nil {
components.append("(\(response!.statusCode))")
}
return join(" ", components)
}
}
extension Request: DebugPrintable {
func cURLRepresentation() -> String {
var components: [String] = ["$ curl -i"]
let URL = request.URL
if request.HTTPMethod != nil && request.HTTPMethod != "GET" {
components.append("-X \(request.HTTPMethod!)")
}
if let credentialStorage = self.session.configuration.URLCredentialStorage {
let protectionSpace = NSURLProtectionSpace(host: URL.host!, port: URL.port?.integerValue ?? 0, `protocol`: URL.scheme!, realm: URL.host!, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
for credential: NSURLCredential in (credentials as [NSURLCredential]) {
components.append("-u \(credential.user!):\(credential.password!)")
}
} else {
if let credential = delegate.credential {
components.append("-u \(credential.user!):\(credential.password!)")
}
}
}
// Temporarily disabled on OS X due to build failure for CocoaPods
// See https://github.com/CocoaPods/swift/issues/24
#if !os(OSX)
if let cookieStorage = session.configuration.HTTPCookieStorage {
if let cookies = cookieStorage.cookiesForURL(URL) as? [NSHTTPCookie] {
if !cookies.isEmpty {
let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value ?? String());" }
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
}
}
}
#endif
if request.allHTTPHeaderFields != nil {
for (field, value) in request.allHTTPHeaderFields! {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if session.configuration.HTTPAdditionalHeaders != nil {
for (field, value) in session.configuration.HTTPAdditionalHeaders! {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if let HTTPBody = request.HTTPBody {
if let escapedBody = NSString(data: HTTPBody, encoding: NSUTF8StringEncoding)?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") {
components.append("-d \"\(escapedBody)\"")
}
}
components.append("\"\(URL.absoluteString!)\"")
return join(" \\\n\t", components)
}
/// The textual representation used when written to an `OutputStreamType`, in the form of a cURL command.
public var debugDescription: String {
return cURLRepresentation()
}
}
// MARK: - Response Serializers
// MARK: String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
:param: encoding The string encoding. `NSUTF8StringEncoding` by default.
:returns: A string response serializer.
*/
public class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> Serializer {
return { (_, _, data) in
let string = NSString(data: data!, encoding: encoding)
return (string, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return responseString(completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: encoding The string encoding. `NSUTF8StringEncoding` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
completionHandler(request, response, string as? String, error)
})
}
}
// MARK: JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:returns: A JSON object response serializer.
*/
public class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> Serializer {
return { (request, response, data) in
if data == nil || data?.length == 0 {
return (nil, nil)
}
var serializationError: NSError?
let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
return (JSON, serializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
:returns: The request.
*/
public func responseJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responseJSON(completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
:returns: The request.
*/
public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
completionHandler(request, response, JSON, error)
})
}
}
// MARK: Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
:param: options The property list reading options. `0` by default.
:returns: A property list object response serializer.
*/
public class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> Serializer {
return { (request, response, data) in
if data == nil || data?.length == 0 {
return (nil, nil)
}
var propertyListSerializationError: NSError?
let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(data!, options: options, format: nil, error: &propertyListSerializationError)
return (plist, propertyListSerializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
:returns: The request.
*/
public func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responsePropertyList(completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: options The property list reading options. `0` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
:returns: The request.
*/
public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
completionHandler(request, response, plist, error)
})
}
}
// MARK: - Convenience -
private func URLRequest(method: Method, URL: URLStringConvertible) -> NSURLRequest {
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL.URLString)!)
mutableURLRequest.HTTPMethod = method.rawValue
return mutableURLRequest
}
// MARK: - Request
/**
Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding.
:param: method The HTTP method.
:param: URLString The URL string.
:param: parameters The parameters. `nil` by default.
:param: encoding The parameter encoding. `.URL` by default.
:returns: The created request.
*/
public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
return request(encoding.encode(URLRequest(method, URLString), parameters: parameters).0)
}
/**
Creates a request using the shared manager instance for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
return Manager.sharedInstance.request(URLRequest.URLRequest)
}
// MARK: - Upload
// MARK: File
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and file.
:param: method The HTTP method.
:param: URLString The URL string.
:param: file The file to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, file: NSURL) -> Request {
return Manager.sharedInstance.upload(URLRequest(method, URLString), file: file)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and file.
:param: URLRequest The URL request.
:param: file The file to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
return Manager.sharedInstance.upload(URLRequest, file: file)
}
// MARK: Data
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and data.
:param: method The HTTP method.
:param: URLString The URL string.
:param: data The data to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, data: NSData) -> Request {
return Manager.sharedInstance.upload(URLRequest(method, URLString), data: data)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and data.
:param: URLRequest The URL request.
:param: data The data to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
return Manager.sharedInstance.upload(URLRequest, data: data)
}
// MARK: Stream
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and stream.
:param: method The HTTP method.
:param: URLString The URL string.
:param: stream The stream to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, stream: NSInputStream) -> Request {
return Manager.sharedInstance.upload(URLRequest(method, URLString), stream: stream)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and stream.
:param: URLRequest The URL request.
:param: stream The stream to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
return Manager.sharedInstance.upload(URLRequest, stream: stream)
}
// MARK: - Download
// MARK: URL Request
/**
Creates a download request using the shared manager instance for the specified method and URL string.
:param: method The HTTP method.
:param: URLString The URL string.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(method: Method, URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(URLRequest(method, URLString), destination: destination)
}
/**
Creates a download request using the shared manager instance for the specified URL request.
:param: URLRequest The URL request.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(URLRequest, destination: destination)
}
// MARK: Resume Data
/**
Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(data, destination: destination)
}
// MARK: - Custom Extension Response Image
// Code from http://www.raywenderlich.com/85080/beginning-alamofire-tutorial
extension Request {
class func imageResponseSerializer() -> Serializer {
return { request, response, data in
if data == nil {
return (nil, nil)
}
let image = UIImage(data: data!)
return (image, nil)
}
}
func responseImage(completionHandler: (NSURLRequest, NSHTTPURLResponse?, UIImage?, NSError?) -> Void) -> Self {
return response(serializer: Request.imageResponseSerializer(), completionHandler: { (request, response, image, error) in
completionHandler(request, response, image as? UIImage, error)
})
}
}
extension Request {
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the SwiftyJSON enum, if one could be created from the URL response and data, and any error produced while creating the SwiftyJSON enum.
:returns: The request.
*/
public func responseSwiftyJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, JSON, NSError?) -> Void) -> Self {
return responseSwiftyJSON(queue:nil, options:NSJSONReadingOptions.AllowFragments, completionHandler:completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: queue The queue on which the completion handler is dispatched.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the SwiftyJSON enum, if one could be created from the URL response and data, and any error produced while creating the SwiftyJSON enum.
:returns: The request.
*/
public func responseSwiftyJSON(queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, JSON, NSError?) -> Void) -> Self {
return response(queue: queue, serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, object, error) -> Void in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
var responseJSON: JSON
if error != nil || object == nil{
responseJSON = JSON.nullJSON
} else {
responseJSON = JSON(object!)
}
dispatch_async(queue ?? dispatch_get_main_queue(), {
completionHandler(self.request, self.response, responseJSON, error)
})
})
})
}
}
|
mit
|
90a14b311899144d95c0416636d64cab
| 39.936649 | 555 | 0.667612 | 5.660881 | false | false | false | false |
aquarchitect/MyKit
|
Sources/Shared/Extensions/Native/Dictionary+.swift
|
1
|
650
|
//
// Dictionary+.swift
// MyKit
//
// Created by Hai Nguyen.
// Copyright (c) 2015 Hai Nguyen.
//
#if !swift(>=4.0)
/// :nodoc:
public extension Dictionary {
init<S: Sequence>(_ sequence: S)
where S.Iterator.Element == Element {
self.init()
self.merge(sequence)
}
mutating func merge<S: Sequence>(_ sequence: S)
where S.Iterator.Element == Element {
sequence.forEach { self[$0] = $1 }
}
func merging<S: Sequence>(_ sequence: S) -> Dictionary
where S.Iterator.Element == Element {
var result = self
result.merge(sequence)
return result
}
}
#endif
|
mit
|
69fbe37a6f2810ae975f16dd2975bf29
| 19.967742 | 58 | 0.576923 | 3.735632 | false | false | false | false |
EclipseSoundscapes/EclipseSoundscapes
|
Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift
|
6
|
4700
|
//
// CurrentThreadScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 8/30/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import class Foundation.NSObject
import protocol Foundation.NSCopying
import class Foundation.Thread
import Dispatch
#if os(Linux)
import struct Foundation.pthread_key_t
import func Foundation.pthread_setspecific
import func Foundation.pthread_getspecific
import func Foundation.pthread_key_create
fileprivate enum CurrentThreadSchedulerQueueKey {
fileprivate static let instance = "RxSwift.CurrentThreadScheduler.Queue"
}
#else
private class CurrentThreadSchedulerQueueKey: NSObject, NSCopying {
static let instance = CurrentThreadSchedulerQueueKey()
private override init() {
super.init()
}
override var hash: Int {
return 0
}
public func copy(with zone: NSZone? = nil) -> Any {
return self
}
}
#endif
/// Represents an object that schedules units of work on the current thread.
///
/// This is the default scheduler for operators that generate elements.
///
/// This scheduler is also sometimes called `trampoline scheduler`.
public class CurrentThreadScheduler : ImmediateSchedulerType {
typealias ScheduleQueue = RxMutableBox<Queue<ScheduledItemType>>
/// The singleton instance of the current thread scheduler.
public static let instance = CurrentThreadScheduler()
private static var isScheduleRequiredKey: pthread_key_t = { () -> pthread_key_t in
let key = UnsafeMutablePointer<pthread_key_t>.allocate(capacity: 1)
defer { key.deallocate() }
guard pthread_key_create(key, nil) == 0 else {
rxFatalError("isScheduleRequired key creation failed")
}
return key.pointee
}()
private static var scheduleInProgressSentinel: UnsafeRawPointer = { () -> UnsafeRawPointer in
return UnsafeRawPointer(UnsafeMutablePointer<Int>.allocate(capacity: 1))
}()
static var queue : ScheduleQueue? {
get {
return Thread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerQueueKey.instance)
}
set {
Thread.setThreadLocalStorageValue(newValue, forKey: CurrentThreadSchedulerQueueKey.instance)
}
}
/// Gets a value that indicates whether the caller must call a `schedule` method.
public static private(set) var isScheduleRequired: Bool {
get {
return pthread_getspecific(CurrentThreadScheduler.isScheduleRequiredKey) == nil
}
set(isScheduleRequired) {
if pthread_setspecific(CurrentThreadScheduler.isScheduleRequiredKey, isScheduleRequired ? nil : scheduleInProgressSentinel) != 0 {
rxFatalError("pthread_setspecific failed")
}
}
}
/**
Schedules an action to be executed as soon as possible on current thread.
If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be
automatically installed and uninstalled after all work is performed.
- parameter state: State passed to the action to be executed.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
if CurrentThreadScheduler.isScheduleRequired {
CurrentThreadScheduler.isScheduleRequired = false
let disposable = action(state)
defer {
CurrentThreadScheduler.isScheduleRequired = true
CurrentThreadScheduler.queue = nil
}
guard let queue = CurrentThreadScheduler.queue else {
return disposable
}
while let latest = queue.value.dequeue() {
if latest.isDisposed {
continue
}
latest.invoke()
}
return disposable
}
let existingQueue = CurrentThreadScheduler.queue
let queue: RxMutableBox<Queue<ScheduledItemType>>
if let existingQueue = existingQueue {
queue = existingQueue
}
else {
queue = RxMutableBox(Queue<ScheduledItemType>(capacity: 1))
CurrentThreadScheduler.queue = queue
}
let scheduledItem = ScheduledItem(action: action, state: state)
queue.value.enqueue(scheduledItem)
return scheduledItem
}
}
|
gpl-3.0
|
54228916e720a57e4069fb6df7a3e2cf
| 33.050725 | 142 | 0.652692 | 5.614098 | false | false | false | false |
narner/AudioKit
|
AudioKit/Common/Tests/AKMorphingOscillatorBankTests.swift
|
1
|
3088
|
//
// AKMorphingOscillatorBankTests.swift
// AudioKitTestSuite
//
// Created by Aurelius Prochazka on 7/21/17.
// Copyright © 2017 AudioKit. All rights reserved.
//
import AudioKit
import XCTest
class AKMorphingOscillatorBankTests: AKTestCase {
var inputBank: AKMorphingOscillatorBank!
let waveforms = [AKTable(.sawtooth), AKTable(.sine), AKTable(.square), AKTable(.triangle)]
override func setUp() {
super.setUp()
// Need to have a longer test duration to allow for envelope to progress
duration = 1.0
afterStart = {
self.inputBank.play(noteNumber: 60, velocity: 120)
self.inputBank.play(noteNumber: 64, velocity: 110)
self.inputBank.play(noteNumber: 67, velocity: 100)
}
}
func testAttackDuration() {
inputBank = AKMorphingOscillatorBank(waveformArray: waveforms, attackDuration: 0.123)
output = inputBank
AKTestMD5("c3dda6103bb693aef41ec27806e3d4c3")
}
func testDecayDuration() {
inputBank = AKMorphingOscillatorBank(waveformArray: waveforms, decayDuration: 0.234)
output = inputBank
AKTestMD5("05af83eb0e1204a9778bdb77d90dc537")
}
func testDefault() {
inputBank = AKMorphingOscillatorBank()
output = inputBank
AKTestMD5("17345f26560ce643990c5a269ab74a43")
}
func testIndex() {
inputBank = AKMorphingOscillatorBank(waveformArray: waveforms, index: 1.7)
output = inputBank
AKTestMD5("460123ae0622996dd8f04441dff25e8b")
}
// Known Failing Test (inconsistencies in iOS/macOS)
// func testParameters() {
// inputBank = AKMorphingOscillatorBank(waveformArray: waveforms,
// index: 1.7,
// attackDuration: 0.123,
// decayDuration: 0.234,
// sustainLevel: 0.345,
// pitchBend: 1,
// vibratoDepth: 1.1,
// vibratoRate: 1.2)
// output = inputBank
// AKTestMD5("4fa33d14f8fbb5ef176a71e54267ea63")
// }
func testPitchBend() {
inputBank = AKMorphingOscillatorBank(waveformArray: waveforms, pitchBend: 1.1)
output = inputBank
AKTestMD5("90a063716a4e32707059b2fda6526010")
}
func testSustainLevel() {
inputBank = AKMorphingOscillatorBank(waveformArray: waveforms, sustainLevel: 0.345)
output = inputBank
AKTestMD5("37a2084b030c5b29a3553a00c30aa61a")
}
func testVibrato() {
inputBank = AKMorphingOscillatorBank(waveformArray: waveforms, vibratoDepth: 1, vibratoRate: 10)
output = inputBank
AKTestMD5("c61c90ba3766a287f4bac8c5e7d931ed")
}
func testWaveformArray() {
inputBank = AKMorphingOscillatorBank(waveformArray: waveforms)
output = inputBank
AKTestMD5("460123ae0622996dd8f04441dff25e8b")
}
}
|
mit
|
6136bc5c8e5f2e476c79c7af24b4947b
| 32.923077 | 104 | 0.611597 | 4.257931 | false | true | false | false |
redlock/SwiftyDeepstream
|
Example/Pods/Starscream/Sources/WebSocket.swift
|
2
|
53874
|
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
// Copyright (c) 2014-2017 Dalton Cherry.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import CoreFoundation
import SSCommonCrypto
public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification"
public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification"
public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName"
//Standard WebSocket close codes
public enum CloseCode : UInt16 {
case normal = 1000
case goingAway = 1001
case protocolError = 1002
case protocolUnhandledType = 1003
// 1004 reserved.
case noStatusReceived = 1005
//1006 reserved.
case encoding = 1007
case policyViolated = 1008
case messageTooBig = 1009
}
//Error codes
enum InternalErrorCode: UInt16 {
// 0-999 WebSocket status codes not used
case outputStreamWriteError = 1
case compressionError = 2
case invalidSSLError = 3
case writeTimeoutError = 4
}
//WebSocketClient is setup to be dependency injection for testing
public protocol WebSocketClient: class {
var delegate: WebSocketDelegate? {get set }
var disableSSLCertValidation: Bool { get set }
var overrideTrustHostname: Bool { get set }
var desiredTrustHostname: String? { get set }
#if os(Linux)
#else
var security: SSLTrustValidator? { get set }
var enabledSSLCipherSuites: [SSLCipherSuite]? { get set }
#endif
var isConnected: Bool { get }
func connect()
func disconnect(forceTimeout: TimeInterval?, closeCode: UInt16)
func write(string: String, completion: (() -> ())?)
func write(data: Data, completion: (() -> ())?)
func write(ping: Data, completion: (() -> ())?)
func write(pong: Data, completion: (() -> ())?)
}
//implements some of the base behaviors
extension WebSocketClient {
public func write(string: String) {
write(string: string, completion: nil)
}
public func write(data: Data) {
write(data: data, completion: nil)
}
public func write(ping: Data) {
write(ping: ping, completion: nil)
}
public func write(pong: Data) {
write(pong: pong, completion: nil)
}
public func disconnect() {
disconnect(forceTimeout: nil, closeCode: CloseCode.normal.rawValue)
}
}
//SSL settings for the stream
public struct SSLSettings {
let useSSL: Bool
let disableCertValidation: Bool
var overrideTrustHostname: Bool
var desiredTrustHostname: String?
#if os(Linux)
#else
let cipherSuites: [SSLCipherSuite]?
#endif
}
public protocol WSStreamDelegate: class {
func newBytesInStream()
func streamDidError(error: Error?)
}
//This protocol is to allow custom implemention of the underlining stream. This way custom socket libraries (e.g. linux) can be used
public protocol WSStream {
weak var delegate: WSStreamDelegate? {get set}
func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void))
func write(data: Data) -> Int
func read() -> Data?
func cleanup()
#if os(Linux) || os(watchOS)
#else
func sslTrust() -> (trust: SecTrust?, domain: String?)
#endif
}
open class FoundationStream : NSObject, WSStream, StreamDelegate {
private static let sharedWorkQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: [])
private var inputStream: InputStream?
private var outputStream: OutputStream?
public weak var delegate: WSStreamDelegate?
let BUFFER_MAX = 4096
public var enableSOCKSProxy = false
public func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h = url.host! as NSString
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
if enableSOCKSProxy {
let proxyDict = CFNetworkCopySystemProxySettings()
let socksConfig = CFDictionaryCreateMutableCopy(nil, 0, proxyDict!.takeRetainedValue())
let propertyKey = CFStreamPropertyKey(rawValue: kCFStreamPropertySOCKSProxy)
CFWriteStreamSetProperty(outputStream, propertyKey, socksConfig)
CFReadStreamSetProperty(inputStream, propertyKey, socksConfig)
}
#endif
guard let inStream = inputStream, let outStream = outputStream else { return }
inStream.delegate = self
outStream.delegate = self
if ssl.useSSL {
inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
var settings = [NSObject: NSObject]()
if ssl.disableCertValidation {
settings[kCFStreamSSLValidatesCertificateChain] = NSNumber(value: false)
}
if ssl.overrideTrustHostname {
if let hostname = ssl.desiredTrustHostname {
settings[kCFStreamSSLPeerName] = hostname as NSString
} else {
settings[kCFStreamSSLPeerName] = kCFNull
}
}
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
#endif
#if os(Linux)
#else
if let cipherSuites = ssl.cipherSuites {
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
completion(errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn)))
}
if resOut != errSecSuccess {
completion(errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut)))
}
}
#endif
}
#endif
}
CFReadStreamSetDispatchQueue(inStream, FoundationStream.sharedWorkQueue)
CFWriteStreamSetDispatchQueue(outStream, FoundationStream.sharedWorkQueue)
inStream.open()
outStream.open()
var out = timeout// wait X seconds before giving up
FoundationStream.sharedWorkQueue.async { [weak self] in
while !outStream.hasSpaceAvailable {
usleep(100) // wait until the socket is ready
out -= 100
if out < 0 {
guard let s = self else {return}
let errCode = InternalErrorCode.writeTimeoutError.rawValue
completion(s.errorWithDetail("write wait timed out", code: errCode))
return
} else if let error = outStream.streamError {
completion(error)
return // disconnectStream will be called.
}
}
completion(nil) //success!
}
}
public func write(data: Data) -> Int {
guard let outStream = outputStream else {return -1}
let buffer = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self)
return outStream.write(buffer, maxLength: data.count)
}
public func read() -> Data? {
guard let stream = inputStream else {return nil}
let buf = NSMutableData(capacity: BUFFER_MAX)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
let length = stream.read(buffer, maxLength: BUFFER_MAX)
if length < 1 {
return nil
}
return Data(bytes: buffer, count: length)
}
public func cleanup() {
if let stream = inputStream {
stream.delegate = nil
CFReadStreamSetDispatchQueue(stream, nil)
stream.close()
}
if let stream = outputStream {
stream.delegate = nil
CFWriteStreamSetDispatchQueue(stream, nil)
stream.close()
}
outputStream = nil
inputStream = nil
}
#if os(Linux) || os(watchOS)
#else
public func sslTrust() -> (trust: SecTrust?, domain: String?) {
let trust = outputStream!.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust?
var domain = outputStream!.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String
if domain == nil,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
var peerNameLen: Int = 0
SSLGetPeerDomainNameLength(sslContextOut, &peerNameLen)
var peerName = Data(count: peerNameLen)
let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer<Int8>) in
SSLGetPeerDomainName(sslContextOut, peerNamePtr, &peerNameLen)
}
if let peerDomain = String(bytes: peerName, encoding: .utf8), peerDomain.count > 0 {
domain = peerDomain
}
}
return (trust, domain)
}
#endif
/**
Delegate for the stream methods. Processes incoming bytes
*/
open func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
if eventCode == .hasBytesAvailable {
if aStream == inputStream {
delegate?.newBytesInStream()
}
} else if eventCode == .errorOccurred {
delegate?.streamDidError(error: aStream.streamError)
} else if eventCode == .endEncountered {
delegate?.streamDidError(error: nil)
}
}
private func errorWithDetail(_ detail: String, code: UInt16) -> Error {
var details = [String: String]()
details[NSLocalizedDescriptionKey] = detail
return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details) as Error
}
}
//WebSocket implementation
//standard delegate you should use
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocketClient)
func websocketDidDisconnect(socket: WebSocketClient, error: Error?)
func websocketDidReceiveMessage(socket: WebSocketClient, text: String)
func websocketDidReceiveData(socket: WebSocketClient, data: Data)
}
//got pongs
public protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(socket: WebSocketClient, data: Data?)
}
// A Delegate with more advanced info on messages and connection etc.
public protocol WebSocketAdvancedDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: Error?)
func websocketDidReceiveMessage(socket: WebSocket, text: String, response: WebSocket.WSResponse)
func websocketDidReceiveData(socket: WebSocket, data: Data, response: WebSocket.WSResponse)
func websocketHttpUpgrade(socket: WebSocket, request: String)
func websocketHttpUpgrade(socket: WebSocket, response: String)
}
open class WebSocket : NSObject, StreamDelegate, WebSocketClient, WSStreamDelegate {
public enum OpCode : UInt8 {
case continueFrame = 0x0
case textFrame = 0x1
case binaryFrame = 0x2
// 3-7 are reserved.
case connectionClose = 0x8
case ping = 0x9
case pong = 0xA
// B-F reserved.
}
public static let ErrorDomain = "WebSocket"
// Where the callback is executed. It defaults to the main UI thread queue.
public var callbackQueue = DispatchQueue.main
// MARK: - Constants
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSExtensionName = "Sec-WebSocket-Extensions"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 4096
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let RSV1Mask: UInt8 = 0x40
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
let httpSwitchProtocolCode = 101
let supportedSSLSchemes = ["wss", "https"]
public class WSResponse {
var isFin = false
public var code: OpCode = .continueFrame
var bytesLeft = 0
public var frameCount = 0
public var buffer: NSMutableData?
public let firstFrame = {
return Date()
}()
}
// MARK: - Delegates
/// Responds to callback about new messages coming in over the WebSocket
/// and also connection/disconnect messages.
public weak var delegate: WebSocketDelegate?
/// The optional advanced delegate can be used instead of of the delegate
public weak var advancedDelegate: WebSocketAdvancedDelegate?
/// Receives a callback for each pong message recived.
public weak var pongDelegate: WebSocketPongDelegate?
public var onConnect: (() -> Void)?
public var onDisconnect: ((Error?) -> Void)?
public var onText: ((String) -> Void)?
public var onData: ((Data) -> Void)?
public var onPong: ((Data?) -> Void)?
public var disableSSLCertValidation = false
public var overrideTrustHostname = false
public var desiredTrustHostname: String? = nil
public var enableCompression = true
#if os(Linux)
#else
public var security: SSLTrustValidator?
public var enabledSSLCipherSuites: [SSLCipherSuite]?
#endif
public var isConnected: Bool {
connectedMutex.lock()
let isConnected = connected
connectedMutex.unlock()
return isConnected
}
public var request: URLRequest //this is only public to allow headers, timeout, etc to be modified on reconnect
public var currentURL: URL { return request.url! }
public var respondToPingWithPong: Bool = true
// MARK: - Private
private struct CompressionState {
var supportsCompression = false
var messageNeedsDecompression = false
var serverMaxWindowBits = 15
var clientMaxWindowBits = 15
var clientNoContextTakeover = false
var serverNoContextTakeover = false
var decompressor:Decompressor? = nil
var compressor:Compressor? = nil
}
private var stream: WSStream
private var connected = false
private var isConnecting = false
private let connectedMutex = NSLock()
private var compressionState = CompressionState()
private var writeQueue = OperationQueue()
private var readStack = [WSResponse]()
private var inputQueue = [Data]()
private var fragBuffer: Data?
private var certValidated = false
private var didDisconnect = false
private var readyToWrite = false
private var headerSecKey = ""
private let readyToWriteMutex = NSLock()
private var canDispatch: Bool {
readyToWriteMutex.lock()
let canWork = readyToWrite
readyToWriteMutex.unlock()
return canWork
}
/// Used for setting protocols.
public init(request: URLRequest, protocols: [String]? = nil, stream: WSStream = FoundationStream()) {
self.request = request
self.stream = stream
if request.value(forHTTPHeaderField: headerOriginName) == nil {
guard let url = request.url else {return}
var origin = url.absoluteString
if let hostUrl = URL (string: "/", relativeTo: url) {
origin = hostUrl.absoluteString
origin.remove(at: origin.index(before: origin.endIndex))
}
self.request.setValue(origin, forHTTPHeaderField: headerOriginName)
}
if let protocols = protocols {
self.request.setValue(protocols.joined(separator: ","), forHTTPHeaderField: headerWSProtocolName)
}
writeQueue.maxConcurrentOperationCount = 1
}
public convenience init(url: URL, protocols: [String]? = nil) {
var request = URLRequest(url: url)
request.timeoutInterval = 5
self.init(request: request, protocols: protocols)
}
// Used for specifically setting the QOS for the write queue.
public convenience init(url: URL, writeQueueQOS: QualityOfService, protocols: [String]? = nil) {
self.init(url: url, protocols: protocols)
writeQueue.qualityOfService = writeQueueQOS
}
/**
Connect to the WebSocket server on a background thread.
*/
open func connect() {
guard !isConnecting else { return }
didDisconnect = false
isConnecting = true
createHTTPRequest()
}
/**
Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed.
If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate.
If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate.
- Parameter forceTimeout: Maximum time to wait for the server to close the socket.
- Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket.
*/
open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) {
guard isConnected else { return }
switch forceTimeout {
case .some(let seconds) where seconds > 0:
let milliseconds = Int(seconds * 1_000)
callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in
self?.disconnectStream(nil)
}
fallthrough
case .none:
writeError(closeCode)
default:
disconnectStream(nil)
break
}
}
/**
Write a string to the websocket. This sends it as a text frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter string: The string to write.
- parameter completion: The (optional) completion handler.
*/
open func write(string: String, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion)
}
/**
Write binary data to the websocket. This sends it as a binary frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter data: The data to write.
- parameter completion: The (optional) completion handler.
*/
open func write(data: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .binaryFrame, writeCompletion: completion)
}
/**
Write a ping to the websocket. This sends it as a control frame.
Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
*/
open func write(ping: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(ping, code: .ping, writeCompletion: completion)
}
/**
Write a pong to the websocket. This sends it as a control frame.
Respond to a Yodel.
*/
open func write(pong: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(pong, code: .pong, writeCompletion: completion)
}
/**
Private method that starts the connection.
*/
private func createHTTPRequest() {
guard let url = request.url else {return}
var port = url.port
if port == nil {
if supportedSSLSchemes.contains(url.scheme!) {
port = 443
} else {
port = 80
}
}
request.setValue(headerWSUpgradeValue, forHTTPHeaderField: headerWSUpgradeName)
request.setValue(headerWSConnectionValue, forHTTPHeaderField: headerWSConnectionName)
headerSecKey = generateWebSocketKey()
request.setValue(headerWSVersionValue, forHTTPHeaderField: headerWSVersionName)
request.setValue(headerSecKey, forHTTPHeaderField: headerWSKeyName)
if enableCompression {
let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15"
request.setValue(val, forHTTPHeaderField: headerWSExtensionName)
}
request.setValue("\(url.host!):\(port!)", forHTTPHeaderField: headerWSHostName)
var path = url.absoluteString
let offset = (url.scheme?.count ?? 2) + 3
path = String(path[path.index(path.startIndex, offsetBy: offset)..<path.endIndex])
if let range = path.range(of: "/") {
path = String(path[range.lowerBound..<path.endIndex])
} else {
path = "/"
if let query = url.query {
path += "?" + query
}
}
var httpBody = "\(request.httpMethod ?? "GET") \(path) HTTP/1.1\r\n"
if let headers = request.allHTTPHeaderFields {
for (key, val) in headers {
httpBody += "\(key): \(val)\r\n"
}
}
httpBody += "\r\n"
initStreamsWithData(httpBody.data(using: .utf8)!, Int(port!))
advancedDelegate?.websocketHttpUpgrade(socket: self, request: httpBody)
}
/**
Generate a WebSocket key as needed in RFC.
*/
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for _ in 0..<seed {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni!))"
}
let data = key.data(using: String.Encoding.utf8)
let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
return baseKey!
}
/**
Start the stream connection and write the data to the output stream.
*/
private func initStreamsWithData(_ data: Data, _ port: Int) {
guard let url = request.url else {
disconnectStream(nil, runDelegate: true)
return
}
// Disconnect and clean up any existing streams before setting up a new pair
disconnectStream(nil, runDelegate: false)
let useSSL = supportedSSLSchemes.contains(url.scheme!)
#if os(Linux)
let settings = SSLSettings(useSSL: useSSL,
disableCertValidation: disableSSLCertValidation,
overrideTrustHostname: overrideTrustHostname,
desiredTrustHostname: desiredTrustHostname)
#else
let settings = SSLSettings(useSSL: useSSL,
disableCertValidation: disableSSLCertValidation,
overrideTrustHostname: overrideTrustHostname,
desiredTrustHostname: desiredTrustHostname,
cipherSuites: self.enabledSSLCipherSuites)
#endif
certValidated = !useSSL
let timeout = request.timeoutInterval * 1_000_000
stream.delegate = self
stream.connect(url: url, port: port, timeout: timeout, ssl: settings, completion: { [weak self] (error) in
guard let s = self else {return}
if error != nil {
//do disconnect
return
}
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
guard let sOperation = operation, let s = self else { return }
guard !sOperation.isCancelled else { return }
// Do the pinning now if needed
#if os(Linux) || os(watchOS)
s.certValidated = false
#else
if let sec = s.security, !s.certValidated {
let trustObj = s.stream.sslTrust()
if let possibleTrust = trustObj.trust {
s.certValidated = sec.isValid(possibleTrust, domain: trustObj.domain)
} else {
s.certValidated = false
}
if !s.certValidated {
let errCode = InternalErrorCode.invalidSSLError.rawValue
let error = s.errorWithDetail("Invalid SSL certificate", code: errCode)
s.disconnectStream(error)
return
}
}
#endif
let _ = s.stream.write(data: data)
}
s.writeQueue.addOperation(operation)
})
self.readyToWriteMutex.lock()
self.readyToWrite = true
self.readyToWriteMutex.unlock()
}
/**
Delegate for the stream methods. Processes incoming bytes
*/
public func newBytesInStream() {
processInputStream()
}
public func streamDidError(error: Error?) {
disconnectStream(error)
}
/**
Disconnect the stream object and notifies the delegate.
*/
private func disconnectStream(_ error: Error?, runDelegate: Bool = true) {
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
cleanupStream()
connectedMutex.lock()
connected = false
connectedMutex.unlock()
if runDelegate {
doDisconnect(error)
}
}
/**
cleanup the streams.
*/
private func cleanupStream() {
stream.cleanup()
fragBuffer = nil
}
/**
Handles the incoming bytes and sending them to the proper processing method.
*/
private func processInputStream() {
let data = stream.read()
guard let d = data else { return }
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(d)
if process {
dequeueInput()
}
}
/**
Dequeue the incoming input so it is processed in order.
*/
private func dequeueInput() {
while !inputQueue.isEmpty {
autoreleasepool {
let data = inputQueue[0]
var work = data
if let buffer = fragBuffer {
var combine = NSData(data: buffer) as Data
combine.append(data)
work = combine
fragBuffer = nil
}
let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self)
let length = work.count
if !connected {
processTCPHandshake(buffer, bufferLen: length)
} else {
processRawMessagesInBuffer(buffer, bufferLen: length)
}
inputQueue = inputQueue.filter{ $0 != data }
}
}
}
/**
Handle checking the inital connection status
*/
private func processTCPHandshake(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) {
let code = processHTTP(buffer, bufferLen: bufferLen)
switch code {
case 0:
break
case -1:
fragBuffer = Data(bytes: buffer, count: bufferLen)
break // do nothing, we are going to collect more data
default:
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
}
}
/**
Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
*/
private func processHTTP(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for i in 0..<bufferLen {
if buffer[i] == CRLFBytes[k] {
k += 1
if k == 4 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
let code = validateResponse(buffer, bufferLen: totalSize)
if code != 0 {
return code
}
isConnecting = false
connectedMutex.lock()
connected = true
connectedMutex.unlock()
didDisconnect = false
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onConnect?()
s.delegate?.websocketDidConnect(socket: s)
s.advancedDelegate?.websocketDidConnect(socket: s)
NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self)
}
}
//totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize)
}
return 0 //success
}
return -1 // Was unable to find the full TCP header.
}
/**
Validates the HTTP is a 101 as per the RFC spec.
*/
private func validateResponse(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
guard let str = String(data: Data(bytes: buffer, count: bufferLen), encoding: .utf8) else { return -1 }
let splitArr = str.components(separatedBy: "\r\n")
var code = -1
var i = 0
var headers = [String: String]()
for str in splitArr {
if i == 0 {
let responseSplit = str.components(separatedBy: .whitespaces)
guard responseSplit.count > 1 else { return -1 }
if let c = Int(responseSplit[1]) {
code = c
}
} else {
let responseSplit = str.components(separatedBy: ":")
guard responseSplit.count > 1 else { break }
let key = responseSplit[0].trimmingCharacters(in: .whitespaces)
let val = responseSplit[1].trimmingCharacters(in: .whitespaces)
headers[key.lowercased()] = val
}
i += 1
}
advancedDelegate?.websocketHttpUpgrade(socket: self, response: str)
if code != httpSwitchProtocolCode {
return code
}
if let extensionHeader = headers[headerWSExtensionName.lowercased()] {
processExtensionHeader(extensionHeader)
}
if let acceptKey = headers[headerWSAcceptName.lowercased()] {
if acceptKey.count > 0 {
if headerSecKey.count > 0 {
let sha = "\(headerSecKey)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64()
if sha != acceptKey as String {
return -1
}
}
return 0
}
}
return -1
}
/**
Parses the extension header, setting up the compression parameters.
*/
func processExtensionHeader(_ extensionHeader: String) {
let parts = extensionHeader.components(separatedBy: ";")
for p in parts {
let part = p.trimmingCharacters(in: .whitespaces)
if part == "permessage-deflate" {
compressionState.supportsCompression = true
} else if part.hasPrefix("server_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressionState.serverMaxWindowBits = val
}
} else if part.hasPrefix("client_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressionState.clientMaxWindowBits = val
}
} else if part == "client_no_context_takeover" {
compressionState.clientNoContextTakeover = true
} else if part == "server_no_context_takeover" {
compressionState.serverNoContextTakeover = true
}
}
if compressionState.supportsCompression {
compressionState.decompressor = Decompressor(windowBits: compressionState.serverMaxWindowBits)
compressionState.compressor = Compressor(windowBits: compressionState.clientMaxWindowBits)
}
}
/**
Read a 16 bit big endian value from a buffer
*/
private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
}
/**
Read a 64 bit big endian value from a buffer
*/
private static func readUint64(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 {
var value = UInt64(0)
for i in 0...7 {
value = (value << 8) | UInt64(buffer[offset + i])
}
return value
}
/**
Write a 16-bit big endian value to a buffer.
*/
private static func writeUint16(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) {
buffer[offset + 0] = UInt8(value >> 8)
buffer[offset + 1] = UInt8(value & 0xff)
}
/**
Write a 64-bit big endian value to a buffer.
*/
private static func writeUint64(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) {
for i in 0...7 {
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
}
}
/**
Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process.
*/
private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> {
let response = readStack.last
guard let baseAddress = buffer.baseAddress else {return emptyBuffer}
let bufferLen = buffer.count
if response != nil && bufferLen < 2 {
fragBuffer = Data(buffer: buffer)
return emptyBuffer
}
if let response = response, response.bytesLeft > 0 {
var len = response.bytesLeft
var extra = bufferLen - response.bytesLeft
if response.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
response.bytesLeft -= len
response.buffer?.append(Data(bytes: baseAddress, count: len))
_ = processResponse(response)
return buffer.fromOffset(bufferLen - extra)
} else {
let isFin = (FinMask & baseAddress[0])
let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0])
let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue)
let isMasked = (MaskMask & baseAddress[1])
let payloadLen = (PayloadLenMask & baseAddress[1])
var offset = 2
if compressionState.supportsCompression && receivedOpcode != .continueFrame {
compressionState.messageNeedsDecompression = (RSV1Mask & baseAddress[0]) > 0
}
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong && !compressionState.messageNeedsDecompression {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode))
writeError(errCode)
return emptyBuffer
}
let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping)
if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame &&
receivedOpcode != .textFrame && receivedOpcode != .pong) {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcodeRawValue)", code: errCode))
writeError(errCode)
return emptyBuffer
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode))
writeError(errCode)
return emptyBuffer
}
var closeCode = CloseCode.normal.rawValue
if receivedOpcode == .connectionClose {
if payloadLen == 1 {
closeCode = CloseCode.protocolError.rawValue
} else if payloadLen > 1 {
closeCode = WebSocket.readUint16(baseAddress, offset: offset)
if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1013 && closeCode < 3000) {
closeCode = CloseCode.protocolError.rawValue
}
}
if payloadLen < 2 {
doDisconnect(errorWithDetail("connection closed by server", code: closeCode))
writeError(closeCode)
return emptyBuffer
}
} else if isControlFrame && payloadLen > 125 {
writeError(CloseCode.protocolError.rawValue)
return emptyBuffer
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
dataLength = WebSocket.readUint64(baseAddress, offset: offset)
offset += MemoryLayout<UInt64>.size
} else if dataLength == 126 {
dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset))
offset += MemoryLayout<UInt16>.size
}
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
fragBuffer = Data(bytes: baseAddress, count: bufferLen)
return emptyBuffer
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
if receivedOpcode == .connectionClose && len > 0 {
let size = MemoryLayout<UInt16>.size
offset += size
len -= UInt64(size)
}
let data: Data
if compressionState.messageNeedsDecompression, let decompressor = compressionState.decompressor {
do {
data = try decompressor.decompress(bytes: baseAddress+offset, count: Int(len), finish: isFin > 0)
if isFin > 0 && compressionState.serverNoContextTakeover {
try decompressor.reset()
}
} catch {
let closeReason = "Decompression failed: \(error)"
let closeCode = CloseCode.encoding.rawValue
doDisconnect(errorWithDetail(closeReason, code: closeCode))
writeError(closeCode)
return emptyBuffer
}
} else {
data = Data(bytes: baseAddress+offset, count: Int(len))
}
if receivedOpcode == .connectionClose {
var closeReason = "connection closed by server"
if let customCloseReason = String(data: data, encoding: .utf8) {
closeReason = customCloseReason
} else {
closeCode = CloseCode.protocolError.rawValue
}
doDisconnect(errorWithDetail(closeReason, code: closeCode))
writeError(closeCode)
return emptyBuffer
}
if receivedOpcode == .pong {
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
let pongData: Data? = data.count > 0 ? data : nil
s.onPong?(pongData)
s.pongDelegate?.websocketDidReceivePong(socket: s, data: pongData)
}
}
return buffer.fromOffset(offset + Int(len))
}
var response = readStack.last
if isControlFrame {
response = nil // Don't append pings.
}
if isFin == 0 && receivedOpcode == .continueFrame && response == nil {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode))
writeError(errCode)
return emptyBuffer
}
var isNew = false
if response == nil {
if receivedOpcode == .continueFrame {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("first frame can't be a continue frame",
code: errCode))
writeError(errCode)
return emptyBuffer
}
isNew = true
response = WSResponse()
response!.code = receivedOpcode!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == .continueFrame {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame",
code: errCode))
writeError(errCode)
return emptyBuffer
}
response!.buffer!.append(data)
}
if let response = response {
response.bytesLeft -= Int(len)
response.frameCount += 1
response.isFin = isFin > 0 ? true : false
if isNew {
readStack.append(response)
}
_ = processResponse(response)
}
let step = Int(offset + numericCast(len))
return buffer.fromOffset(step)
}
}
/**
Process all messages in the buffer if possible.
*/
private func processRawMessagesInBuffer(_ pointer: UnsafePointer<UInt8>, bufferLen: Int) {
var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen)
repeat {
buffer = processOneRawMessage(inBuffer: buffer)
} while buffer.count >= 2
if buffer.count > 0 {
fragBuffer = Data(buffer: buffer)
}
}
/**
Process the finished response of a buffer.
*/
private func processResponse(_ response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .ping {
if respondToPingWithPong {
let data = response.buffer! // local copy so it is perverse for writing
dequeueWrite(data as Data, code: .pong)
}
} else if response.code == .textFrame {
guard let str = String(data: response.buffer! as Data, encoding: .utf8) else {
writeError(CloseCode.encoding.rawValue)
return false
}
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onText?(str)
s.delegate?.websocketDidReceiveMessage(socket: s, text: str)
s.advancedDelegate?.websocketDidReceiveMessage(socket: s, text: str, response: response)
}
}
} else if response.code == .binaryFrame {
if canDispatch {
let data = response.buffer! // local copy so it is perverse for writing
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onData?(data as Data)
s.delegate?.websocketDidReceiveData(socket: s, data: data as Data)
s.advancedDelegate?.websocketDidReceiveData(socket: s, data: data as Data, response: response)
}
}
}
readStack.removeLast()
return true
}
return false
}
/**
Create an error
*/
private func errorWithDetail(_ detail: String, code: UInt16) -> Error {
var details = [String: String]()
details[NSLocalizedDescriptionKey] = detail
return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details) as Error
}
/**
Write an error to the socket
*/
private func writeError(_ code: UInt16) {
let buf = NSMutableData(capacity: MemoryLayout<UInt16>.size)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
WebSocket.writeUint16(buffer, offset: 0, value: code)
dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose)
}
/**
Used to write things to the stream
*/
private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) {
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
//stream isn't ready, let's wait
guard let s = self else { return }
guard let sOperation = operation else { return }
var offset = 2
var firstByte:UInt8 = s.FinMask | code.rawValue
var data = data
if [.textFrame, .binaryFrame].contains(code), let compressor = s.compressionState.compressor {
do {
data = try compressor.compress(data)
if s.compressionState.clientNoContextTakeover {
try compressor.reset()
}
firstByte |= s.RSV1Mask
} catch {
// TODO: report error? We can just send the uncompressed frame.
}
}
let dataLength = data.count
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self)
buffer[0] = firstByte
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength))
offset += MemoryLayout<UInt16>.size
} else {
buffer[1] = 127
WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength))
offset += MemoryLayout<UInt64>.size
}
buffer[1] |= s.MaskMask
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
_ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey)
offset += MemoryLayout<UInt32>.size
for i in 0..<dataLength {
buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size]
offset += 1
}
var total = 0
while !sOperation.isCancelled {
let stream = s.stream
let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self)
let len = stream.write(data: Data(bytes: writeBuffer, count: offset-total))
if len <= 0 {
var error: Error?
let errCode = InternalErrorCode.outputStreamWriteError.rawValue
error = s.errorWithDetail("output stream error during write", code: errCode)
s.doDisconnect(error)
break
} else {
total += len
}
if total >= offset {
if let queue = self?.callbackQueue, let callback = writeCompletion {
queue.async {
callback()
}
}
break
}
}
}
writeQueue.addOperation(operation)
}
/**
Used to preform the disconnect delegate
*/
private func doDisconnect(_ error: Error?) {
guard !didDisconnect else { return }
didDisconnect = true
isConnecting = false
connectedMutex.lock()
connected = false
connectedMutex.unlock()
guard canDispatch else {return}
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onDisconnect?(error)
s.delegate?.websocketDidDisconnect(socket: s, error: error)
s.advancedDelegate?.websocketDidDisconnect(socket: s, error: error)
let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] }
NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo)
}
}
// MARK: - Deinit
deinit {
readyToWriteMutex.lock()
readyToWrite = false
readyToWriteMutex.unlock()
cleanupStream()
writeQueue.cancelAllOperations()
}
}
private extension String {
func sha1Base64() -> String {
let data = self.data(using: String.Encoding.utf8)!
var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) }
return Data(bytes: digest).base64EncodedString()
}
}
private extension Data {
init(buffer: UnsafeBufferPointer<UInt8>) {
self.init(bytes: buffer.baseAddress!, count: buffer.count)
}
}
private extension UnsafeBufferPointer {
func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> {
return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset)
}
}
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
|
mit
|
c4212a3ec6bba0cc4b13948f8a2569ad
| 39.084821 | 226 | 0.583862 | 5.389556 | false | false | false | false |
mnisn/zhangchu
|
zhangchu/zhangchu/classes/recipe/recommend/main/view/RecommentChosenCell.swift
|
1
|
4340
|
//
// RecommentChosenCell.swift
// zhangchu
//
// Created by 苏宁 on 2016/10/31.
// Copyright © 2016年 suning. All rights reserved.
//
import UIKit
class RecommentChosenCell: UITableViewCell {
var clickClosure:RecipClickClosure?
var listModel:RecipeRecommendWidgetList?{
didSet{
showData()
}
}
//视图点击
@IBAction func btnClick(sender: UIButton)
{
let index = sender.tag - 100
if listModel?.widget_data?.count > index * 3
{
let data = listModel?.widget_data![index * 3]
if data?.link != nil && clickClosure != nil
{
clickClosure!((data?.link)!)
}
}
}
//头像点击
@IBAction func userBtnClick(sender: UIButton)
{
let index = sender.tag - 300
if listModel?.widget_data?.count > index * 3 + 1
{
let data = listModel?.widget_data![index * 3 + 1]
if data?.link != nil && clickClosure != nil
{
clickClosure!((data?.link)!)
}
}
}
@IBOutlet weak var descLabel: UILabel!
func showData()
{
if listModel?.widget_data?.count > 0
{
for i in 0 ..< 3
{
//i * 3
if listModel?.widget_data?.count > i * 3
{
let imgData = listModel?.widget_data![i * 3]
if imgData?.type == "image"
{
let tmpView = contentView.viewWithTag(200 + i)
if tmpView?.isKindOfClass(UIImageView) == true
{
let imgView = tmpView as! UIImageView
imgView.kf_setImageWithURL(NSURL(string: (imgData?.content)!), placeholderImage: UIImage(named: "sdefaultImage"))
}
}
}
//i * 3 + 1
if listModel?.widget_data?.count > i * 3 + 1
{
let userImgData = listModel?.widget_data![i * 3 + 1]
if userImgData?.type == "image"
{
let tmpView = contentView.viewWithTag(300 + i)
if tmpView?.isKindOfClass(UIButton) == true
{
let userBtn = tmpView as! UIButton
userBtn.kf_setBackgroundImageWithURL(NSURL(string: (userImgData?.content)!), forState: .Normal)
userBtn.layer.cornerRadius = 15
userBtn.layer.masksToBounds = true
}
}
}
//i * 3 + 2
if listModel?.widget_data?.count > i * 3 + 2
{
let nameLabelData = listModel?.widget_data![i * 3 + 2]
if nameLabelData?.type == "text"
{
let tmpView = contentView.viewWithTag(400 + i)
if tmpView?.isKindOfClass(UILabel) == true
{
let nameLabel = tmpView as! UILabel
nameLabel.text = nameLabelData?.content
}
}
}
}
//
descLabel.text = listModel?.desc
}
}
//创建cell
class func createChonsenCell(tableView: UITableView, atIndexPath indexPath:NSIndexPath, listModel:RecipeRecommendWidgetList?) ->RecommentChosenCell
{
let cellID = "recommentChosenCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as? RecommentChosenCell
if cell == nil
{
cell = NSBundle.mainBundle().loadNibNamed("RecommentChosenCell", owner: nil, options: nil).last as? RecommentChosenCell
}
cell?.listModel = listModel!
return cell!
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
979cf88d20899672501ecd05db0aea43
| 31.923664 | 151 | 0.474148 | 5.190132 | false | false | false | false |
younata/RSSClient
|
Tethys/Generic/CoreGraphicsLinearAlgebra.swift
|
1
|
748
|
import CoreGraphics
extension CGPoint {
static func - (lhs: CGPoint, rhs: CGPoint) -> CGVector {
return CGVector(dx: lhs.x - rhs.x, dy: lhs.y - rhs.y)
}
static func + (lhs: CGPoint, rhs: CGVector) -> CGPoint {
return CGPoint(x: lhs.x + rhs.dx, y: lhs.y + rhs.dy)
}
static func += (lhs: inout CGPoint, rhs: CGVector) {
lhs = lhs + rhs // swiftlint:disable:this shorthand_operator
}
}
extension CGVector {
func magnitudeSquared() -> CGFloat {
return pow(self.dx, 2) + pow(self.dy, 2)
}
func normalized() -> CGVector {
let x2 = pow(dx, 2)
let y2 = pow(dy, 2)
let mag = sqrt(x2 + y2)
return CGVector(dx: self.dx / mag, dy: self.dy / mag)
}
}
|
mit
|
ac4feeb6761f17bccaf0b59a27f175d8
| 24.793103 | 68 | 0.565508 | 3.324444 | false | false | false | false |
iAugux/iBBS-Swift
|
iBBS/IBBSNodeTopicListModel.swift
|
1
|
600
|
//
// IBBSNodeTopicListModel.swift
// iBBS
//
// Created by Augus on 4/18/16.
// Copyright © 2016 iAugus. All rights reserved.
//
import SwiftyJSON
struct IBBSNodeTopicListModel {
var title: String!
var uid: Int!
var username: String!
var postTime: String!
var avatarUrl: NSURL!
init(json: JSON) {
title = json["title"].stringValue
uid = json["uid"].intValue
username = json["username"].stringValue
postTime = json["post_time"].stringValue
avatarUrl = NSURL(string: json["avatar"].stringValue)
}
}
|
mit
|
4d1dc79d60769a2fb3534fa0506318ce
| 20.428571 | 61 | 0.607679 | 3.940789 | false | false | false | false |
liuxuan30/ios-charts
|
ChartsDemo-iOS/Swift/Demos/NegativeStackedBarChartViewController.swift
|
3
|
4553
|
//
// NegativeStackedBarChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
#if canImport(UIKit)
import UIKit
#endif
import Charts
class NegativeStackedBarChartViewController: DemoBaseViewController {
@IBOutlet var chartView: HorizontalBarChartView!
lazy var customFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.negativePrefix = ""
formatter.positiveSuffix = "m"
formatter.negativeSuffix = "m"
formatter.minimumSignificantDigits = 1
formatter.minimumFractionDigits = 1
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Stacked Bar Chart Negative"
self.options = [.toggleValues,
.toggleIcons,
.toggleHighlight,
.animateX,
.animateY,
.animateXY,
.saveToGallery,
.togglePinchZoom,
.toggleAutoScaleMinMax,
.toggleData,
.toggleBarBorders]
chartView.delegate = self
chartView.chartDescription?.enabled = false
chartView.drawBarShadowEnabled = false
chartView.drawValueAboveBarEnabled = true
chartView.leftAxis.enabled = false
let rightAxis = chartView.rightAxis
rightAxis.axisMaximum = 25
rightAxis.axisMinimum = -25
rightAxis.drawZeroLineEnabled = true
rightAxis.labelCount = 7
rightAxis.valueFormatter = DefaultAxisValueFormatter(formatter: customFormatter)
rightAxis.labelFont = .systemFont(ofSize: 9)
let xAxis = chartView.xAxis
xAxis.labelPosition = .bothSided
xAxis.drawAxisLineEnabled = false
xAxis.axisMinimum = 0
xAxis.axisMaximum = 110
xAxis.centerAxisLabelsEnabled = true
xAxis.labelCount = 12
xAxis.granularity = 10
xAxis.valueFormatter = self
xAxis.labelFont = .systemFont(ofSize: 9)
let l = chartView.legend
l.horizontalAlignment = .right
l.verticalAlignment = .bottom
l.orientation = .horizontal
l.formSize = 8
l.formToTextSpace = 8
l.xEntrySpace = 6
// chartView.legend = l
self.updateChartData()
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setChartData()
}
func setChartData() {
let yVals = [BarChartDataEntry(x: 5, yValues: [-10, 10]),
BarChartDataEntry(x: 15, yValues: [-12, 13]),
BarChartDataEntry(x: 25, yValues: [-15, 15]),
BarChartDataEntry(x: 35, yValues: [-17, 17]),
BarChartDataEntry(x: 45, yValues: [-19, 120]),
BarChartDataEntry(x: 55, yValues: [-19, 19]),
BarChartDataEntry(x: 65, yValues: [-16, 16]),
BarChartDataEntry(x: 75, yValues: [-13, 14]),
BarChartDataEntry(x: 85, yValues: [-10, 11]),
BarChartDataEntry(x: 95, yValues: [-5, 6]),
BarChartDataEntry(x: 105, yValues: [-1, 2])
]
let set = BarChartDataSet(entries: yVals, label: "Age Distribution")
set.drawIconsEnabled = false
set.valueFormatter = DefaultValueFormatter(formatter: customFormatter)
set.valueFont = .systemFont(ofSize: 7)
set.axisDependency = .right
set.colors = [UIColor(red: 67/255, green: 67/255, blue: 72/255, alpha: 1),
UIColor(red: 124/255, green: 181/255, blue: 236/255, alpha: 1)
]
set.stackLabels = ["Men", "Women"]
let data = BarChartData(dataSet: set)
data.barWidth = 8.5
chartView.data = data
chartView.setNeedsDisplay()
}
override func optionTapped(_ option: Option) {
super.handleOption(option, forChartView: chartView)
}
}
extension NegativeStackedBarChartViewController: IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return String(format: "%03.0f-%03.0f", value, value + 10)
}
}
|
apache-2.0
|
94321af0f91e01807dcaed4ba51fcabc
| 32.970149 | 88 | 0.570958 | 5.149321 | false | false | false | false |
adly-holler/Bond
|
Bond/OSX/Bond+NSControl.swift
|
12
|
2348
|
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tony Arnold (@tonyarnold)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Cocoa
protocol ControlDynamicHelper {
typealias T
var value: T { get }
var listener: (T -> Void)? { get set }
}
class ControlDynamic<T, U: ControlDynamicHelper where U.T == T>: Dynamic<T> {
var helper: U
init(helper: U) {
self.helper = helper
super.init(helper.value)
self.helper.listener = {
[unowned self] in
self.value = $0
}
}
}
var enabledDynamicHandleNSControl: UInt8 = 0;
extension NSControl {
public var dynEnabled: Dynamic<Bool> {
if let d: AnyObject = objc_getAssociatedObject(self, &enabledDynamicHandleNSControl) {
return (d as? Dynamic<Bool>)!
} else {
let d = InternalDynamic<Bool>(self.enabled)
let bond = Bond<Bool>() { [weak self] v in
if let s = self {
s.enabled = v
}
}
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &enabledDynamicHandleNSControl, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
}
|
mit
|
81804734c6103ab4e54d0ad95baa6c88
| 31.164384 | 136 | 0.652896 | 4.230631 | false | false | false | false |
jiapan1984/swift-datastructures-algorithms
|
linearsearch.swift
|
1
|
491
|
func linearSearch<T:Equatable>(array:[T], e:T) -> Int? {
for i in 0..<array.count {
if array[i] == e {
return i
}
}
return nil
}
func linearSearch1<T: Equatable>(_ array:[T], _ object:T) -> Int? {
for (index, obj) in array.enumerated() where obj == object {
return index
}
return nil
}
let a = [1, 4, 9, 2, 10, 7]
print(linearSearch(array:a, e:7) ?? "nil")
print(linearSearch1(a, 10) ?? "nil")
print(linearSearch1(a, 6) ?? "nil")
|
mit
|
6616e8462e2ea37ba5b1e6df2c06e905
| 23.6 | 67 | 0.549898 | 2.922619 | false | false | false | false |
akosma/Swift-Presentation
|
PresentationKit/Demos/ObjCDemo.swift
|
1
|
281
|
import Cocoa
public class ObjCDemo: BaseDemo {
public override func show() {
typealias BOOL = Bool
let YES = true
let NO = false
var value : BOOL = YES
println("YES = \(YES)")
println("NO = \(NO)")
}
}
|
bsd-2-clause
|
7ffcd0943ad3c50bec765393ab9eac78
| 14.611111 | 33 | 0.483986 | 4.606557 | false | false | false | false |
AlbertWu0212/MyDailyTodo
|
MyDailyTodo/MyDailyTodo/AppDelegate.swift
|
1
|
3232
|
//
// AppDelegate.swift
// Checklists
//
// Created by M.I. Hollemans on 27/07/15.
// Copyright © 2015 Razeware. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let dataModel = DataModel()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let navigationController = window!.rootViewController as! UINavigationController
let controller = navigationController.viewControllers[0] as! AllListsViewController
controller.dataModel = dataModel
let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
// let date = NSDate(timeIntervalSinceNow: 10)
// let localNotification = UILocalNotification()
// localNotification.fireDate = date
// localNotification.timeZone = NSTimeZone.defaultTimeZone()
// localNotification.alertBody = "I am a local notification!"
// localNotification.soundName = UILocalNotificationDefaultSoundName
// UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
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.
saveData()
}
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:.
saveData()
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
print("didReceiveLocalNotification \(notification)")
}
func saveData() {
dataModel.saveChecklists()
}
}
|
mit
|
193c4745f6c2849901e9a40428bc4eef
| 44.507042 | 281 | 0.774064 | 5.648601 | false | false | false | false |
haijianhuo/TopStore
|
Pods/Hero/Sources/HeroViewControllerDelegate.swift
|
1
|
2637
|
// 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 UIKit
@objc public protocol HeroViewControllerDelegate {
@objc optional func heroWillStartAnimatingFrom(viewController: UIViewController)
@objc optional func heroDidEndAnimatingFrom(viewController: UIViewController)
@objc optional func heroDidCancelAnimatingFrom(viewController: UIViewController)
@objc optional func heroWillStartTransition()
@objc optional func heroDidEndTransition()
@objc optional func heroDidCancelTransition()
@objc optional func heroWillStartAnimatingTo(viewController: UIViewController)
@objc optional func heroDidEndAnimatingTo(viewController: UIViewController)
@objc optional func heroDidCancelAnimatingTo(viewController: UIViewController)
}
// delegate helper
internal extension HeroTransition {
func closureProcessForHeroDelegate<T: UIViewController>(vc: T, closure: (HeroViewControllerDelegate) -> Void) {
if let delegate = vc as? HeroViewControllerDelegate {
closure(delegate)
}
if let navigationController = vc as? UINavigationController,
let delegate = navigationController.topViewController as? HeroViewControllerDelegate {
closure(delegate)
} else if let tabBarController = vc as? UITabBarController,
let delegate = tabBarController.selectedViewController as? HeroViewControllerDelegate {
closure(delegate)
} else {
for vc in vc.childViewControllers where vc.isViewLoaded {
self.closureProcessForHeroDelegate(vc: vc, closure: closure)
}
}
}
}
|
mit
|
787d90b0eeec7464ae806a4481179ab2
| 44.465517 | 113 | 0.773986 | 4.956767 | false | false | false | false |
con-beo-vang/Spendy
|
Spendy/Views/Custom Animation Transition/CustomDismissAnimationController.swift
|
1
|
4783
|
//
// CustomDismissAnimationController.swift
// CustomTransitions
//
// Created by Joyce Echessa on 3/3/15.
// Copyright (c) 2015 Appcoda. All rights reserved.
//
import UIKit
class CustomDismissAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
var animationType = CustomSegueAnimation.Push
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 2
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
let containerView = transitionContext.containerView()
let screenBounds = UIScreen.mainScreen().bounds
switch animationType {
case CustomSegueAnimation.Push:
let finalToFrame = screenBounds
let finalFromFrame = CGRectOffset(finalToFrame, screenBounds.size.width, 0)
toViewController.view.frame = CGRectOffset(finalToFrame, -screenBounds.size.width, 0)
containerView?.addSubview(toViewController.view)
UIView.animateWithDuration(0.5, animations: {
toViewController.view.frame = finalToFrame
fromViewController.view.frame = finalFromFrame
}, completion: {
finished in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
})
break
case CustomSegueAnimation.SwipeDown:
let finalToFrame = screenBounds
let finalFromFrame = CGRectOffset(finalToFrame, 0, -screenBounds.size.height)
toViewController.view.frame = CGRectOffset(finalToFrame, 0, screenBounds.size.height)
containerView?.addSubview(toViewController.view)
UIView.animateWithDuration(0.5, animations: {
toViewController.view.frame = finalToFrame
fromViewController.view.frame = finalFromFrame
}, completion: {
finished in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
})
break
case CustomSegueAnimation.GrowScale:
fromViewController.view.superview?.insertSubview(toViewController.view, atIndex: 0)
UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
fromViewController.view.transform = CGAffineTransformMakeScale(0.05, 0.05)
}, completion: {
finished in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
})
break
case CustomSegueAnimation.CornerRotate:
toViewController.view.layer.anchorPoint = CGPointZero
fromViewController.view.layer.anchorPoint = CGPointZero
toViewController.view.layer.position = CGPointZero
fromViewController.view.layer.position = CGPointZero
let containerView = fromViewController.view.superview
containerView?.addSubview(toViewController.view)
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.TransitionNone, animations: {
fromViewController.view.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_2))
toViewController.view.transform = CGAffineTransformIdentity
}, completion: {
finished in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
})
break
case CustomSegueAnimation.Mixed:
let finalFrameForVC = transitionContext.finalFrameForViewController(toViewController)
let containerView = transitionContext.containerView()
toViewController.view.frame = finalFrameForVC
toViewController.view.alpha = 0.5
containerView!.addSubview(toViewController.view)
containerView!.sendSubviewToBack(toViewController.view)
let snapshotView = fromViewController.view.snapshotViewAfterScreenUpdates(false)
snapshotView.frame = fromViewController.view.frame
containerView!.addSubview(snapshotView)
fromViewController.view.removeFromSuperview()
UIView.animateWithDuration(transitionDuration(transitionContext), animations: {
snapshotView.frame = CGRectInset(fromViewController.view.frame, fromViewController.view.frame.size.width / 2, fromViewController.view.frame.size.height / 2)
toViewController.view.alpha = 1.0
}, completion: {
finished in
snapshotView.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
})
break
}
}
}
|
mit
|
226b7d41cf51f724007da6d7f3cdb5f2
| 40.232759 | 168 | 0.732386 | 5.971286 | false | false | false | false |
mubstimor/smartcollaborationvapor
|
Sources/App/Models/Fixture.swift
|
1
|
1944
|
//
// Fixture.swift
// SmartCollaborationVapor
//
// Created by Timothy Mubiru on 02/03/2017.
//
//
import Vapor
import Fluent
final class Fixture: Model {
var id: Node?
var league_id : Node?
var name: String
var game_date: String
var game_time: String
var home_team: String
var away_team: String
var exists: Bool = false
init(league_id: Node? = nil, name: String, game_date: String, game_time: String, home_team: String, away_team: String) {
self.league_id = league_id
self.name = name
self.game_date = game_date
self.game_time = game_time
self.home_team = home_team
self.away_team = away_team
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
league_id = try node.extract("league_id")
name = try node.extract("name")
game_date = try node.extract("game_date")
game_time = try node.extract("game_time")
home_team = try node.extract("home_team")
away_team = try node.extract("away_team")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"league_id": league_id,
"name": name,
"game_date": game_date,
"game_time": game_time,
"home_team": home_team,
"away_team": away_team
])
}
static func prepare(_ database: Database) throws {
try database.create("fixtures") { fixtures in
fixtures.id()
fixtures.parent(League.self, optional: false)
fixtures.string("name")
fixtures.string("game_date")
fixtures.string("game_time")
fixtures.string("home_team")
fixtures.string("away_team")
}
}
static func revert(_ database: Database) throws {
try database.delete("fixtures")
}
}
|
mit
|
154f625267de3464d197d6c756d7e578
| 26.771429 | 124 | 0.561214 | 3.841897 | false | false | false | false |
fuku2014/spritekit-original-game
|
src/scenes/play/sprites/Man.swift
|
1
|
2078
|
//
// Man.swift
// あるきスマホ
//
// Created by admin on 2015/09/20.
// Copyright (c) 2015年 m.fukuzawa. All rights reserved.
//
import UIKit
import SpriteKit
class Man: SKSpriteNode {
init() {
let atlas = SKTextureAtlas(named: "man")
let texture1 = atlas.textureNamed("man-01")
let texture2 = atlas.textureNamed("man-02")
texture1.filteringMode = .Nearest
texture2.filteringMode = .Nearest
let anim = SKAction.animateWithTextures([texture1, texture2], timePerFrame: 0.2)
let walk = SKAction.repeatActionForever(anim)
super.init(texture: nil, color: UIColor.clearColor(), size: texture1.size())
self.setScale(1 / 15)
self.runAction(walk)
// 衝突判定用
self.physicsBody = SKPhysicsBody(rectangleOfSize: self.size)
self.physicsBody?.dynamic = true
self.physicsBody?.affectedByGravity = false
self.physicsBody?.categoryBitMask = 0x1 << 1
self.physicsBody?.contactTestBitMask = 0x1 << 0
self.physicsBody?.collisionBitMask = 0
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func move() {
let road = self.parent as! Road
let positionBefore : CGPoint = self.position
let moveAmountY : CGFloat = road.direction == DirectionType.DirectionUp ? 5.0 : -5.0
var positionAfter : CGPoint = CGPointMake(positionBefore.x, positionBefore.y + moveAmountY)
let topEnd = road.groundTexture.size().height * road.textureYScale + road.loadTexture.size().height * road.textureYScale
let bottomEnd = road.groundTexture.size().height * road.textureYScale
if positionAfter.y - self.size.height / 2 <= bottomEnd || positionAfter.y + self.size.height / 2 >= topEnd {
positionAfter = positionBefore
}
self.position = positionAfter
}
}
|
apache-2.0
|
92240b9d47a227240c8c6d8fbff7d750
| 31.09375 | 131 | 0.607595 | 4.2881 | false | false | false | false |
hgani/ganilib-ios
|
glib/Classes/Screen/LaunchHelper.swift
|
1
|
3534
|
import MessageUI
import UIKit
open class LaunchHelper {
private unowned let screen: UIViewController
public init(_ screen: UIViewController) {
self.screen = screen
}
private func navController() -> UIViewController {
// Needed for nav menu which will fail to present because it will be closed/closing when clicked,
// so use global nav controller instead.
return screen.viewIfLoaded?.window == nil ? GApp.instance.navigationController : screen
}
public func alert(_ message: String, title: String? = nil) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
navController().present(alert, animated: true, completion: nil)
}
public func confirm(_ message: String, title: String? = nil, handler: @escaping (() -> Void)) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .destructive, handler: { _ in
handler()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
navController().present(alert, animated: true, completion: nil)
}
public func call(_ number: String) {
if let phoneCallURL = URL(string: "tel://\(number)") {
let application = UIApplication.shared
if application.canOpenURL(phoneCallURL) {
if #available(iOS 10.0, *) {
application.open(phoneCallURL, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
}
} else {
alert("This device doesn't support phone calls")
}
} else {
// Do nothing
}
}
public func mail(_ recipient: String, subject: String, message: String, delegate: MFMailComposeViewControllerDelegate) {
if MFMailComposeViewController.canSendMail() {
let composeViewController = MFMailComposeViewController()
composeViewController.mailComposeDelegate = delegate
composeViewController.setToRecipients([recipient])
composeViewController.setSubject(subject)
composeViewController.setMessageBody(message, isHTML: false)
screen.present(composeViewController, animated: true, completion: nil)
} else {
UIApplication.shared.open(URL(string: "mailto:\(recipient)")!)
}
}
public func maps(_ address: String) {
let baseURL = "http://maps.apple.com/?q="
let encodedName = address.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
let mapURL = baseURL + encodedName
if let url = URL(string: mapURL) {
let application = UIApplication.shared
if application.canOpenURL(url) {
if #available(iOS 10.0, *) {
application.open(url, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
}
} else {
alert("This device does not have Maps app")
}
} else {
// Do nothing
}
}
public func url(_ string: String) {
if let url = URL(string: string) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
}
|
mit
|
d1eaca5263187a04e24a1842eaf566b6
| 39.159091 | 124 | 0.601302 | 5.106936 | false | false | false | false |
piscoTech/MBLibrary
|
Shared/CoreDataManager.swift
|
1
|
4195
|
//
// CoreDataManager.swift
// MBLibrary
//
// Created by Marco Boschi on 23/08/2018.
// Part of code are from Alexander Grebenyuk tutorials at http://kean.github.io/post/core-data-progressive-migrations and https://gist.github.com/kean/28439b29532993b620497621a4545789
// Copyright © 2018 Marco Boschi. All rights reserved.
//
import Foundation
import CoreData
public enum MBCoreDataError: Error {
case incompatibleModels
case notAStore
}
public class CoreDataManager {
private let storeType = NSSQLiteStoreType
private let storeURL: URL
private let moms: [NSManagedObjectModel]
private let mappingBundles: [Bundle]
public init(store url: URL, withModelHistory moms: [NSManagedObjectModel], mappingBundles: [Bundle]? = nil) {
precondition(!moms.isEmpty, "You cannot use CoreData without a Managed Object Model")
self.storeURL = url
self.moms = moms
self.mappingBundles = mappingBundles ?? Bundle.allBundles + Bundle.allFrameworks
}
/// Migrate the store to the latest model if necessary and loads it in a new persistent store coordinator.
/// - returns: The new persistent store coordinator for the store.
public func getStoreCoordinator() throws -> NSPersistentStoreCoordinator {
do {
try migrateStore()
} catch MBCoreDataError.notAStore {
if FileManager.default.fileExists(atPath: storeURL.absoluteString) {
try FileManager.default.removeItem(at: storeURL)
}
} catch MBCoreDataError.incompatibleModels {
try FileManager.default.removeItem(at: storeURL)
} catch let e {
throw e
}
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: moms.last!)
try coordinator.addPersistentStore(ofType: storeType, configurationName: nil, at: storeURL)
return coordinator
}
private func migrateStore() throws {
let idx = try indexOfCompatibleMom(at: storeURL, moms: moms)
let remaining = moms.suffix(from: (idx + 1))
guard remaining.count > 0 else {
// The store already uses the latest model
return
}
_ = try remaining.reduce(moms[idx]) { sMom, dMom in
try migrateStore(from: sMom, to: dMom)
return dMom
}
}
private func indexOfCompatibleMom(at storeURL: URL, moms: [NSManagedObjectModel]) throws -> Int {
do {
let meta = try NSPersistentStoreCoordinator.metadataForPersistentStore(ofType: storeType, at: storeURL)
guard let idx = moms.firstIndex(where: { $0.isConfiguration(withName: nil, compatibleWithStoreMetadata: meta) }) else {
throw MBCoreDataError.incompatibleModels
}
return idx
} catch MBCoreDataError.incompatibleModels {
throw MBCoreDataError.incompatibleModels
} catch _ {
throw MBCoreDataError.notAStore
}
}
private func migrateStore(from sMom: NSManagedObjectModel, to dMom: NSManagedObjectModel) throws {
// Prepare temporary directory
let dir = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: nil)
defer {
try? FileManager.default.removeItem(at: dir)
}
// Perform migration
let mapping = try findMapping(from: sMom, to: dMom)
let destURL = dir.appendingPathComponent(storeURL.lastPathComponent)
let manager = NSMigrationManager(sourceModel: sMom, destinationModel: dMom)
try autoreleasepool {
try manager.migrateStore(
from: storeURL,
sourceType: storeType,
options: nil,
with: mapping,
toDestinationURL: destURL,
destinationType: storeType,
destinationOptions: nil
)
}
// Replace source store
let psc = NSPersistentStoreCoordinator(managedObjectModel: dMom)
try psc.replacePersistentStore(
at: storeURL,
destinationOptions: nil,
withPersistentStoreFrom: destURL,
sourceOptions: nil,
ofType: storeType
)
}
private func findMapping(from sMom: NSManagedObjectModel, to dMom: NSManagedObjectModel) throws -> NSMappingModel {
// Search for custom mapping models
if let mapping = NSMappingModel(from: mappingBundles, forSourceModel: sMom, destinationModel: dMom) {
return mapping
}
return try NSMappingModel.inferredMappingModel(forSourceModel: sMom, destinationModel: dMom)
}
}
|
mit
|
ee997745cdd00490ccf21f87a52ff2d9
| 31.511628 | 184 | 0.749642 | 3.926966 | false | true | false | false |
nathawes/swift
|
test/ClangImporter/cxx_interop_ir.swift
|
9
|
3421
|
// RUN: %target-swift-frontend -module-name cxx_ir -I %S/Inputs/custom-modules -module-cache-path %t -enable-cxx-interop -emit-ir -o - -primary-file %s | %FileCheck %s
import CXXInterop
// CHECK-LABEL: define hidden swiftcc void @"$s6cxx_ir13indirectUsageyyF"()
// CHECK: %0 = call %"class.ns::T"* @{{_Z5makeTv|"\?makeT@@YAPE?AVT@ns@@XZ"}}()
// CHECK: call void @{{_Z4useTPN2ns1TE|"\?useT@@YAXPE?AVT@ns@@@Z"}}(%"class.ns::T"* %2)
func indirectUsage() {
useT(makeT())
}
// CHECK-LABEL: define hidden swiftcc %swift.type* @"$s6cxx_ir14reflectionInfo3argypXpSo2nsV1TV_tF"
// CHECK: %0 = call swiftcc %swift.metadata_response @"$sSo2nsV1TVMa"({{i64|i32}} 0)
func reflectionInfo(arg: namespacedT) -> Any.Type {
return type(of: arg)
}
// CHECK: define hidden swiftcc void @"$s6cxx_ir24namespaceManglesIntoName3argySo2nsV1TV_tF"
func namespaceManglesIntoName(arg: namespacedT) {
}
// CHECK: define hidden swiftcc void @"$s6cxx_ir42namespaceManglesIntoNameForUsingShadowDecl3argySo2nsV14NamespacedTypeV_tF"
func namespaceManglesIntoNameForUsingShadowDecl(arg: NamespacedType) {
}
// CHECK-LABEL: define hidden swiftcc void @"$s6cxx_ir14accessNSMemberyyF"()
// CHECK: %0 = call %"class.ns::T"* @{{_ZN2ns7doMakeTEv|"\?doMakeT@ns@@YAPEAVT@1@XZ"}}()
// CHECK: call void @{{_Z4useTPN2ns1TE|"\?useT@@YAXPE?AVT@ns@@@Z"}}(%"class.ns::T"* %2)
func accessNSMember() {
useT(ns.doMakeT())
}
// CHECK-LABEL: define hidden swiftcc i32 @"$s6cxx_ir12basicMethods1as5Int32VSpySo0D0VG_tF"(i8* %0)
// CHECK: [[THIS_PTR1:%.*]] = bitcast i8* %0 to %TSo7MethodsV*
// CHECK: [[THIS_PTR2:%.*]] = bitcast %TSo7MethodsV* [[THIS_PTR1]] to %class.Methods*
// CHECK: [[RESULT:%.*]] = call {{(signext )?}}i32 @{{_ZN7Methods12SimpleMethodEi|"\?SimpleMethod@Methods@@QEAAHH@Z"}}(%class.Methods* [[THIS_PTR2]], i32{{( signext)?}} 4)
// CHECK: ret i32 [[RESULT]]
func basicMethods(a: UnsafeMutablePointer<Methods>) -> Int32 {
return a.pointee.SimpleMethod(4)
}
// CHECK-LABEL: define hidden swiftcc i32 @"$s6cxx_ir17basicMethodsConst1as5Int32VSpySo0D0VG_tF"(i8* %0)
// CHECK: [[THIS_PTR1:%.*]] = bitcast i8* %0 to %TSo7MethodsV*
// CHECK: [[THIS_PTR2:%.*]] = bitcast %TSo7MethodsV* [[THIS_PTR1]] to %class.Methods*
// CHECK: [[RESULT:%.*]] = call {{(signext )?}}i32 @{{_ZNK7Methods17SimpleConstMethodEi|"\?SimpleConstMethod@Methods@@QEBAHH@Z"}}(%class.Methods* [[THIS_PTR2]], i32{{( signext)?}} 3)
// CHECK: ret i32 [[RESULT]]
func basicMethodsConst(a: UnsafeMutablePointer<Methods>) -> Int32 {
return a.pointee.SimpleConstMethod(3)
}
// CHECK-LABEL: define hidden swiftcc i32 @"$s6cxx_ir18basicMethodsStatics5Int32VyF"()
// CHECK: [[RESULT:%.*]] = call {{(signext )?}}i32 @{{_ZN7Methods18SimpleStaticMethodEi|"\?SimpleStaticMethod@Methods@@SAHH@Z"}}(i32{{( signext)?}} 5)
// CHECK: ret i32 [[RESULT]]
func basicMethodsStatic() -> Int32 {
return Methods.SimpleStaticMethod(5)
}
// CHECK-LABEL: define hidden swiftcc i32 @"$s6cxx_ir12basicMethods1as5Int32VSpySo8Methods2VG_tF"(i8* %0)
// CHECK: [[THIS_PTR1:%.*]] = bitcast i8* %0 to %TSo8Methods2V*
// CHECK: [[THIS_PTR2:%.*]] = bitcast %TSo8Methods2V* [[THIS_PTR1]] to %class.Methods2*
// CHECK: [[RESULT:%.*]] = call {{(signext )?}}i32 @{{_ZN8Methods212SimpleMethodEi|"\?SimpleMethod@Methods2@@QEAAHH@Z"}}(%class.Methods2* [[THIS_PTR2]], i32{{( signext)?}} 4)
// CHECK: ret i32 [[RESULT]]
func basicMethods(a: UnsafeMutablePointer<Methods2>) -> Int32 {
return a.pointee.SimpleMethod(4)
}
|
apache-2.0
|
e733b5a95ea5be8b64ff4ae2a29ae9f2
| 51.630769 | 182 | 0.695411 | 2.928938 | false | false | false | false |
WhisperSystems/Signal-iOS
|
Signal/src/ConversationSearch.swift
|
1
|
10749
|
//
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
@objc
public protocol ConversationSearchControllerDelegate: UISearchControllerDelegate {
@objc
func conversationSearchController(_ conversationSearchController: ConversationSearchController,
didUpdateSearchResults resultSet: ConversationScreenSearchResultSet?)
@objc
func conversationSearchController(_ conversationSearchController: ConversationSearchController,
didSelectMessageId: String)
}
@objc
public class ConversationSearchController: NSObject {
// MARK: - Dependencies
private var databaseStorage: SDSDatabaseStorage {
return SDSDatabaseStorage.shared
}
// MARK: -
@objc
public static let kMinimumSearchTextLength: UInt = 2
@objc
public let uiSearchController = UISearchController(searchResultsController: nil)
@objc
public weak var delegate: ConversationSearchControllerDelegate?
let thread: TSThread
@objc
public let resultsBar: SearchResultsBar = SearchResultsBar(frame: .zero)
// MARK: Initializer
@objc
required public init(thread: TSThread) {
self.thread = thread
super.init()
resultsBar.resultsBarDelegate = self
uiSearchController.delegate = self
uiSearchController.searchResultsUpdater = self
uiSearchController.hidesNavigationBarDuringPresentation = false
uiSearchController.dimsBackgroundDuringPresentation = false
uiSearchController.searchBar.inputAccessoryView = resultsBar
applyTheme()
}
func applyTheme() {
OWSSearchBar.applyTheme(to: uiSearchController.searchBar)
}
}
extension ConversationSearchController: UISearchControllerDelegate {
public func didPresentSearchController(_ searchController: UISearchController) {
Logger.verbose("")
delegate?.didPresentSearchController?(searchController)
}
public func didDismissSearchController(_ searchController: UISearchController) {
Logger.verbose("")
delegate?.didDismissSearchController?(searchController)
}
}
extension ConversationSearchController: UISearchResultsUpdating {
var dbSearcher: FullTextSearcher {
return FullTextSearcher.shared
}
public func updateSearchResults(for searchController: UISearchController) {
Logger.verbose("searchBar.text: \( searchController.searchBar.text ?? "<blank>")")
guard let rawSearchText = searchController.searchBar.text?.stripped else {
self.resultsBar.updateResults(resultSet: nil)
self.delegate?.conversationSearchController(self, didUpdateSearchResults: nil)
return
}
let searchText = FullTextSearchFinder.normalize(text: rawSearchText)
BenchManager.startEvent(title: "Conversation Search", eventId: searchText)
guard searchText.count >= ConversationSearchController.kMinimumSearchTextLength else {
self.resultsBar.updateResults(resultSet: nil)
self.delegate?.conversationSearchController(self, didUpdateSearchResults: nil)
return
}
var resultSet: ConversationScreenSearchResultSet?
databaseStorage.asyncRead(block: { [weak self] transaction in
guard let self = self else {
return
}
resultSet = self.dbSearcher.searchWithinConversation(thread: self.thread, searchText: searchText, transaction: transaction)
}, completion: { [weak self] in
guard let self = self else {
return
}
self.resultsBar.updateResults(resultSet: resultSet)
self.delegate?.conversationSearchController(self, didUpdateSearchResults: resultSet)
})
}
}
extension ConversationSearchController: SearchResultsBarDelegate {
func searchResultsBar(_ searchResultsBar: SearchResultsBar,
setCurrentIndex currentIndex: Int,
resultSet: ConversationScreenSearchResultSet) {
guard let searchResult = resultSet.messages[safe: currentIndex] else {
owsFailDebug("messageId was unexpectedly nil")
return
}
BenchEventStart(title: "Conversation Search Nav", eventId: "Conversation Search Nav: \(searchResult.messageId)")
self.delegate?.conversationSearchController(self, didSelectMessageId: searchResult.messageId)
}
}
protocol SearchResultsBarDelegate: AnyObject {
func searchResultsBar(_ searchResultsBar: SearchResultsBar,
setCurrentIndex currentIndex: Int,
resultSet: ConversationScreenSearchResultSet)
}
public class SearchResultsBar: UIToolbar {
weak var resultsBarDelegate: SearchResultsBarDelegate?
var showLessRecentButton: UIBarButtonItem!
var showMoreRecentButton: UIBarButtonItem!
let labelItem: UIBarButtonItem
var resultSet: ConversationScreenSearchResultSet?
override init(frame: CGRect) {
labelItem = UIBarButtonItem(title: nil, style: .plain, target: nil, action: nil)
super.init(frame: frame)
let leftExteriorChevronMargin: CGFloat
let leftInteriorChevronMargin: CGFloat
if CurrentAppContext().isRTL {
leftExteriorChevronMargin = 8
leftInteriorChevronMargin = 0
} else {
leftExteriorChevronMargin = 0
leftInteriorChevronMargin = 8
}
let upChevron = #imageLiteral(resourceName: "ic_chevron_up").withRenderingMode(.alwaysTemplate)
showLessRecentButton = UIBarButtonItem(image: upChevron, style: .plain, target: self, action: #selector(didTapShowLessRecent))
showLessRecentButton.imageInsets = UIEdgeInsets(top: 2, left: leftExteriorChevronMargin, bottom: 2, right: leftInteriorChevronMargin)
showLessRecentButton.tintColor = UIColor.ows_systemPrimaryButton
let downChevron = #imageLiteral(resourceName: "ic_chevron_down").withRenderingMode(.alwaysTemplate)
showMoreRecentButton = UIBarButtonItem(image: downChevron, style: .plain, target: self, action: #selector(didTapShowMoreRecent))
showMoreRecentButton.imageInsets = UIEdgeInsets(top: 2, left: leftInteriorChevronMargin, bottom: 2, right: leftExteriorChevronMargin)
showMoreRecentButton.tintColor = UIColor.ows_systemPrimaryButton
let spacer1 = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let spacer2 = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
self.items = [showLessRecentButton, showMoreRecentButton, spacer1, labelItem, spacer2]
self.isTranslucent = false
self.isOpaque = true
self.barTintColor = Theme.toolbarBackgroundColor
self.autoresizingMask = .flexibleHeight
self.translatesAutoresizingMaskIntoConstraints = false
}
required init?(coder aDecoder: NSCoder) {
notImplemented()
}
@objc
public func didTapShowLessRecent() {
Logger.debug("")
guard let resultSet = resultSet else {
owsFailDebug("resultSet was unexpectedly nil")
return
}
guard let currentIndex = currentIndex else {
owsFailDebug("currentIndex was unexpectedly nil")
return
}
guard currentIndex + 1 < resultSet.messages.count else {
owsFailDebug("showLessRecent button should be disabled")
return
}
let newIndex = currentIndex + 1
self.currentIndex = newIndex
updateBarItems()
resultsBarDelegate?.searchResultsBar(self, setCurrentIndex: newIndex, resultSet: resultSet)
}
@objc
public func didTapShowMoreRecent() {
Logger.debug("")
guard let resultSet = resultSet else {
owsFailDebug("resultSet was unexpectedly nil")
return
}
guard let currentIndex = currentIndex else {
owsFailDebug("currentIndex was unexpectedly nil")
return
}
guard currentIndex > 0 else {
owsFailDebug("showMoreRecent button should be disabled")
return
}
let newIndex = currentIndex - 1
self.currentIndex = newIndex
updateBarItems()
resultsBarDelegate?.searchResultsBar(self, setCurrentIndex: newIndex, resultSet: resultSet)
}
var currentIndex: Int?
// MARK:
func updateResults(resultSet: ConversationScreenSearchResultSet?) {
if let resultSet = resultSet {
if resultSet.messages.count > 0 {
currentIndex = min(currentIndex ?? 0, resultSet.messages.count - 1)
} else {
currentIndex = nil
}
} else {
currentIndex = nil
}
self.resultSet = resultSet
updateBarItems()
if let currentIndex = currentIndex, let resultSet = resultSet {
resultsBarDelegate?.searchResultsBar(self, setCurrentIndex: currentIndex, resultSet: resultSet)
}
}
func updateBarItems() {
guard let resultSet = resultSet else {
labelItem.title = nil
showMoreRecentButton.isEnabled = false
showLessRecentButton.isEnabled = false
return
}
switch resultSet.messages.count {
case 0:
labelItem.title = NSLocalizedString("CONVERSATION_SEARCH_NO_RESULTS", comment: "keyboard toolbar label when no messages match the search string")
case 1:
labelItem.title = NSLocalizedString("CONVERSATION_SEARCH_ONE_RESULT", comment: "keyboard toolbar label when exactly 1 message matches the search string")
default:
let format = NSLocalizedString("CONVERSATION_SEARCH_RESULTS_FORMAT",
comment: "keyboard toolbar label when more than 1 message matches the search string. Embeds {{number/position of the 'currently viewed' result}} and the {{total number of results}}")
guard let currentIndex = currentIndex else {
owsFailDebug("currentIndex was unexpectedly nil")
return
}
labelItem.title = String(format: format, currentIndex + 1, resultSet.messages.count)
}
if let currentIndex = currentIndex {
showMoreRecentButton.isEnabled = currentIndex > 0
showLessRecentButton.isEnabled = currentIndex + 1 < resultSet.messages.count
} else {
showMoreRecentButton.isEnabled = false
showLessRecentButton.isEnabled = false
}
}
}
|
gpl-3.0
|
812fb7561cff3014f969322547d111c0
| 35.686007 | 225 | 0.673737 | 5.666315 | false | false | false | false |
yanqingsmile/RNAi
|
RNAi/AppDelegate.swift
|
1
|
1837
|
//
// AppDelegate.swift
// RNAi
//
// Created by Vivian Liu on 1/10/17.
// Copyright © 2017 Vivian Liu. All rights reserved.
//
import UIKit
import GoogleMobileAds
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// MARK: - Property
fileprivate(set) var genes: [Gene] = []
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
readPlistData()
UINavigationBar.appearance().tintColor = UIColor.white
// Initialize Google Mobile Ads SDK
GADMobileAds.configure(withApplicationID: "ca-app-pub-3264388918879738~6896285006")
return true
}
// MARK: - Private Methods
fileprivate func readPlistData() {
if let path = Bundle.main.path(forResource: "data", ofType: "plist"), let siRNALibrary = NSArray(contentsOfFile: path) {
var startIndex = 0
var endIndex = 1
while startIndex < siRNALibrary.count - 1, endIndex < siRNALibrary.count {
let startItem = siRNALibrary[startIndex] as! Dictionary<String, String>
let endItem = siRNALibrary[endIndex] as! Dictionary<String, String>
if startItem["siRNA Pool Name"] == endItem["siRNA Pool Name"] {
endIndex += 1
} else {
let range = NSMakeRange(startIndex, endIndex - startIndex)
let gene = Gene(dataArray: siRNALibrary.subarray(with: range) as NSArray)
genes.append(gene)
startIndex = endIndex
endIndex = startIndex + 1
}
}
}
}
}
|
mit
|
1482b21275bef5d46067f00c0208841f
| 35 | 144 | 0.608932 | 4.744186 | false | false | false | false |
toshiapp/toshi-ios-client
|
Tests/EthereumAPIClientTests.swift
|
1
|
13832
|
// Copyright (c) 2018 Token Browser, Inc
//
// 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 XCTest
import UIKit
import Quick
import Nimble
import Teapot
@testable import Toshi
class EthereumAPIClientTests: QuickSpec {
let parameters: [String: Any] = [
"from": "0x011c6dd9565b8b83e6a9ee3f06e89ece3251ef2f",
"to": "0x011c6dd9565b8b83e6a9ee3f06e89ece3251ef2f",
"value": "0x330a41d05c8a780a"
]
override func spec() {
describe("the Ethereum API Client") {
// swiftlint:disable:next implicitly_unwrapped_optional - Testing setup
var subject: EthereumAPIClient!
guard let testCereal = Cereal(entropy: Cereal.generateEntropy()) else {
fail("Could not generate test cereal!")
return
}
HeaderGenerator.setTestingCereal(testCereal)
context("Happy path 😎") {
it("creates an unsigned transaction") {
let mockTeapot = MockTeapot(bundle: Bundle(for: EthereumAPIClientTests.self), mockFilename: "createUnsignedTransaction")
subject = EthereumAPIClient(mockTeapot: mockTeapot)
waitUntil { done in
subject.createUnsignedTransaction(parameters: self.parameters) { transaction, error in
expect(transaction).toNot(beNil())
expect(error).to(beNil())
expect(transaction).to(equal("0xf085746f6b658d8504a817c800825208945c156634bc3aed611e71550fb8a54480b480cd3b8718972b8c63638a80748080"))
done()
}
}
}
it("fetches the transaction Skeleton") {
let mockTeapot = MockTeapot(bundle: Bundle(for: EthereumAPIClientTests.self), mockFilename: "transactionSkeleton")
mockTeapot.overrideEndPoint("timestamp", withFilename: "timestamp")
subject = EthereumAPIClient(mockTeapot: mockTeapot)
waitUntil { done in
subject.transactionSkeleton(for: self.parameters) { skeleton, error in
expect(skeleton).toNot(beNil())
expect(error).to(beNil())
expect(skeleton.gas).to(equal("0x5208"))
expect(skeleton.gasPrice).to(equal("0xa02ffee00"))
expect(skeleton.transaction).to(equal("0xf085746f6b656e850a02ffee0082520894011c6dd9565b8b83e6a9ee3f06e89ece3251ef2f8712103c5eee63dc80748080"))
done()
}
}
}
it("sends a signed transaction") {
let mockTeapot = MockTeapot(bundle: Bundle(for: EthereumAPIClientTests.self), mockFilename: "sendSignedTransaction")
mockTeapot.overrideEndPoint("timestamp", withFilename: "timestamp")
subject = EthereumAPIClient(mockTeapot: mockTeapot)
waitUntil(timeout: 3) { done in
let originalTransaction = "0xf085746f6b658d8504a817c800825208945c156634bc3aed611e71550fb8a54480b480cd3b8718972b8c63638a80748080"
let transactionSignature = "0x4f80931676670df5b7a919aeaa56ae1d0c2db1792e6e252ee66a30007022200e44f61e710dbd9b24bed46338bed73f21e3a1f28ac791452fde598913867ebbb701"
subject.sendSignedTransaction(originalTransaction: originalTransaction, transactionSignature: transactionSignature) { success, transactionHash, error in
expect(success).to(beTrue())
expect(transactionHash).toNot(beNil())
expect(error).to(beNil())
expect(transactionHash).to(equal("0xe649f968c44d293128b0fa79a9ccba81ed32d72d34205330aa21a77ab6457ae5"))
done()
}
}
}
it("gets the balance") {
let mockTeapot = MockTeapot(bundle: Bundle(for: EthereumAPIClientTests.self), mockFilename: "getBalance")
subject = EthereumAPIClient(mockTeapot: mockTeapot)
waitUntil { done in
subject.getBalance(address: "0x1ad0bb2d14595fa6ad885e53eaaa6c82339f9b98") { fetchedBalance, error in
expect(fetchedBalance).toNot(beNil())
expect(error).to(beNil())
expect(fetchedBalance).to(equal(3677824408863012874))
done()
}
}
}
it("gets tokens") {
let mockTeapot = MockTeapot(bundle: Bundle(for: EthereumAPIClientTests.self), mockFilename: "getTokens")
subject = EthereumAPIClient(mockTeapot: mockTeapot)
waitUntil { done in
subject.getTokens(address: testCereal.paymentAddress) { tokens, error in
expect(tokens).toNot(beNil())
expect(error).to(beNil())
let token = tokens.first as? Token
expect(token).toNot(beNil())
expect(token?.name).to(equal("Alphabet Token"))
expect(token?.symbol).to(equal("ABC"))
expect(token?.value).to(equal("0x1234567890abcdef"))
expect(token?.decimals).to(equal(Int(18)))
expect(token?.contractAddress).to(equal("0x0123456789012345678901234567890123456789"))
expect(token?.icon).to(equal("https://ethereum.service.toshi.org/token/ABC.png"))
done()
}
}
}
it("gets collectibles") {
let mockTeapot = MockTeapot(bundle: Bundle(for: EthereumAPIClientTests.self), mockFilename: "getCollectibles")
subject = EthereumAPIClient(mockTeapot: mockTeapot)
waitUntil { done in
subject.getCollectibles(address: testCereal.paymentAddress) { collectibles, error in
expect(collectibles).toNot(beNil())
expect(error).to(beNil())
let collectible = collectibles.first as? Collectible
expect(collectible).toNot(beNil())
expect(collectible?.name).to(equal("Cryptokitties"))
expect(collectible?.value).to(equal("0x10"))
expect(collectible?.contractAddress).to(equal("0x0123456789012345678901234567890123456789"))
expect(collectible?.icon).to(equal("https://www.cryptokitties.co/icons/logo.svg"))
done()
}
}
}
it("gets a single collectible") {
let mockTeapot = MockTeapot(bundle: Bundle(for: EthereumAPIClientTests.self), mockFilename: "getACollectible")
subject = EthereumAPIClient(mockTeapot: mockTeapot)
waitUntil { done in
subject.getCollectible(address: testCereal.paymentAddress, contractAddress: "0xb1690c08e213a35ed9bab7b318de14420fb57d8c") { collectible, error in
guard let collectible = collectible else {
fail("Collectible is nil")
return
}
expect(error).to(beNil())
expect(collectible.name).to(equal("Cryptokitties"))
expect(collectible.value).to(equal("0x10"))
expect(collectible.contractAddress).to(equal("0x0123456789012345678901234567890123456789"))
expect(collectible.icon).to(equal("https://www.cryptokitties.co/icons/logo.svg"))
guard let token = collectible.tokens?.first else {
fail("No tokens on a collectible")
return
}
expect(token.name).to(equal("Kitten 423423"))
expect(token.tokenId).to(equal("abcdef0123456"))
expect(token.image).to(equal("https://storage.googleapis.com/ck-kitty-image/0x06012c8cf97bead5deae237070f9587f8e7a266d/467583.svg"))
expect(token.description).to(equal("A kitten"))
done()
}
}
}
}
context("⚠ Unauthorized error 🔒") {
it("creates an unsigned transaction") {
let mockTeapot = MockTeapot(bundle: Bundle(for: EthereumAPIClientTests.self), mockFilename: "createUnsignedTransaction", statusCode: .unauthorized)
subject = EthereumAPIClient(mockTeapot: mockTeapot)
waitUntil { done in
subject.createUnsignedTransaction(parameters: self.parameters) { transaction, error in
expect(transaction).to(beNil())
expect(error).toNot(beNil())
expect(error?.description).to(equal("Error creating transaction"))
done()
}
}
}
it("fetches the transaction Skeleton") {
let mockTeapot = MockTeapot(bundle: Bundle(for: EthereumAPIClientTests.self), mockFilename: "transactionSkeleton", statusCode: .unauthorized)
mockTeapot.overrideEndPoint("timestamp", withFilename: "timestamp")
subject = EthereumAPIClient(mockTeapot: mockTeapot)
waitUntil { done in
subject.transactionSkeleton(for: self.parameters) { skeleton, error in
expect(skeleton).toNot(beNil())
expect(error).toNot(beNil())
expect(skeleton.gas).to(beNil())
expect(skeleton.gasPrice).to(beNil())
expect(skeleton.transaction).to(beNil())
done()
}
}
}
it("sends a signed transaction") {
let mockTeapot = MockTeapot(bundle: Bundle(for: EthereumAPIClientTests.self), mockFilename: "sendSignedTransaction", statusCode: .unauthorized)
mockTeapot.overrideEndPoint("timestamp", withFilename: "timestamp")
subject = EthereumAPIClient(mockTeapot: mockTeapot)
waitUntil(timeout: 3) { done in
let originalTransaction = "0xf085746f6b658d8504a817c800825208945c156634bc3aed611e71550fb8a54480b480cd3b8718972b8c63638a80748080"
let transactionSignature = "0x4f80931676670df5b7a919aeaa56ae1d0c2db1792e6e252ee66a30007022200e44f61e710dbd9b24bed46338bed73f21e3a1f28ac791452fde598913867ebbb701"
subject.sendSignedTransaction(originalTransaction: originalTransaction, transactionSignature: transactionSignature) { success, transactionHash, error in
expect(success).to(beFalse())
expect(transactionHash).to(beNil())
expect(error).toNot(beNil())
expect(error?.description).to(equal("An error occurred: request response status reported an issue. Status code: 401."))
done()
}
}
}
it("gets the balance") {
let mockTeapot = MockTeapot(bundle: Bundle(for: EthereumAPIClientTests.self), mockFilename: "getBalance", statusCode: .unauthorized)
subject = EthereumAPIClient(mockTeapot: mockTeapot)
waitUntil { done in
subject.getBalance(address: "0x1ad0bb2d14595fa6ad885e53eaaa6c82339f9b98") { number, error in
expect(number).to(equal(0))
expect(error).toNot(beNil())
expect(error?.description).to(equal("An error occurred: request response status reported an issue. Status code: 401."))
done()
}
}
}
}
}
}
}
|
gpl-3.0
|
cdcede09b705e0b1566a919a1a60f8e4
| 51.166038 | 185 | 0.532263 | 4.979827 | false | true | false | false |
zmian/xcore.swift
|
Sources/Xcore/Swift/Components/FeatureFlag/Core/Providers/CompositeFeatureFlagProvider.swift
|
1
|
1800
|
//
// Xcore
// Copyright © 2019 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
struct CompositeFeatureFlagProvider: FeatureFlagProvider, ExpressibleByArrayLiteral {
/// The registered list of providers.
private var providers: [FeatureFlagProvider] = []
init(_ providers: [FeatureFlagProvider]) {
self.providers = providers
}
init(arrayLiteral elements: FeatureFlagProvider...) {
self.providers = elements
}
/// Add given provider if it's not already included in the collection.
///
/// - Note: This method ensures there are no duplicate providers.
mutating func add(_ provider: FeatureFlagProvider) {
guard !providers.contains(where: { $0.id == provider.id }) else {
return
}
providers.append(provider)
}
/// Add list of given providers if they are not already included in the
/// collection.
///
/// - Note: This method ensures there are no duplicate providers.
mutating func add(_ providers: [FeatureFlagProvider]) {
providers.forEach {
add($0)
}
}
/// Removes the given provider.
mutating func remove(_ provider: FeatureFlagProvider) {
let ids = providers.map(\.id)
guard let index = ids.firstIndex(of: provider.id) else {
return
}
providers.remove(at: index)
}
}
extension CompositeFeatureFlagProvider {
var id: String {
providers.map(\.id).joined(separator: "_")
}
func value(forKey key: FeatureFlag.Key) -> FeatureFlag.Value? {
for provider in providers {
guard let value = provider.value(forKey: key) else {
continue
}
return value
}
return nil
}
}
|
mit
|
eed4129dd96bad5ca20dc170749b749f
| 24.7 | 85 | 0.612563 | 4.81016 | false | false | false | false |
qiuncheng/posted-articles-in-blog
|
Demos/QRCodeDemo/QRCodeDemo/QRScanViewController.swift
|
1
|
11228
|
//
// ScanViewController.swift
// YLQRCode
//
// Created by yolo on 2017/1/1.
// Copyright © 2017年 Qiuncheng. All rights reserved.
//
// 仅仅是视图和扫描的作用
//
import UIKit
import AVFoundation
import CoreImage
import SafariServices
enum YLScanSetupResult {
case successed
case failed
case unknown
}
class QRScanViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
fileprivate var captureSession = AVCaptureSession()
fileprivate var capturePreviewLayer: AVCaptureVideoPreviewLayer?
fileprivate var deviceInput: AVCaptureDeviceInput?
fileprivate var metadataOutput: AVCaptureMetadataOutput?
fileprivate var dimmingView: DimmingView?
fileprivate var rectOfInteres = CGRect.zero
fileprivate var sessionQueue = DispatchQueue(label: "com.vsccw.qrcode.session.queue", attributes: [], target: nil)
fileprivate var setupResult = YLScanSetupResult.successed
fileprivate var isFirstPush = false
fileprivate var activityView: UIActivityIndicatorView?
var style: ScanViewConfig?
fileprivate var selectPhotosButton: UIButton!
/// 得到的二维码String信息 去override
var resultString: String?
override func viewDidLoad() {
super.viewDidLoad()
isFirstPush = true
view.backgroundColor = UIColor.black
func authorizationStatus() -> YLScanSetupResult {
var setupResult = YLScanSetupResult.successed
let authorizationStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
switch authorizationStatus {
case .authorized:
setupResult = YLScanSetupResult.successed
case .notDetermined:
sessionQueue.suspend()
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { [weak self] (granted) in
if !granted {
setupResult = YLScanSetupResult.failed
}
self?.sessionQueue.resume()
})
break
case .denied:
setupResult = YLScanSetupResult.failed
break
default:
setupResult = YLScanSetupResult.unknown
break
}
return setupResult
}
setupResult = authorizationStatus()
dimmingView = DimmingView(frame: view.bounds)
let viewStyle = dimmingView!.style
let viewWidth = view.frame.width
let viewHeight = view.frame.height
let objectiveyY = ((viewHeight - viewStyle.scanRectWidthHeight) * 0.5 - viewStyle.contentOffSetUp + 64.0) / viewHeight
let objectiveX = (viewWidth - viewStyle.scanRectWidthHeight) * 0.5 / viewWidth
let objectiveHeight = viewStyle.scanRectWidthHeight / viewHeight
let objectiveWidth = viewStyle.scanRectWidthHeight / viewWidth
rectOfInteres = CGRect(x: objectiveyY,
y: objectiveX,
width: objectiveHeight,
height: objectiveWidth)
activityView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
activityView?.tintColor = UIColor.black
activityView?.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
activityView?.center = CGPoint(x: view.center.x, y: view.center.y - 100)
activityView?.hidesWhenStopped = true
view.addSubview(activityView!)
activityView?.startAnimating()
selectPhotosButton = UIButton(frame: CGRect(x: 35.0, y: viewHeight - 136.0, width: UIScreen.main.bounds.width - 70.0, height: 44.0))
selectPhotosButton.layer.masksToBounds = true
selectPhotosButton.layer.cornerRadius = 4.0
selectPhotosButton.backgroundColor = UIColor.yellow
selectPhotosButton.setTitle("扫描相册中的二维码", for: UIControlState())
selectPhotosButton.setTitleColor(UIColor.black, for: .normal)
selectPhotosButton.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
selectPhotosButton.addTarget(self, action: #selector(openAlbumAction(_:)), for: .touchUpInside)
/// 在一个新的队列里进行初始化工作,还是**主线程**
sessionQueue.sync { [weak self] in
self?.configSession()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
sessionQueue.sync { [weak self] in
guard let strongSelf = self else { return }
switch strongSelf.setupResult {
case .successed:
if strongSelf.isFirstPush {
strongSelf.startSessionRunning()
}
default:
// strongSelf.activityView?.stopAnimating()
let message = "没有权限获取相机"
let alertController = UIAlertController(title: "", message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "好", style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: "设置", style: .`default`, handler: { action in
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
}))
strongSelf.present(alertController, animated: true, completion: nil)
}
strongSelf.activityView?.stopAnimating()
strongSelf.view.addSubview(strongSelf.dimmingView!)
strongSelf.view.addSubview(strongSelf.selectPhotosButton)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
stopSessionRunning()
}
func startSessionRunning() {
captureSession.startRunning()
dimmingView?.beginAnimation()
}
func stopSessionRunning() {
captureSession.stopRunning()
DispatchQueue.safeMainQueue { [weak self] in
self?.dimmingView?.removeAnimations()
}
}
private func configSession() {
if setupResult != .successed {
return
}
/// setup session
captureSession.beginConfiguration()
do {
var defaultVedioDevice: AVCaptureDevice?
if #available(iOS 10.0, *) {
if let backCameraDevice = AVCaptureDevice.defaultDevice(withDeviceType: AVCaptureDeviceType.builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .back) {
defaultVedioDevice = backCameraDevice
}
else if let frontCameraDevice = AVCaptureDevice.defaultDevice(withDeviceType: AVCaptureDeviceType.builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .front) {
defaultVedioDevice = frontCameraDevice
}
}
else {
if let cameraDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) {
defaultVedioDevice = cameraDevice
}
}
let videoDeviceInput = try AVCaptureDeviceInput(device: defaultVedioDevice)
/// 添加自动对焦功能,否则不容易读取二维码
/// **添加了自动对焦,反而增大了模糊误差**
// if videoDeviceInput.device.isAutoFocusRangeRestrictionSupported
// && videoDeviceInput.device.isSmoothAutoFocusSupported {
// try videoDeviceInput.device.lockForConfiguration()
// videoDeviceInput.device.focusMode = .autoFocus
// videoDeviceInput.device.unlockForConfiguration()
// }
if captureSession.canAddInput(videoDeviceInput) {
captureSession.addInput(videoDeviceInput)
}
self.deviceInput = videoDeviceInput
}
catch {
print("无法添加input.")
setupResult = .failed
}
metadataOutput = AVCaptureMetadataOutput()
if captureSession.canAddOutput(metadataOutput) {
captureSession.addOutput(metadataOutput)
}
else {
setupResult = .failed
return
}
metadataOutput?.setMetadataObjectsDelegate(self, queue: self.sessionQueue)
metadataOutput?.metadataObjectTypes = metadataOutput?.availableMetadataObjectTypes
metadataOutput?.rectOfInterest = self.rectOfInteres
captureSession.commitConfiguration()
capturePreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
capturePreviewLayer?.frame = view.bounds
view.layer.insertSublayer(capturePreviewLayer!, at: 0)
}
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
for _supportedBarcode in metadataObjects {
guard let supportedBarcode = _supportedBarcode as? AVMetadataObject else { return }
if supportedBarcode.type == AVMetadataObjectTypeQRCode {
guard let barcodeObject = self.capturePreviewLayer?.transformedMetadataObject(for: supportedBarcode) as? AVMetadataMachineReadableCodeObject else { return }
self.stopSessionRunning()
QRScanCommon.playSound()
self.resultString = barcodeObject.stringValue
return
}
}
}
func openAlbumAction(_ sender: Any) {
self.stopSessionRunning()
isFirstPush = false
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let imagePickerView = UIImagePickerController()
imagePickerView.allowsEditing = false
imagePickerView.sourceType = .photoLibrary
imagePickerView.delegate = self
present(imagePickerView, animated: true, completion: nil)
}
}
}
extension QRScanViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
isFirstPush = true
picker.dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion: nil)
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
YLDetectQRCode.scanQRCodeFromPhotoLibrary(image: image) { [weak self] str in
if let result = str {
self?.resultString = result
QRScanCommon.playSound()
}
else {
self?.isFirstPush = false
showAlertView(title: "提醒", message: "没有二维码", cancelButtonTitle: "确定")
}
}
}
}
}
|
apache-2.0
|
e73c96677a044b4707ba8cd1d957ef79
| 38.163701 | 186 | 0.627987 | 5.725806 | false | false | false | false |
PomTTcat/YYModelGuideRead_JEFF
|
RxSwiftGuideRead/RxDemoSelf/RxDemoSelf/ViewController.swift
|
2
|
21651
|
//
// ViewController.swift
// RxDemoSelf
//
// Created by PomCat on 2019/7/18.
// PomCat
//
/*
RXSwift源码浅析(一)
https://juejin.im/post/5a355ab15188252bca04f0fd#heading-25
RXSwift源码浅析(二)
https://juejin.im/post/5a38d34ff265da430d582355
RxSwift 的概念
https://zhang759740844.github.io/2017/10/26/RxSwift%E4%B8%80%E4%BA%9B%E6%A6%82%E5%BF%B5/
https://zhang759740844.github.io/2017/11/14/RxSwift%E5%8E%9F%E7%90%86/
https://zhang759740844.github.io/2017/11/03/RxCocoa%E5%BA%94%E7%94%A8/ // cocoa
官方文档
https://beeth0ven.github.io/RxSwift-Chinese-Documentation/content/more_demo/calculator.html
*/
import UIKit
import RxCocoa
import RxSwift
class ViewController: UIViewController {
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let type = UIViewController.rx
print(type)
let vc = UIViewController()
// vc.rx
ObservablesDemo()
// SubjectsDemo()
// operatorsBeforeDoDemo()
// operatorsAfterDoDemo()
// operatorsToSome()
// actionHappen()
}
func ObservablesDemo() {
// let observable = Observable<Int>.just(1)
// let observable2 = Observable.of(1, 2, 3)
// let observable3 = Observable.from([1, 2, 3])
// let observable4 = Observable<Void>.empty()
// let observable5 = Observable<Any>.never()
// 通过create创建一个可观察序列
let observable = Observable<String>.create { observer in
// 实际使用:这里可以是异步发起一个请求,然后请求回来之后发出一些信号。比如请求错误,请求返回json.
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
// your code here
observer.onNext("1")
observer.onNext("121")
observer.onCompleted()
observer.onNext("???")
}
return Disposables.create()
}
let ob = observable.subscribe(onNext: { (element) in
print("Hi \(element)")
}, onError: { (error) in
print("error")
}, onCompleted: {
print("finish")
})
ob.disposed(by: disposeBag)
}
func SubjectsDemo() {
// 订阅后接受事件
func PublishSubject1() {
let disposeBag = DisposeBag()
// 创建 PublishSubject
let subject = PublishSubject<Int>()
// 订阅
subject.subscribe { print($0.element ?? $0) }
.disposed(by: disposeBag)
// 发送事件
subject.onNext(1) //1
// 结束订阅
subject.onCompleted() //completed
// 再次订阅
subject.subscribe { print($0.element ?? $0) }
.disposed(by: disposeBag) //completed
// 发送事件
subject.onNext(2)
}
// 有初始值的subject
func BehaviorSubjects1() {
let bag = DisposeBag()
// 创建 BehaviorSubject
let subject = BehaviorSubject(value: "Initial value")
// 订阅
subject.subscribe { print($0.element ?? $0) }
.disposed(by: bag) // Initial Value
// 发送事件
subject.onNext("X") // X
// 错误事件
subject.onError(MyError.anError) // anError
// 再次订阅
subject.subscribe { print($0.element ?? $0) }
.disposed(by: bag) // anError
// 发送事件。
subject.onNext("X") // 订阅接收到errorb之后,就不再接收信息。
}
// 有一定的缓存信息。此处设置缓存大小为2.
func ReplaySubjects1() {
let bag = DisposeBag()
// 创建 ReplaySubject
let subject = ReplaySubject<String>.create(bufferSize: 2)
// 发送事件
subject.onNext("1")
subject.onNext("2")
// 订阅
subject.subscribe { print($0.element ?? $0) }
.disposed(by: bag) // 1 2
// 发送错误
subject.onError(MyError.annError) // annError
// 再次订阅
subject.subscribe { print($0.element ?? $0) }
.disposed(by: bag) // 1 2 annError
// 发送事件
subject.onNext("3") // 没有任何反应
}
PublishSubject1()
// BehaviorSubjects1()
// ReplaySubjects1()
}
// 接受某个事件之前的所有事件,之后的都不接受。
func operatorsBeforeDoDemo() {
let bag = DisposeBag()
func takeDemo() {
Observable.of(1, 2, 3, 4, 5)
.take(2)
.subscribe { print($0.element ?? $0) }
.disposed(by: bag)
}
// 取到某个不满足条件的事件
func takeWhileDemo() {
Observable.of(2, 2, 1, 4, 5)
.enumerated().takeWhile{i,v in
print("this v:",v)
// 只有前两个是满足的,第三个不满足。complete
return i < 2
}.subscribe {
print($0.element ?? $0)
print("good")
}
.disposed(by: bag)
}
func takeUntilDemo() {
let subject = PublishSubject<String>()
let trigger = PublishSubject<String>()
subject.takeUntil(trigger)
.subscribe { print($0.element ?? $0 )}
.disposed(by: bag)
// ... 此时一直接受 next 事件
trigger.onNext("x")
// ... 现在忽略所有的 next 事件了
}
// 忽略数值一样的序列
func distinctUntilChangedDemo() {
Observable.of(1, 2, 2, 1)
.distinctUntilChanged()
.subscribe { print($0.element ?? $0) }
.disposed(by: bag)
}
func distinctUntilChangedDemo2() {
Observable.of(1, 2, 3, 2, 1)
.distinctUntilChanged { (a:Int, b) in
// 1,2 这种情况就被忽略了。
if a == 1 && b == 2 {
return true
}
return false
}.subscribe { print($0.element ?? $0) }
.disposed(by: bag)
}
takeDemo()
// takeWhileDemo()
// takeUntilDemo()
// distinctUntilChangedDemo()
// distinctUntilChangedDemo2()
}
func operatorsAfterDoDemo() {
let bag = DisposeBag()
// 用来忽略所有的 .next 事件。所以用来指接受 completed 事件
func ignoreElementsDemo() {
let strikes = PublishSubject<String>()
strikes.ignoreElements()
.subscribe{_ in print("You are out")}
.disposed(by: bag)
strikes.onNext("2")
}
// 获取索引序号的事件,忽略其他的所有 .next.从0开始。
func elementAtDemo() {
let strikes = PublishSubject<String>()
strikes.elementAt(1)
.subscribe{ element in print("this element:\(element)")}
.disposed(by: bag)
strikes.onNext("this 0")
strikes.onNext("this 1")
strikes.onNext("this 2")
strikes.onNext("this 3")
/*
this element:next(this 1)
this element:completed
*/
}
func filterDemo() {
Observable.of(1, 2, 3, 4, 5)
.filter { $0 % 2 == 0}
.subscribe { print($0.element ?? $0) }
.disposed(by: bag)
// 2 4
}
func skipDemo() {
Observable.of(1, 2, 3, 4, 5)
.skip(2)
.subscribe { print($0.element ?? $0)}
.disposed(by: bag)
// 3,4,5
}
// skipWhile 遍历数据,直到为否
func skipWhileDemo() {
Observable.of(3, 5, 7, 4, 5)
.skipWhile({ (number: Int) -> Bool in
print("look look :",number)
return number % 2 == 1
// 一旦为否,跳出循环。
})
.subscribe { print($0.element ?? $0)}
.disposed(by: bag)
/*
look look : 3
look look : 5
look look : 7
look look : 4
4
5
completed
*/
}
// 直到trigger有信号,subject才接受信号。
func skipUntilDemo() {
let subject = PublishSubject<String>()
let trigger = PublishSubject<String>()
subject.skipUntil(trigger)
.subscribe { print( $0.element ?? $0) }
.disposed(by: bag)
// ... 当前时刻虽然订阅了,但是发送事件是无反应的
subject.onNext("this 1")
subject.onNext("this 2")
trigger.onNext("a")
subject.onNext("this 3")
}
// ignoreElementsDemo()
// elementAtDemo()
// filterDemo()
// skipDemo()
// skipWhileDemo()
skipUntilDemo()
}
func operatorsToSome() {
let bag = DisposeBag()
// 序列成组输出
func toArrayDemo() {
Observable.of("A", "B", "C")
.toArray()
.subscribe({ print($0) })
.disposed(by: bag) // ["A", "B", "c"]
}
func mapDemo() {
Observable.of(1, 2, 3)
.map{ $0 * 2}
.subscribe{ print($0.element ?? $0) }
.disposed(by: bag)
}
//MARK: TODO这个还是不太懂
func flatMapDemo() {
// https://beeth0ven.github.io/RxSwift-Chinese-Documentation/content/decision_tree/flatMap.html
let first = BehaviorSubject(value: "👦🏻")
let second = BehaviorSubject(value: "🅰️")
let variable = Variable(first)
variable.asObservable()
// .flatMap({ (subj) in
// print(subj)
// return subj
// })
.flatMap { $0 }
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
first.onNext("🐱")
variable.value = second
second.onNext("🅱️")
first.onNext("🐶")
}
// 插入新的元素,返回新的Observable
func startWithDemo() {
let numbers = Observable.of(2, 3, 4)
let observable = numbers.startWith(1)
observable.subscribe{ print($0.element ?? $0) }
.disposed(by: bag)
}
// 内部的时间序列都 completed 后,merge 产生的事件序列才会 completed
func mergeDemo() {
let left = PublishSubject<String>()
let right = PublishSubject<String>()
// 将两个事件序列作为事件值
let source = Observable.of(left.asObservable(), right.asObservable())
// 将新的事件序列的元素合并,返回一个新的事件序列
let observable = source.merge()
observable.subscribe{ print($0.element ?? $0) }
.disposed(by: bag)
left.onNext("this l1")
left.onNext("this l2")
right.onNext("this r1")
left.onNext("this l3")
right.onNext("this r2")
left.onCompleted()
right.onNext("this r3")
right.onCompleted()
}
// 每有一个信号,合并两个源的最新状态。
func combineLatestDemo() {
let left = PublishSubject<String>()
let right = PublishSubject<String>()
let observable = Observable.combineLatest(left, right, resultSelector: {
lastLeft, lastRight in
"\(lastLeft) \(lastRight)"
})
observable.subscribe(onNext: { value in
print(value)
}).disposed(by: bag)
left.onNext("this l1")
left.onNext("this l2")
right.onNext("this r1")
left.onNext("this l3")
right.onNext("this r2")
left.onCompleted()
right.onNext("this r3")
right.onNext("this r4") // 这个时候left已经结束,就用的left最后一个值。l3
right.onCompleted()
}
// 和上面的 combineLatest 不同,zip 要求必须每个子序列都有新消息的时候,才触发事件。
func zipDemo() {
let left = PublishSubject<String>()
let right = PublishSubject<String>()
let observable = Observable.zip(left, right) {
lastLeft, lastRight in
"\(lastLeft) \(lastRight)"
}
observable.subscribe(onNext: { value in
print(value)
}).disposed(by: bag)
left.onNext("this l1")
left.onNext("this l2")
right.onNext("this r1")
left.onNext("this l3")
right.onNext("this r2")
left.onCompleted()
right.onNext("this r3")
right.onNext("this r4") // 这个时候left已经结束,r4永远不会匹配。
right.onCompleted()
}
// toArrayDemo()
// mapDemo()
flatMapDemo()
// startWithDemo()
// mergeDemo()
// combineLatestDemo()
// zipDemo()
}
func actionHappen() {
let bag = DisposeBag()
// 点击按钮后,获取textField最新的字符串。
func withLatestFromDemo() {
let button = PublishSubject<Void>()
let textField = PublishSubject<String>()
button.withLatestFrom(textField)
.subscribe { print($0.element ?? $0) }
.disposed(by: bag)
}
// Observable 没有更新值,那么不会触发事件,类似于 distinctUntilChanged
func simpleDemo() {
let button = PublishSubject<Void>()
let textField = PublishSubject<String>()
let Observable = textField.sample(button)
.subscribe { print($0.element ?? $0) }
.disposed(by: bag)
}
Void()
// 最先触发就一直订阅哪一个。会自动取消订阅另一个。
func ambDemo() {
let left = PublishSubject<String>()
let right = PublishSubject<String>()
left.amb(right)
.subscribe { print($0.element ?? $0) }
.disposed(by: bag)
}
// 手动去订阅其他信号源。
func switchLatestDemo() {
let one = PublishSubject<String>()
let two = PublishSubject<String>()
let three = PublishSubject<String>()
// source 的事件值类型是 Observable 类型
let source = PublishSubject<Observable<String>>()
let observable = source.switchLatest()
let disposable = observable.subscribe(onNext: { value in print(value) })
// 选择Observable one
source.onNext(one)
one.onNext("emit one") // emit
two.onNext("emit two") // 没有 emit
// 选择Observable two
source.onNext(two)
two.onNext("emit two") // emit
}
// 一串序列经过计算,最后返回一个值
func reduceDemo() {
Observable.of(1, 2, 3)
.reduce(10) { summary, newValue in
return summary + newValue
}.subscribe { print($0.element ?? "OK") }
.disposed(by: bag)
}
// scan 和 reduce 的不同在于,reduce 是一锤子买卖,scan 每次接收到事件值时都会触发一个事件:
func scanDemo() {
Observable.of(1, 2, 3)
.scan(0, accumulator: +)
.subscribe(onNext: { value in print(value) })
.disposed(by: bag)
}
// 假设replay值为2,有新的订阅者订阅时,会立即触发最近的3个事件。缓存了2个信号。
func replayDemo() {
let interval = Observable<Int>.interval(1,
scheduler:MainScheduler.instance).replay(2)
_ = interval.connect()
let d = Date()
print("Subscriber 2: start - at \(d)")
// (2,3) 4 5 ...
DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
_ = interval.subscribe(onNext: {
let d = Date()
print("Subscriber 2: Event - \($0) at \(d)")
})
}
/*
Subscriber 2: start - at 2019-07-19 09:32:44 +0000
Subscriber 2: Event - 2 at 2019-07-19 09:32:49 +0000 // 缓存的
Subscriber 2: Event - 3 at 2019-07-19 09:32:49 +0000 // 缓存的
Subscriber 2: Event - 4 at 2019-07-19 09:32:49 +0000 // 新的信号
Subscriber 2: Event - 5 at 2019-07-19 09:32:50 +0000
Subscriber 2: Event - 6 at 2019-07-19 09:32:51 +0000
*/
}
// buffer 时间和数量,其中一个条件满足,就发送数组信号。
func bufferDemo() {
let subject = PublishSubject<String>()
//每缓存3个元素则组合起来一起发出。
//如果1秒钟内不够3个也会发出(有几个发几个,一个都没有发空数组 [])
subject
.buffer(timeSpan: 1.0, count: 3, scheduler: MainScheduler.instance)
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
subject.onNext("a")
subject.onNext("b")
subject.onNext("c")
subject.onNext("1")
subject.onNext("2")
subject.onNext("3")
}
// 延时订阅
func delaySubscriptionDemo() {
Observable.of(1, 2, 1)
.delaySubscription(3, scheduler: MainScheduler.instance) //延迟3秒才开始订阅
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
}
// 将序列中的所有事件延迟执行,所以并不会忽略掉事件
func delayDemo() {
Observable.of(1, 2, 3, 4, 5)
.delay(1, scheduler: MainScheduler.instance)
.subscribe{ print($0.element ?? $0) }
}
// 一直重复
func intervalDemo() {
// Observable<Int>.interval(2, scheduler: MainScheduler.instance)
// .subscribe{ print("do it") }
// .disposed(by: bag)
let scheduler = SerialDispatchQueueScheduler(qos: .default)
let subscription = Observable<Int>.interval(.milliseconds(300), scheduler: scheduler)
.subscribe { event in
print(event)
print("\(Thread.current)")
}
// 主线程3秒之后把订阅关掉
Thread.sleep(forTimeInterval: 3.0)
subscription.dispose()
}
// 可以设置重复值
func timerDemo() {
print("\(Date.init())")
let scheduler = SerialDispatchQueueScheduler(qos: .default)
let subscription = Observable<Int>.timer(.seconds(3), period:.seconds(3), scheduler: scheduler).subscribe { event in
print(event)
print("\(Date.init())")
}
// 主线程3秒之后把订阅关掉
Thread.sleep(forTimeInterval: 10.0)
subscription.dispose()
}
// switchLatestDemo()
// reduceDemo()
// replayDemo()
bufferDemo()
// delaySubscriptionDemo()
// delayDemo()
// intervalDemo()
// timerDemo()
}
}
enum MyError: Error {
case anError
case annError
case level1Error
case level2Error
case level3Error
}
|
mit
|
ec173fece73a9b84ac3c70002dd7d912
| 30.867412 | 128 | 0.461226 | 4.419362 | false | false | false | false |
mortorqrobotics/MorTeam-ios
|
MorTeam/CalendarVC.swift
|
1
|
10222
|
//
// CalendarVC.swift
// MorTeam
//
// Created by arvin zadeh on 10/7/16.
// Copyright © 2016 MorTorq. All rights reserved.
//
import Foundation
import UIKit
import CVCalendar
class CalendarVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
struct Color {
static let selectedText = UIColor.black
static let text = UIColor.black
static let textDisabled = UIColor.gray
static let selectionBackground = UIColorFromHex("#FFC547")
static let sundayText = UIColor(red: 1.0, green: 0.2, blue: 0.2, alpha: 1.0)
static let sundayTextDisabled = UIColor.gray
static let sundaySelectionBackground = UIColorFromHex("#FFC547")
}
@IBOutlet weak var calendarView: CVCalendarView!
@IBOutlet weak var menuView: CVCalendarMenuView!
@IBOutlet weak var monthLabel: UILabel!
@IBOutlet var eventTableView: UITableView!
var shouldShowDaysOut = true
var animationFinished = true
var selectedDay:DayView!
var showingEvents = [Event]()
let morTeamUrl = "http://www.morteam.com/api"
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
monthLabel.text = CVDate(date: Date()).globalDescription
self.loadEvents(month: CVDate(date: Date()).month, year: CVDate(date: Date()).year)
}
func setup(){
self.view.backgroundColor = UIColor.white
self.eventTableView.backgroundColor = UIColor.white
self.eventTableView.separatorInset = .zero
}
func loadEvents(month: Int, year: Int){
DispatchQueue.main.async(execute: {
//For early empty and refresh
self.showingEvents = []
self.eventTableView.reloadData()
if let cc = self.calendarView.contentController as? CVCalendarMonthContentViewController {
cc.refreshPresentedMonth()
}
})
httpRequest(self.morTeamUrl+"/events/startYear/\(year)/startMonth/\(month-1)/endYear/\(year)/endMonth/\(month-1)", type: "GET"){
responseText, responseCode in
let events = parseJSON(responseText)
self.showingEvents = []
for(_, json):(String, JSON) in events {
self.showingEvents.append(Event(eventJSON: json))
}
DispatchQueue.main.async(execute: {
self.eventTableView.reloadData()
if let cc = self.calendarView.contentController as? CVCalendarMonthContentViewController {
cc.refreshPresentedMonth()
}
})
}
}
@IBAction func didClickAddEvent(_ sender: AnyObject) {
DispatchQueue.main.async(execute: {
let vc: AddEventVC! = self.storyboard!.instantiateViewController(withIdentifier: "AddEvent") as! AddEventVC
self.show(vc as UIViewController, sender: vc)
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.showingEvents.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = eventTableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CalendarTableViewCell
let row = (indexPath as NSIndexPath).row
let event = self.showingEvents[row]
cell.selectionStyle = .none
cell.dayView.text = "\(event.day)" //Thanks, type safety
cell.eventDescriptionLabel.text = event.description
if (event.description == "null") {
cell.eventDescriptionLabel.text = "--"
}
cell.eventTitleLabel.text = event.name
return cell
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
calendarView.commitCalendarViewUpdate()
menuView.commitMenuViewUpdate()
}
}
extension CalendarVC: CVCalendarViewDelegate, CVCalendarMenuViewDelegate {
func presentationMode() -> CalendarMode {
return .monthView
}
func firstWeekday() -> Weekday {
return .sunday
}
func dayOfWeekTextColor(by weekday: Weekday) -> UIColor {
return UIColor.black
}
func shouldShowWeekdaysOut() -> Bool {
return shouldShowDaysOut
}
func shouldAnimateResizing() -> Bool {
return true
}
func didSelectDayView(_ dayView: CVCalendarDayView, animationDidFinish: Bool) {
let day = dayView.date.day
let month = dayView.date.month
let year = dayView.date.year
for (index, event) in self.showingEvents.enumerated() {
if (event.day == day && event.year == year && event.month == month){
let indexPath = IndexPath(row: index, section: 0)
self.eventTableView.scrollToRow(at: indexPath, at: .top, animated: true)
break
}
}
}
func presentedDateUpdated(_ date: CVDate) {
if monthLabel.text != date.globalDescription && self.animationFinished {
DispatchQueue.main.async(execute: {
self.loadEvents(month: date.month, year: date.year)
})
let updatedMonthLabel = UILabel()
updatedMonthLabel.textColor = monthLabel.textColor
updatedMonthLabel.font = monthLabel.font
updatedMonthLabel.textAlignment = .center
updatedMonthLabel.text = date.globalDescription
updatedMonthLabel.sizeToFit()
updatedMonthLabel.alpha = 0
updatedMonthLabel.center = self.monthLabel.center
let offset = CGFloat(48)
updatedMonthLabel.transform = CGAffineTransform(translationX: 0, y: offset)
updatedMonthLabel.transform = CGAffineTransform(scaleX: 1, y: 0.1)
UIView.animate(withDuration: 0.35, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.animationFinished = false
self.monthLabel.transform = CGAffineTransform(translationX: 0, y: -offset)
self.monthLabel.transform = CGAffineTransform(scaleX: 1, y: 0.1)
self.monthLabel.alpha = 0
updatedMonthLabel.alpha = 1
updatedMonthLabel.transform = CGAffineTransform.identity
}) { _ in
self.animationFinished = true
self.monthLabel.frame = updatedMonthLabel.frame
self.monthLabel.text = updatedMonthLabel.text
self.monthLabel.transform = CGAffineTransform.identity
self.monthLabel.alpha = 1
updatedMonthLabel.removeFromSuperview()
}
self.view.insertSubview(updatedMonthLabel, aboveSubview: self.monthLabel)
}
}
func topMarker(shouldDisplayOnDayView dayView: CVCalendarDayView) -> Bool {
return true
}
func dotMarker(shouldShowOnDayView dayView: CVCalendarDayView) -> Bool {
let day = dayView.date.day
let month = dayView.date.month
for event in self.showingEvents {
if (day == event.day && month == event.month){
return true
}
}
return false
}
func dotMarker(colorOnDayView dayView: CVCalendarDayView) -> [UIColor] {
return [UIColorFromHex("#FFC547")]
}
func dotMarker(shouldMoveOnHighlightingOnDayView dayView: CVCalendarDayView) -> Bool {
return true
}
func dotMarker(sizeOnDayView dayView: DayView) -> CGFloat {
return 13
}
func weekdaySymbolType() -> WeekdaySymbolType {
return .short
}
func selectionViewPath() -> ((CGRect) -> (UIBezierPath)) {
return { UIBezierPath(rect: CGRect(x: 0, y: 0, width: $0.width, height: $0.height)) }
}
func shouldShowCustomSingleSelection() -> Bool {
return false
}
func preliminaryView(viewOnDayView dayView: DayView) -> UIView {
let circleView = CVAuxiliaryView(dayView: dayView, rect: dayView.bounds, shape: CVShape.circle)
circleView.fillColor = .colorFromCode(0xCCCCCC)
return circleView
}
func preliminaryView(shouldDisplayOnDayView dayView: DayView) -> Bool {
if (dayView.isCurrentDay) {
return true
}
return false
}
func dayOfWeekTextColor() -> UIColor {
return UIColor.white
}
func dayOfWeekBackGroundColor() -> UIColor {
return UIColorFromHex("#FFC547")
}
}
extension CalendarVC: CVCalendarViewAppearanceDelegate {
func dayLabelPresentWeekdayInitallyBold() -> Bool {
return false
}
func spaceBetweenDayViews() -> CGFloat {
return 0.0
}
func dayLabelFont(by weekDay: Weekday, status: CVStatus, present: CVPresent) -> UIFont { return UIFont.systemFont(ofSize: 14) }
func dayLabelColor(by weekDay: Weekday, status: CVStatus, present: CVPresent) -> UIColor? {
switch (weekDay, status, present) {
case (_, .selected, _), (_, .highlighted, _): return Color.selectedText
case (.sunday, .in, _): return Color.text
case (.sunday, _, _): return Color.textDisabled
case (_, .in, _): return Color.text
default: return Color.textDisabled
}
}
func dayLabelBackgroundColor(by weekDay: Weekday, status: CVStatus, present: CVPresent) -> UIColor? {
switch (weekDay, status, present) {
case (.sunday, .selected, _), (.sunday, .highlighted, _): return Color.sundaySelectionBackground
case (_, .selected, _), (_, .highlighted, _): return Color.selectionBackground
default: return nil
}
}
}
extension CalendarVC {
@IBAction func todayMonthView() {
calendarView.toggleCurrentDayView()
}
}
|
mit
|
0060f2bee648c71c7a549f48fd51c05d
| 31.550955 | 136 | 0.602681 | 5.16473 | false | false | false | false |
s4cha/then
|
Sources/Then/Promise+Recover.swift
|
3
|
3551
|
//
// Promise+Recover.swift
// then
//
// Created by Sacha Durand Saint Omer on 22/02/2017.
// Copyright © 2017 s4cha. All rights reserved.
//
import Foundation
extension Promise {
public func recover(with value: T) -> Promise<T> {
let p = newLinkedPromise()
syncStateWithCallBacks(
success: p.fulfill,
failure: { _ in
p.fulfill(value)
}, progress: p.setProgress)
return p
}
public func recover<E: Error>(_ errorType: E, with value: T) -> Promise<T> {
let p = newLinkedPromise()
syncStateWithCallBacks(
success: p.fulfill,
failure: { e in
if errorMatchesExpectedError(e, expectedError: errorType) {
p.fulfill(value)
} else {
p.reject(e)
}
},
progress: p.setProgress)
return p
}
public func recover<E: Error>(_ errorType: E, with value: T) -> Promise<T> where E: Equatable {
let p = newLinkedPromise()
syncStateWithCallBacks(
success: p.fulfill,
failure: { e in
if errorMatchesExpectedError(e, expectedError: errorType) {
p.fulfill(value)
} else {
p.reject(e)
}
},
progress: p.setProgress)
return p
}
public func recover(with promise: Promise<T>) -> Promise<T> {
let p = newLinkedPromise()
syncStateWithCallBacks(
success: p.fulfill,
failure: { _ in
promise.then { t in
p.fulfill(t)
}.onError { error in
p.reject(error)
}
},
progress: p.setProgress)
return p
}
public func recover(_ block:@escaping (Error) throws -> T) -> Promise<T> {
let p = newLinkedPromise()
syncStateWithCallBacks(
success: p.fulfill,
failure: { e in
do {
let v = try block(e)
p.fulfill(v)
} catch {
p.reject(error)
}
}, progress: p.setProgress)
return p
}
public func recover(_ block:@escaping (Error) throws -> Promise<T>) -> Promise<T> {
let p = newLinkedPromise()
syncStateWithCallBacks(
success: p.fulfill,
failure: { e in
do {
let promise = try block(e)
promise.then { t in
p.fulfill(t)
}.onError { error in
p.reject(error)
}
} catch {
p.reject(error)
}
}, progress: p.setProgress)
return p
}
}
// Credits to Quick/Nimble for how to compare Errors
// https://github.com/Quick/Nimble/blob/db706fc1d7130f6ac96c56aaf0e635fa3217fe57/Sources/
// Nimble/Utils/Errors.swift#L37-L53
private func errorMatchesExpectedError<T: Error>(_ error: Error, expectedError: T) -> Bool {
return error._domain == expectedError._domain && error._code == expectedError._code
}
private func errorMatchesExpectedError<T: Error>(_ error: Error,
expectedError: T) -> Bool where T: Equatable {
if let error = error as? T {
return error == expectedError
}
return false
}
|
mit
|
58853bfe4a4daa4cb7ec5d629392230a
| 29.084746 | 99 | 0.492676 | 4.516539 | false | false | false | false |
infobip/mobile-messaging-sdk-ios
|
Classes/Core/CustomEvents/EventsService.swift
|
1
|
3816
|
//
// EventsService.swift
// MobileMessaging
//
// Created by Andrey Kadochnikov on 31.01.2020.
//
import Foundation
import CoreData
@objcMembers public class MMBaseEvent: NSObject {
/**
Event ID that is generated on the Portal for your custom Event Definition.
*/
public let definitionId: String
public init(definitionId: String) {
self.definitionId = definitionId
}
}
/**
CustomEvent class represents Custom event. Events allow you to track arbitrary user actions and collect arbitrary contextual information represented by event key-value properties.
*/
@objcMembers public class MMCustomEvent: MMBaseEvent {
/**
Arbitrary contextual data of the custom event.
*/
public let properties: [String: MMEventPropertyType]?
/**
Initializes a custom event.
- parameter definitionId: Event ID that is generated on the Portal for your custom Event Definition.
- parameter properties: Arbitrary contextual data of the custom event.
*/
public init(definitionId: String, properties: [String: MMEventPropertyType]?) {
self.properties = properties
super.init(definitionId: definitionId)
}
//Method is needed for plugins support
public required convenience init?(dictRepresentation dict: DictionaryRepresentation) {
let value = JSON.init(dict)
guard let definitionId = value["definitionId"].string else {
return nil
}
self.init(definitionId: definitionId,
properties: value["properties"].dictionary?.decodeCustomEventPropertiesJSON)
}
}
class EventsService: MobileMessagingService {
private let q: DispatchQueue
private let eventReportingQueue: MMOperationQueue
private let eventPersistingQueue: MMOperationQueue
private let context: NSManagedObjectContext
lazy var reportPostponer = MMPostponer(executionQueue: DispatchQueue.global())
init(mmContext: MobileMessaging) {
self.q = DispatchQueue(label: "events-service", qos: DispatchQoS.default, attributes: .concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil)
self.context = mmContext.internalStorage.newPrivateContext()
self.eventReportingQueue = MMOperationQueue.newSerialQueue(underlyingQueue: q)
self.eventPersistingQueue = MMOperationQueue.newSerialQueue(underlyingQueue: q)
super.init(mmContext: mmContext, uniqueIdentifier: "EventsService")
}
func submitEvent(customEvent: MMCustomEvent, reportImmediately: Bool, completion: @escaping (NSError?) -> Void) {
guard let pushRegistrationId = mmContext.currentInstallation().pushRegistrationId else {
completion(NSError(type: .NoRegistration))
return
}
if reportImmediately {
self.scheduleReport(userInitiated: true, customEvent: customEvent, completion: completion)
} else {
persistEvent(customEvent, pushRegistrationId) {
self.reportPostponer.postponeBlock(block: {
self.scheduleReport(userInitiated: false, customEvent: nil, completion: completion)
})
}
}
}
override func appWillEnterForeground(_ completion: @escaping () -> Void) {
scheduleReport(userInitiated: false, customEvent: nil, completion: { _ in completion() })
}
private func persistEvent(_ customEvent: MMCustomEvent, _ pushRegistrationId: String, completion: @escaping () -> Void) {
eventPersistingQueue.addOperation(EventPersistingOperation(customEvent: customEvent, mmContext: mmContext, pushRegId: pushRegistrationId, context: context, finishBlock: { _ in completion() }))
}
private func scheduleReport(userInitiated: Bool, customEvent: MMCustomEvent?, completion: @escaping ((NSError?) -> Void)) {
self.eventReportingQueue.addOperation(CustomEventReportingOperation(userInitiated: userInitiated, customEvent: customEvent, context: context, mmContext: self.mmContext, finishBlock: completion))
}
}
|
apache-2.0
|
8a4809cc32c6691ce0885925a41cee8e
| 40.032258 | 202 | 0.76153 | 4.391254 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.