repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
yanqingsmile/RNAi
|
refs/heads/master
|
RNAi/Constants.swift
|
mit
|
1
|
//
// Constants.swift
// RNAi
//
// Created by Vivian Liu on 1/19/17.
// Copyright © 2017 Vivian Liu. All rights reserved.
//
import Foundation
struct CellIdentifier {
static let masterGeneCellIdentifier = "GeneCellIdentifier"
static let masterHeaderCellIdentifier = "MasterHeaderCellIdentifier"
static let detailCellIdentifier = "siRNADetailIdentifier"
static let detailHeaderCellIdentifier = "DetailHeaderCellIdentifier"
static let savedCellIdentifier = "SavedCellIdentifier"
static let savedHeaderIdentifier = "SavedHeaderCellIdentifier"
}
struct TextLabel {
static let headerCellTextLabel = "Gene Name"
static let headerCellDetailTextLabel = "Accession Number"
}
struct SegueIdentifier {
static let showDetailFromMasterToDetail = "ShowDetailFromMaster"
static let showDetailFromSavedToDetail = "showDetailFromSaved"
}
struct ConstantString {
static let userDefaultsKey = "savedGeneNames"
static let geneNCBIUrlPrefix = "https://www.ncbi.nlm.nih.gov/gene/?term="
static let genomeRNAiURLPrefix = "http://genomernai.dkfz.de/v16/reagentdetails/"
static let unSavedImageName = "emptyHeart"
static let savedImageName = "filledHeart"
}
|
e4cc0812f31c117a9380a3bb738367a8
| 31.540541 | 84 | 0.766611 | false | false | false | false |
bitjammer/swift
|
refs/heads/master
|
test/SILGen/complete_object_init.swift
|
apache-2.0
|
3
|
// RUN: %target-swift-frontend %s -emit-silgen | %FileCheck %s
struct X { }
class A {
// CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick A.Type) -> @owned A
// CHECK: bb0([[SELF_META:%[0-9]+]] : $@thick A.Type):
// CHECK: [[SELF:%[0-9]+]] = alloc_ref_dynamic [[SELF_META]] : $@thick A.Type, $A
// CHECK: [[OTHER_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A
// CHECK: [[RESULT:%[0-9]+]] = apply [[OTHER_INIT]]([[SELF]]) : $@convention(method) (@owned A) -> @owned A
// CHECK: return [[RESULT]] : $A
// CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A
// CHECK: bb0([[SELF_PARAM:%[0-9]+]] : $A):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var A }
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*A
// CHECK: store [[SELF_PARAM]] to [init] [[SELF]] : $*A
// CHECK: [[SELFP:%[0-9]+]] = load [take] [[SELF]] : $*A
// CHECK: [[INIT:%[0-9]+]] = class_method [[SELFP]] : $A, #A.init!initializer.1 : (A.Type) -> (X) -> A, $@convention(method) (X, @owned A) -> @owned A
// CHECK: [[X_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X
// CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type
// CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X
// CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT]]([[X]], [[SELFP]]) : $@convention(method) (X, @owned A) -> @owned A
// CHECK: store [[INIT_RESULT]] to [init] [[SELF]] : $*A
// CHECK: [[RESULT:%[0-9]+]] = load [copy] [[SELF]] : $*A
// CHECK: destroy_value [[SELF_BOX]] : ${ var A }
// CHECK: return [[RESULT]] : $A
convenience init() {
self.init(x: X())
}
init(x: X) { }
}
|
a15fbd9ecd7ef130419bd40b4643e139
| 53.388889 | 152 | 0.543412 | false | false | false | false |
i-schuetz/rest_client_ios
|
refs/heads/master
|
clojushop_client_ios/CartViewController.swift
|
apache-2.0
|
1
|
//
// CartViewController.swift
// clojushop_client_ios
//
// Created by ischuetz on 08/06/2014.
// Copyright (c) 2014 ivanschuetz. All rights reserved.
//
import Foundation
class CartViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate, SingleSelectionControllerDelegate {
@IBOutlet var tableView: UITableView!
@IBOutlet var emptyCartView: UIView!
@IBOutlet var totalContainer: UIView!
@IBOutlet var buyView: UIView!
@IBOutlet var totalView: UILabel!
var quantityPicker: SingleSelectionViewController!
// var quantityPicker: SingleSelectionViewController<CartItem>!
var quantityPickerPopover: UIPopoverController!
var items: [CartItem] = []
var showingController: Bool! = false //quickfix to avoid reloading when coming back from quantity controller
var currency: Currency!
typealias BaseObjectType = CartItem
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.tabBarItem.title = "Cart"
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func clearCart() {
self.items.removeAll(keepCapacity: false)
self.tableView.reloadData()
var a : [String] = []
a.removeAll(keepCapacity: false)
}
func onRetrievedItems(items: [CartItem]) {
self.items = items
if (items.count == 0) {
self.showCartState(true)
} else {
self.showCartState(false)
self.tableView.reloadData()
self.onModifyLocalCartContent()
}
}
func showCartState(empty: Bool) {
emptyCartView.hidden = !empty
}
func onModifyLocalCartContent() {
if (items.count == 0) {
totalView.text = "0" //just for consistency
self.showCartState(true)
} else {
//TODO server calculates this
//TODO multiple currencies
//for now we assume all the items have the same currency
let currencyId = items[0].currency
self.totalView.text = CurrencyManager.sharedCurrencyManager().getFormattedPrice(self.getTotalPrice(items), currencyId: currencyId)
self.showCartState(false)
self.tableView.reloadData()
}
}
func getTotalPrice(cartItems:[CartItem]) -> Double {
return cartItems.reduce(0.0, combine: {$0 + ($1.price * Double($1.quantity))})
}
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "CartItemCell", bundle: nil)
self.tableView.registerNib(nib, forCellReuseIdentifier: "CartItemCell")
self.emptyCartView.hidden = true
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if !self.showingController {
self.requestItems()
}
self.showingController = false
self.adjustLayout()
}
func requestItems() {
self.setProgressHidden(false, transparent: false)
DataStore.sharedDataStore().getCart(
{(items:[CartItem]!) -> Void in
self.setProgressHidden(true, transparent: false)
self.onRetrievedItems(items)
}, failureHandler: {(Int) -> Bool in
self.setProgressHidden(true, transparent: false)
self.emptyCartView.hidden = false
return false
})
}
func adjustLayout() {
if let navigationController = self.navigationController {
navigationController.navigationBar.translucent = false;
let screenBounds: CGRect = UIScreen.mainScreen().bounds
if let tabBarController = self.tabBarController {
let h:CGFloat = screenBounds.size.height -
(CGRectGetHeight(tabBarController.tabBar.frame)
+ CGRectGetHeight(navigationController.navigationBar.frame)
+ CGRectGetHeight(self.buyView.frame))
self.tableView.frame = CGRectMake(0, CGRectGetHeight(self.buyView.frame), self.tableView.frame.size.width, h)
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier:String = "CartItemCell"
let cell: CartItemCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as CartItemCell
cell.selectionStyle = UITableViewCellSelectionStyle.None
let item: CartItem = items[indexPath.row]
cell.productName.text = item.name
cell.productDescr.text = item.descr
cell.productBrand.text = item.seller
cell.productPrice.text = CurrencyManager.sharedCurrencyManager().getFormattedPrice(item.price, currencyId: item.currency)
cell.quantityField.text = String(item.quantity)
cell.controller = self
cell.tableView = self.tableView
cell.productImg.setImageWithURL(NSURL(string: item.imgList))
return cell
}
func tableView(tableView:UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> Double {
return 133
}
func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
if editingStyle == UITableViewCellEditingStyle.Delete {
let item:CartItem = items[indexPath.row]
DataStore.sharedDataStore().removeFromCart(item.id, successHandler: {() -> Void in
self.items.removeAtIndex(indexPath.row)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
self.onModifyLocalCartContent()
}, failureHandler: {(Int) -> Bool in return false})
}
}
func setQuantity(sender: AnyObject, atIndexPath ip:NSIndexPath) {
let selectedCartItem:CartItem = items[ip.row]
let quantities:[Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
let cartItemsForQuantitiesDialog:[SingleSelectionItem] = self.wrapQuantityItemsForDialog(quantities)
// let selectQuantityController:SingleSelectionViewController<CartItem> = SingleSelectionViewController<CartItem>(style: UITableViewStyle.Plain)
let selectQuantityController:SingleSelectionViewController = SingleSelectionViewController(style: UITableViewStyle.Plain)
selectQuantityController.items = cartItemsForQuantitiesDialog
println(selectQuantityController.items.count)
selectQuantityController.delegate = self
selectQuantityController.baseObject = selectedCartItem
self.showingController = true
self.presentViewController(selectQuantityController, animated: true, completion: nil)
}
func wrapQuantityItemsForDialog(quantities: [Int]) -> [SingleSelectionItem] {
return quantities.map {(let q) -> SingleSelectionItem in CartQuantityItem(quantity: q)
as SingleSelectionItem //TOOD check if it works correctly without casting (specially resulting array count)
}
}
@IBAction func onBuyPress(sender: UIButton) {
let paymentViewController:PaymentViewController = PaymentViewController(nibName:"CSPaymentViewController", bundle:nil)
paymentViewController.totalValue = self.getTotalPrice(items)
// TODO
// paymentViewController.currency = [CSCurrency alloc]initWithId:<#(int)#> format:<#(NSString *)#>;
self.navigationController?.pushViewController(paymentViewController, animated: true)
}
func selectedItem(item: SingleSelectionItem, baseObject:AnyObject) {
var cartItem = baseObject as CartItem //FIXME insufficient generics, have to cast
let quantity:Int = item.getWrappedItem() as Int //FIXME insufficient generics, have to cast
self.setProgressHidden(false, transparent:true)
DataStore.sharedDataStore().setCartQuantity(cartItem.id, quantity: quantity,
{() -> Void in
cartItem.quantity = quantity
self.tableView.reloadData()
self.onModifyLocalCartContent()
self.setProgressHidden(true, transparent:true)
}, failureHandler: {(Int) -> Bool in return false
self.setProgressHidden(true, transparent: true)
})
}
}
|
d9ea4022be597b045de683c9f96288e6
| 34.584615 | 151 | 0.621879 | false | false | false | false |
vrrathod/YATC_swift
|
refs/heads/master
|
YATC_swift/Utils.swift
|
bsd-2-clause
|
1
|
//
// Utils.swift
// YATC_swift
//
// Created by personal on 8/28/14.
// Copyright (c) 2014 personal. All rights reserved.
//
import Foundation
class Utils {
////////////////////////////////////////////////////////////////////////////////////////////////
// Constants
////////////////////////////////////////////////////////////////////////////////////////////////
let QUALITY_SETTINGS_NAME = "qualitySettings";
let FOOD_QUALITY_NAME = "foodQuality";
let SERVICE_QUALITY_NAME = "serviceQuality";
let SPLIT_COUNT_NAME = "splitCount";
let SPLIT_SETTINGS_NAME = "splitSettings";
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods
////////////////////////////////////////////////////////////////////////////////////////////////
func initializeDefaultsIfRequired() {
var defaults = NSUserDefaults.standardUserDefaults();
// by default we want to store everything
if (!defaults.objectForKey(QUALITY_SETTINGS_NAME) ) {
defaults.setBool(true, forKey: QUALITY_SETTINGS_NAME);
defaults.setInteger(1, forKey: FOOD_QUALITY_NAME);
defaults.setInteger(1, forKey: SERVICE_QUALITY_NAME);
}
if (!defaults.boolForKey(SPLIT_SETTINGS_NAME) ) {
defaults.setBool(true, forKey: SPLIT_SETTINGS_NAME);
defaults.setDouble(1.0, forKey: SPLIT_COUNT_NAME);
}
defaults.synchronize();
}
//-------------------------------------------------------------------------------------------------
// Quality settings
func checkAndSaveQualitySettings(food:Int, service:Int) {
var defaults = NSUserDefaults.standardUserDefaults();
if defaults.boolForKey(QUALITY_SETTINGS_NAME) {
defaults.setInteger(food, forKey: FOOD_QUALITY_NAME);
defaults.setInteger(service, forKey: SERVICE_QUALITY_NAME);
defaults.synchronize();
}
}
func shouldSaveQualitySettings() -> Bool {
var defaults = NSUserDefaults.standardUserDefaults();
return defaults.boolForKey(QUALITY_SETTINGS_NAME);
}
func savedFoodQualityValue() -> Int {
var foodQuality = 1;
var defaults = NSUserDefaults.standardUserDefaults();
if defaults.boolForKey(QUALITY_SETTINGS_NAME) {
foodQuality = defaults.integerForKey(FOOD_QUALITY_NAME);
}
return foodQuality;
}
func savedServiceQualityValue() -> Int {
var serviceQuality = 1;
var defaults = NSUserDefaults.standardUserDefaults();
if defaults.boolForKey(QUALITY_SETTINGS_NAME) {
serviceQuality = defaults.integerForKey(SERVICE_QUALITY_NAME);
}
return serviceQuality;
}
func updateQualitySettings(val: Bool) {
NSUserDefaults.standardUserDefaults().setBool(val, forKey: QUALITY_SETTINGS_NAME);
}
//-------------------------------------------------------------------------------------------------
// split settings
func shouldSaveSplitSettings() -> Bool {
var defaults = NSUserDefaults.standardUserDefaults();
return defaults.boolForKey(SPLIT_SETTINGS_NAME);
}
func checkAndSaveSplitSettings(splits:Double) {
var defaults = NSUserDefaults.standardUserDefaults();
if defaults.boolForKey(SPLIT_SETTINGS_NAME) {
defaults.setDouble(splits, forKey: SPLIT_COUNT_NAME);
defaults.synchronize();
}
}
func savedSplitSettings() -> Double {
var splitVal = 1.0;
var defaults = NSUserDefaults.standardUserDefaults();
if defaults.boolForKey(SPLIT_SETTINGS_NAME) {
splitVal = defaults.doubleForKey(SPLIT_COUNT_NAME) ;
}
return splitVal;
}
func updateSplitSettings(val: Bool) {
NSUserDefaults.standardUserDefaults().setBool(val, forKey: SPLIT_SETTINGS_NAME);
}
}
//-------------------------------------------------------------------------------------------------
|
35fccc5bf4558166b954ee7741831806
| 36.418182 | 103 | 0.52661 | false | false | false | false |
firebase/quickstart-ios
|
refs/heads/master
|
authentication/LegacyAuthQuickstart/AuthenticationExampleSwift/PasswordlessViewController.swift
|
apache-2.0
|
1
|
//
// Copyright (c) 2018 Google 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 FirebaseAuth
import UIKit
@objc(PasswordlessViewController)
class PasswordlessViewController: UIViewController {
@IBOutlet var emailField: UITextField!
@IBOutlet var signInButton: UIButton!
var link: String!
override func viewDidLoad() {
super.viewDidLoad()
emailField.text = UserDefaults.standard.value(forKey: "Email") as? String
if let link = UserDefaults.standard.value(forKey: "Link") as? String {
self.link = link
signInButton.isEnabled = true
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
@IBAction func didTapSignInWithEmailLink(_ sender: AnyObject) {
if let email = emailField.text {
showSpinner {
// [START signin_emaillink]
Auth.auth().signIn(withEmail: email, link: self.link) { user, error in
// [START_EXCLUDE]
self.hideSpinner {
if let error = error {
self.showMessagePrompt(error.localizedDescription)
return
}
self.navigationController!.popViewController(animated: true)
}
// [END_EXCLUDE]
}
// [END signin_emaillink]
}
} else {
showMessagePrompt("Email can't be empty")
}
}
@IBAction func didTapSendSignInLink(_ sender: AnyObject) {
if let email = emailField.text {
showSpinner {
// [START action_code_settings]
let actionCodeSettings = ActionCodeSettings()
actionCodeSettings.url = URL(string: "https://www.example.com")
// The sign-in operation has to always be completed in the app.
actionCodeSettings.handleCodeInApp = true
actionCodeSettings.setIOSBundleID(Bundle.main.bundleIdentifier!)
actionCodeSettings.setAndroidPackageName("com.example.android",
installIfNotAvailable: false, minimumVersion: "12")
// [END action_code_settings]
// [START send_signin_link]
Auth.auth().sendSignInLink(toEmail: email,
actionCodeSettings: actionCodeSettings) { error in
// [START_EXCLUDE]
self.hideSpinner {
// [END_EXCLUDE]
if let error = error {
self.showMessagePrompt(error.localizedDescription)
return
}
// The link was successfully sent. Inform the user.
// Save the email locally so you don't need to ask the user for it again
// if they open the link on the same device.
UserDefaults.standard.set(email, forKey: "Email")
self.showMessagePrompt("Check your email for link")
// [START_EXCLUDE]
}
// [END_EXCLUDE]
}
// [END send_signin_link]
}
} else {
showMessagePrompt("Email can't be empty")
}
}
}
|
4bab2dac4f1c598dd714c2196f82d7a4
| 34.663265 | 100 | 0.626037 | false | false | false | false |
ohwutup/ReactiveCocoa
|
refs/heads/master
|
ReactiveCocoa/AppKit/NSButton.swift
|
mit
|
1
|
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 += trigger.observeValues { [unowned base = self.base] in
action.execute(base)
}
return (action, disposable)
}
}
}
}
}
|
05c3fa92fb631cc74f7e2e96cf10344a
| 23.290323 | 103 | 0.687915 | false | false | false | false |
seguemodev/Meducated-Ninja
|
refs/heads/master
|
iOS/Zippy/Medication.swift
|
cc0-1.0
|
1
|
//
// Medication.swift
// Zippy
//
// Created by Geoffrey Bender on 6/19/15.
// Copyright (c) 2015 Segue Technologies, Inc. All rights reserved.
//
import UIKit
class Medication: NSObject, NSCoding
{
// MARK: - Properties
// The name of the medicine cabinet this medication is saved in
var medicineCabinet: String?
// ID and version
var set_id: String?
var document_id: String?
var version: String?
var effective_time: String?
// Abuse and overdosage
var drug_abuse_and_dependence: [String]?
var controlled_substance: [String]?
var abuse: [String]?
var dependence: [String]?
var overdosage: [String]?
// Adverse effects and interactions
var adverse_reactions: [String]?
var drug_interactions: [String]?
var drug_and_or_laboratory_test_interactions: [String]?
// Clinical pharmacology
var clinical_pharmacology: [String]?
var mechanism_of_action: [String]?
var pharmacodynamics: [String]?
var pharmacokinetics: [String]?
// Indications, usage, and dosage
var indications_and_usage: [String]?
var contraindications: [String]?
var dosage_and_administration: [String]?
var dosage_forms_and_strengths: [String]?
var purpose: [String]?
var product_description: [String]?
var active_ingredient: [String]?
var inactive_ingredient: [String]?
var spl_product_data_elements: [String]?
// Patient information
var spl_patient_package_insert: [String]?
var information_for_patients: [String]?
var information_for_owners_or_caregivers: [String]?
var instructions_for_use: [String]?
var ask_doctor: [String]?
var ask_doctor_or_pharmacist: [String]?
var do_not_use: [String]?
var keep_out_of_reach_of_children: [String]?
var other_safety_information: [String]?
var questions: [String]?
var stop_use: [String]?
var when_using: [String]?
var patient_medication_information: [String]?
var spl_medguide: [String]?
// Special Populations
var use_in_specific_populations: [String]?
var pregnancy: [String]?
var teratogenic_effects: [String]?
var nonteratogenic_effects: [String]?
var labor_and_delivery: [String]?
var nursing_mothers: [String]?
var pregnancy_or_breast_feeding: [String]?
var pediatric_use: [String]?
var geriatric_use: [String]?
// Nonclinical toxicology
var nonclinical_toxicology: [String]?
var carcinogenesis_and_mutagenesis_and_impairment_of_fertility: [String]?
var animal_pharmacology_and_or_toxicology: [String]?
// References
var clinical_studies: [String]?
var references: [String]?
// Supply, storage, and handling
var how_supplied: [String]?
var storage_and_handling: [String]?
var safe_handling_warning: [String]?
// Warnings and precautions
var boxed_warning: [String]?
var warnings_and_precautions: [String]?
var user_safety_warnings: [String]?
var precautions: [String]?
var warnings: [String]?
var general_precautions: [String]?
// Other fields
var laboratory_tests: [String]?
var recent_major_changes: [String]?
var microbiology: [String]?
var package_label_principal_display_panel: [String]?
var spl_unclassified_section: [String]?
// Open FDA
var openfda: NSDictionary?
// MARK: - Methods
required init(coder aDecoder: NSCoder)
{
// Saved medicine cabinet
self.medicineCabinet = aDecoder.decodeObjectForKey("medicineCabinet") as? String
// ID and version
self.set_id = aDecoder.decodeObjectForKey("set_id") as? String
self.document_id = aDecoder.decodeObjectForKey("document_id") as? String
self.version = aDecoder.decodeObjectForKey("version") as? String
self.effective_time = aDecoder.decodeObjectForKey("effective_time") as? String
// Abuse and overdosage
self.drug_abuse_and_dependence = aDecoder.decodeObjectForKey("drug_abuse_and_dependence") as? [String]
self.controlled_substance = aDecoder.decodeObjectForKey("controlled_substance") as? [String]
self.abuse = aDecoder.decodeObjectForKey("abuse") as? [String]
self.dependence = aDecoder.decodeObjectForKey("dependence") as? [String]
self.overdosage = aDecoder.decodeObjectForKey("overdosage") as? [String]
// Adverse effects and interactions
self.adverse_reactions = aDecoder.decodeObjectForKey("adverse_reactions") as? [String]
self.drug_interactions = aDecoder.decodeObjectForKey("drug_interactions") as? [String]
self.drug_and_or_laboratory_test_interactions = aDecoder.decodeObjectForKey("drug_and_or_laboratory_test_interactions") as? [String]
// Clinical pharmacology
self.clinical_pharmacology = aDecoder.decodeObjectForKey("clinical_pharmacology") as? [String]
self.mechanism_of_action = aDecoder.decodeObjectForKey("mechanism_of_action") as? [String]
self.pharmacodynamics = aDecoder.decodeObjectForKey("pharmacodynamics") as? [String]
self.pharmacokinetics = aDecoder.decodeObjectForKey("pharmacokinetics") as? [String]
// Indications, usage, and dosage
self.indications_and_usage = aDecoder.decodeObjectForKey("indications_and_usage") as? [String]
self.contraindications = aDecoder.decodeObjectForKey("contraindications") as? [String]
self.dosage_and_administration = aDecoder.decodeObjectForKey("dosage_and_administration") as? [String]
self.dosage_forms_and_strengths = aDecoder.decodeObjectForKey("dosage_forms_and_strengths") as? [String]
self.purpose = aDecoder.decodeObjectForKey("purpose") as? [String]
self.product_description = aDecoder.decodeObjectForKey("product_description") as? [String]
self.active_ingredient = aDecoder.decodeObjectForKey("active_ingredient") as? [String]
self.inactive_ingredient = aDecoder.decodeObjectForKey("inactive_ingredient") as? [String]
self.spl_product_data_elements = aDecoder.decodeObjectForKey("spl_product_data_elements") as? [String]
// Patient information
self.spl_patient_package_insert = aDecoder.decodeObjectForKey("spl_patient_package_insert") as? [String]
self.information_for_patients = aDecoder.decodeObjectForKey("information_for_patients") as? [String]
self.information_for_owners_or_caregivers = aDecoder.decodeObjectForKey("information_for_owners_or_caregivers") as? [String]
self.instructions_for_use = aDecoder.decodeObjectForKey("instructions_for_use") as? [String]
self.ask_doctor = aDecoder.decodeObjectForKey("ask_doctor") as? [String]
self.ask_doctor_or_pharmacist = aDecoder.decodeObjectForKey("ask_doctor_or_pharmacist") as? [String]
self.do_not_use = aDecoder.decodeObjectForKey("do_not_use") as? [String]
self.keep_out_of_reach_of_children = aDecoder.decodeObjectForKey("keep_out_of_reach_of_children") as? [String]
self.other_safety_information = aDecoder.decodeObjectForKey("other_safety_information") as? [String]
self.questions = aDecoder.decodeObjectForKey("questions") as? [String]
self.stop_use = aDecoder.decodeObjectForKey("stop_use") as? [String]
self.when_using = aDecoder.decodeObjectForKey("when_using") as? [String]
self.patient_medication_information = aDecoder.decodeObjectForKey("patient_medication_information") as? [String]
self.spl_medguide = aDecoder.decodeObjectForKey("spl_medguide") as? [String]
// Special Populations
self.use_in_specific_populations = aDecoder.decodeObjectForKey("use_in_specific_populations") as? [String]
self.pregnancy = aDecoder.decodeObjectForKey("pregnancy") as? [String]
self.teratogenic_effects = aDecoder.decodeObjectForKey("teratogenic_effects") as? [String]
self.nonteratogenic_effects = aDecoder.decodeObjectForKey("nonteratogenic_effects") as? [String]
self.labor_and_delivery = aDecoder.decodeObjectForKey("labor_and_delivery") as? [String]
self.nursing_mothers = aDecoder.decodeObjectForKey("nursing_mothers") as? [String]
self.pregnancy_or_breast_feeding = aDecoder.decodeObjectForKey("pregnancy_or_breast_feeding") as? [String]
self.pediatric_use = aDecoder.decodeObjectForKey("pediatric_use") as? [String]
self.geriatric_use = aDecoder.decodeObjectForKey("geriatric_use") as? [String]
// Nonclinical toxicology
self.nonclinical_toxicology = aDecoder.decodeObjectForKey("nonclinical_toxicology") as? [String]
self.carcinogenesis_and_mutagenesis_and_impairment_of_fertility = aDecoder.decodeObjectForKey("carcinogenesis_and_mutagenesis_and_impairment_of_fertility") as? [String]
self.animal_pharmacology_and_or_toxicology = aDecoder.decodeObjectForKey("animal_pharmacology_and_or_toxicology") as? [String]
// References
self.clinical_studies = aDecoder.decodeObjectForKey("clinical_studies") as? [String]
self.references = aDecoder.decodeObjectForKey("references") as? [String]
// Supply, storage, and handling
self.how_supplied = aDecoder.decodeObjectForKey("how_supplied") as? [String]
self.storage_and_handling = aDecoder.decodeObjectForKey("storage_and_handling") as? [String]
self.safe_handling_warning = aDecoder.decodeObjectForKey("safe_handling_warning") as? [String]
// Warnings and precautions
self.boxed_warning = aDecoder.decodeObjectForKey("boxed_warning") as? [String]
self.warnings_and_precautions = aDecoder.decodeObjectForKey("warnings_and_precautions") as? [String]
self.user_safety_warnings = aDecoder.decodeObjectForKey("user_safety_warnings") as? [String]
self.precautions = aDecoder.decodeObjectForKey("precautions") as? [String]
self.warnings = aDecoder.decodeObjectForKey("warnings") as? [String]
self.general_precautions = aDecoder.decodeObjectForKey("general_precautions") as? [String]
// Other fields
self.laboratory_tests = aDecoder.decodeObjectForKey("laboratory_tests") as? [String]
self.recent_major_changes = aDecoder.decodeObjectForKey("recent_major_changes") as? [String]
self.microbiology = aDecoder.decodeObjectForKey("microbiology") as? [String]
self.package_label_principal_display_panel = aDecoder.decodeObjectForKey("package_label_principal_display_panel") as? [String]
self.spl_unclassified_section = aDecoder.decodeObjectForKey("spl_unclassified_section") as? [String]
// OpenFDA
self.openfda = aDecoder.decodeObjectForKey("openfda") as? NSDictionary
}
override init()
{
// Saved medicine cabinet
self.medicineCabinet = ""
// ID and version
self.set_id = ""
self.document_id = ""
self.version = ""
self.effective_time = ""
// Abuse and overdosage
self.drug_abuse_and_dependence = [String]()
self.controlled_substance = [String]()
self.abuse = [String]()
self.dependence = [String]()
self.overdosage = [String]()
// Adverse effects and interactions
self.adverse_reactions = [String]()
self.drug_interactions = [String]()
self.drug_and_or_laboratory_test_interactions = [String]()
// Clinical pharmacology
self.clinical_pharmacology = [String]()
self.mechanism_of_action = [String]()
self.pharmacodynamics = [String]()
self.pharmacokinetics = [String]()
// Indications, usage, and dosage
self.indications_and_usage = [String]()
self.contraindications = [String]()
self.dosage_and_administration = [String]()
self.dosage_forms_and_strengths = [String]()
self.purpose = [String]()
self.product_description = [String]()
self.active_ingredient = [String]()
self.inactive_ingredient = [String]()
self.spl_product_data_elements = [String]()
// Patient information
self.spl_patient_package_insert = [String]()
self.information_for_patients = [String]()
self.information_for_owners_or_caregivers = [String]()
self.instructions_for_use = [String]()
self.ask_doctor = [String]()
self.ask_doctor_or_pharmacist = [String]()
self.do_not_use = [String]()
self.keep_out_of_reach_of_children = [String]()
self.other_safety_information = [String]()
self.questions = [String]()
self.stop_use = [String]()
self.when_using = [String]()
self.patient_medication_information = [String]()
self.spl_medguide = [String]()
// Special Populations
self.use_in_specific_populations = [String]()
self.pregnancy = [String]()
self.teratogenic_effects = [String]()
self.nonteratogenic_effects = [String]()
self.labor_and_delivery = [String]()
self.nursing_mothers = [String]()
self.pregnancy_or_breast_feeding = [String]()
self.pediatric_use = [String]()
self.geriatric_use = [String]()
// Nonclinical toxicology
self.nonclinical_toxicology = [String]()
self.carcinogenesis_and_mutagenesis_and_impairment_of_fertility = [String]()
self.animal_pharmacology_and_or_toxicology = [String]()
// References
self.clinical_studies = [String]()
self.references = [String]()
// Supply, storage, and handling
self.how_supplied = [String]()
self.storage_and_handling = [String]()
self.safe_handling_warning = [String]()
// Warnings and precautions
self.boxed_warning = [String]()
self.warnings_and_precautions = [String]()
self.user_safety_warnings = [String]()
self.precautions = [String]()
self.warnings = [String]()
self.general_precautions = [String]()
// Other fields
self.laboratory_tests = [String]()
self.recent_major_changes = [String]()
self.microbiology = [String]()
self.package_label_principal_display_panel = [String]()
self.spl_unclassified_section = [String]()
// Open FDA
self.openfda = NSDictionary()
super.init()
}
func encodeWithCoder(aCoder: NSCoder)
{
// Saved medicine cabinet
aCoder.encodeObject(self.medicineCabinet, forKey: "medicineCabinet")
// ID and version
aCoder.encodeObject(self.set_id, forKey: "set_id")
aCoder.encodeObject(self.document_id, forKey: "document_id")
aCoder.encodeObject(self.version, forKey: "version")
aCoder.encodeObject(self.effective_time, forKey: "effective_time")
// Abuse and overdosage
aCoder.encodeObject(self.drug_abuse_and_dependence, forKey: "drug_abuse_and_dependence")
aCoder.encodeObject(self.controlled_substance, forKey: "controlled_substance")
aCoder.encodeObject(self.abuse, forKey: "abuse")
aCoder.encodeObject(self.dependence, forKey: "dependence")
aCoder.encodeObject(self.overdosage, forKey: "overdosage")
// Adverse effects and interactions
aCoder.encodeObject(self.adverse_reactions, forKey: "adverse_reactions")
aCoder.encodeObject(self.drug_interactions, forKey: "drug_interactions")
aCoder.encodeObject(self.drug_and_or_laboratory_test_interactions, forKey: "drug_and_or_laboratory_test_interactions")
// Clinical pharmacology
aCoder.encodeObject(self.clinical_pharmacology, forKey: "clinical_pharmacology")
aCoder.encodeObject(self.mechanism_of_action, forKey: "mechanism_of_action")
aCoder.encodeObject(self.pharmacodynamics, forKey: "pharmacodynamics")
aCoder.encodeObject(self.pharmacokinetics, forKey: "pharmacokinetics")
// Indications, usage, and dosage
aCoder.encodeObject(self.indications_and_usage, forKey: "indications_and_usage")
aCoder.encodeObject(self.contraindications, forKey: "contraindications")
aCoder.encodeObject(self.dosage_and_administration, forKey: "dosage_and_administration")
aCoder.encodeObject(self.dosage_forms_and_strengths, forKey: "dosage_forms_and_strengths")
aCoder.encodeObject(self.purpose, forKey: "purpose")
aCoder.encodeObject(self.product_description, forKey: "product_description")
aCoder.encodeObject(self.active_ingredient, forKey: "active_ingredient")
aCoder.encodeObject(self.inactive_ingredient, forKey: "inactive_ingredient")
aCoder.encodeObject(self.spl_product_data_elements, forKey: "spl_product_data_elements")
// Patient information
aCoder.encodeObject(self.spl_patient_package_insert, forKey: "spl_patient_package_insert")
aCoder.encodeObject(self.information_for_patients, forKey: "information_for_patients")
aCoder.encodeObject(self.information_for_owners_or_caregivers, forKey: "information_for_owners_or_caregivers")
aCoder.encodeObject(self.instructions_for_use, forKey: "instructions_for_use")
aCoder.encodeObject(self.ask_doctor, forKey: "ask_doctor")
aCoder.encodeObject(self.ask_doctor_or_pharmacist, forKey: "ask_doctor_or_pharmacist")
aCoder.encodeObject(self.do_not_use, forKey: "do_not_use")
aCoder.encodeObject(self.keep_out_of_reach_of_children, forKey: "keep_out_of_reach_of_children")
aCoder.encodeObject(self.other_safety_information, forKey: "other_safety_information")
aCoder.encodeObject(self.questions, forKey: "questions")
aCoder.encodeObject(self.stop_use, forKey: "stop_use")
aCoder.encodeObject(self.when_using, forKey: "when_using")
aCoder.encodeObject(self.patient_medication_information, forKey: "patient_medication_information")
aCoder.encodeObject(self.spl_medguide, forKey: "spl_medguide")
// Special Populations
aCoder.encodeObject(self.use_in_specific_populations, forKey: "use_in_specific_populations")
aCoder.encodeObject(self.pregnancy, forKey: "pregnancy")
aCoder.encodeObject(self.teratogenic_effects, forKey: "teratogenic_effects")
aCoder.encodeObject(self.nonteratogenic_effects, forKey: "nonteratogenic_effects")
aCoder.encodeObject(self.labor_and_delivery, forKey: "labor_and_delivery")
aCoder.encodeObject(self.nursing_mothers, forKey: "nursing_mothers")
aCoder.encodeObject(self.pregnancy_or_breast_feeding, forKey: "pregnancy_or_breast_feeding")
aCoder.encodeObject(self.pediatric_use, forKey: "pediatric_use")
aCoder.encodeObject(self.geriatric_use, forKey: "geriatric_use")
// Nonclinical toxicology
aCoder.encodeObject(self.nonclinical_toxicology, forKey: "nonclinical_toxicology")
aCoder.encodeObject(self.carcinogenesis_and_mutagenesis_and_impairment_of_fertility, forKey: "carcinogenesis_and_mutagenesis_and_impairment_of_fertility")
aCoder.encodeObject(self.animal_pharmacology_and_or_toxicology, forKey: "animal_pharmacology_and_or_toxicology")
// References
aCoder.encodeObject(self.clinical_studies, forKey: "clinical_studies")
aCoder.encodeObject(self.references, forKey: "references")
// Supply, storage, and handling
aCoder.encodeObject(self.how_supplied, forKey: "how_supplied")
aCoder.encodeObject(self.storage_and_handling, forKey: "storage_and_handling")
aCoder.encodeObject(self.safe_handling_warning, forKey: "safe_handling_warning")
// Warnings and precautions
aCoder.encodeObject(self.boxed_warning, forKey: "boxed_warning")
aCoder.encodeObject(self.warnings_and_precautions, forKey: "warnings_and_precautions")
aCoder.encodeObject(self.user_safety_warnings, forKey: "user_safety_warnings")
aCoder.encodeObject(self.precautions, forKey: "precautions")
aCoder.encodeObject(self.warnings, forKey: "warnings")
aCoder.encodeObject(self.general_precautions, forKey: "general_precautions")
// Other fields
aCoder.encodeObject(self.laboratory_tests, forKey: "laboratory_tests")
aCoder.encodeObject(self.recent_major_changes, forKey: "recent_major_changes")
aCoder.encodeObject(self.microbiology, forKey: "microbiology")
aCoder.encodeObject(self.package_label_principal_display_panel, forKey: "package_label_principal_display_panel")
aCoder.encodeObject(self.spl_unclassified_section, forKey: "spl_unclassified_section")
// Open FDA
aCoder.encodeObject(self.openfda, forKey: "openfda")
}
// Initializes object from JSON dict
init (result: NSDictionary)
{
// If we have a medicine cabinet
self.medicineCabinet = ""
// ID and version
if let set_id = result["set_id"] as? String{
self.set_id = set_id
}
if let document_id = result["document_id"] as? String{
self.document_id = document_id
}
if let version = result["version"] as? String{
self.version = version
}
if let effective_time = result["effective_time"] as? String{
self.effective_time = effective_time
}
// Abuse and overdosage
if let drug_abuse_and_dependence = result["drug_abuse_and_dependence"] as? [String]{
self.drug_abuse_and_dependence = drug_abuse_and_dependence
}
if let controlled_substance = result["controlled_substance"] as? [String]{
self.controlled_substance = controlled_substance
}
if let abuse = result["abuse"] as? [String]{
self.abuse = abuse
}
if let dependence = result["dependence"] as? [String]{
self.dependence = dependence
}
if let overdosage = result["overdosage"] as? [String]{
self.overdosage = overdosage
}
// Adverse effects and interactions
if let adverse_reactions = result["adverse_reactions"] as? [String]{
self.adverse_reactions = adverse_reactions
}
if let drug_interactions = result["drug_interactions"] as? [String]{
self.drug_interactions = drug_interactions
}
if let drug_and_or_laboratory_test_interactions = result["drug_and_or_laboratory_test_interactions"] as? [String]{
self.drug_and_or_laboratory_test_interactions = drug_and_or_laboratory_test_interactions
}
// Clinical pharmacology
if let clinical_pharmacology = result["clinical_pharmacology"] as? [String]{
self.clinical_pharmacology = clinical_pharmacology
}
if let mechanism_of_action = result["mechanism_of_action"] as? [String]{
self.mechanism_of_action = mechanism_of_action
}
if let pharmacodynamics = result["pharmacodynamics"] as? [String]{
self.pharmacodynamics = pharmacodynamics
}
if let pharmacokinetics = result["pharmacokinetics"] as? [String]{
self.pharmacokinetics = pharmacokinetics
}
// Indications, usage, and dosage
if let indications_and_usage = result["indications_and_usage"] as? [String]{
self.indications_and_usage = indications_and_usage
}
if let contraindications = result["contraindications"] as? [String]{
self.contraindications = contraindications
}
if let dosage_and_administration = result["dosage_and_administration"] as? [String]{
self.dosage_and_administration = dosage_and_administration
}
if let dosage_forms_and_strengths = result["dosage_forms_and_strengths"] as? [String]{
self.dosage_forms_and_strengths = dosage_forms_and_strengths
}
if let purpose = result["purpose"] as? [String]{
self.purpose = purpose
}
if let product_description = result["product_description"] as? [String]{
self.product_description = product_description
}
if let active_ingredient = result["active_ingredient"] as? [String]{
self.active_ingredient = active_ingredient
}
if let inactive_ingredient = result["inactive_ingredient"] as? [String]{
self.inactive_ingredient = inactive_ingredient
}
if let spl_product_data_elements = result["spl_product_data_elements"] as? [String]{
self.spl_product_data_elements = spl_product_data_elements
}
// Patient information
if let spl_patient_package_insert = result["spl_patient_package_insert"] as? [String]{
self.spl_patient_package_insert = spl_patient_package_insert
}
if let information_for_patients = result["information_for_patients"] as? [String]{
self.information_for_patients = information_for_patients
}
if let information_for_owners_or_caregivers = result["information_for_owners_or_caregivers"] as? [String]{
self.information_for_owners_or_caregivers = information_for_owners_or_caregivers
}
if let instructions_for_use = result["instructions_for_use"] as? [String]{
self.instructions_for_use = instructions_for_use
}
if let ask_doctor = result["ask_doctor"] as? [String]{
self.ask_doctor = ask_doctor
}
if let ask_doctor_or_pharmacist = result["ask_doctor_or_pharmacist"] as? [String]{
self.ask_doctor_or_pharmacist = ask_doctor_or_pharmacist
}
if let do_not_use = result["do_not_use"] as? [String]{
self.do_not_use = do_not_use
}
if let keep_out_of_reach_of_children = result["keep_out_of_reach_of_children"] as? [String]{
self.keep_out_of_reach_of_children = keep_out_of_reach_of_children
}
if let other_safety_information = result["other_safety_information"] as? [String]{
self.other_safety_information = other_safety_information
}
if let questions = result["questions"] as? [String]{
self.questions = questions
}
if let stop_use = result["stop_use"] as? [String]{
self.stop_use = stop_use
}
if let when_using = result["when_using"] as? [String]{
self.when_using = when_using
}
if let patient_medication_information = result["patient_medication_information"] as? [String]{
self.patient_medication_information = patient_medication_information
}
if let spl_medguide = result["spl_medguide"] as? [String]{
self.spl_medguide = spl_medguide
}
// Special Populations
if let use_in_specific_populations = result["use_in_specific_populations"] as? [String]{
self.use_in_specific_populations = use_in_specific_populations
}
if let pregnancy = result["pregnancy"] as? [String]{
self.pregnancy = pregnancy
}
if let teratogenic_effects = result["teratogenic_effects"] as? [String]{
self.teratogenic_effects = teratogenic_effects
}
if let nonteratogenic_effects = result["nonteratogenic_effects"] as? [String]{
self.nonteratogenic_effects = nonteratogenic_effects
}
if let labor_and_delivery = result["labor_and_delivery"] as? [String]{
self.labor_and_delivery = labor_and_delivery
}
if let nursing_mothers = result["nursing_mothers"] as? [String]{
self.nursing_mothers = nursing_mothers
}
if let pregnancy_or_breast_feeding = result["pregnancy_or_breast_feeding"] as? [String]{
self.pregnancy_or_breast_feeding = pregnancy_or_breast_feeding
}
if let pediatric_use = result["pediatric_use"] as? [String]{
self.pediatric_use = pediatric_use
}
if let geriatric_use = result["geriatric_use"] as? [String]{
self.geriatric_use = geriatric_use
}
// Nonclinical toxicology
if let nonclinical_toxicology = result["nonclinical_toxicology"] as? [String]{
self.nonclinical_toxicology = nonclinical_toxicology
}
if let carcinogenesis_and_mutagenesis_and_impairment_of_fertility = result["carcinogenesis_and_mutagenesis_and_impairment_of_fertility"] as? [String]{
self.carcinogenesis_and_mutagenesis_and_impairment_of_fertility = carcinogenesis_and_mutagenesis_and_impairment_of_fertility
}
if let animal_pharmacology_and_or_toxicology = result["animal_pharmacology_and_or_toxicology"] as? [String]{
self.animal_pharmacology_and_or_toxicology = animal_pharmacology_and_or_toxicology
}
// References
if let clinical_studies = result["clinical_studies"] as? [String]{
self.clinical_studies = clinical_studies
}
if let references = result["references"] as? [String]{
self.references = references
}
// Supply, storage, and handling
if let how_supplied = result["how_supplied"] as? [String]{
self.how_supplied = how_supplied
}
if let storage_and_handling = result["storage_and_handling"] as? [String]{
self.storage_and_handling = storage_and_handling
}
if let safe_handling_warning = result["safe_handling_warning"] as? [String]{
self.safe_handling_warning = safe_handling_warning
}
// Warnings and precautions
if let boxed_warning = result["boxed_warning"] as? [String]{
self.boxed_warning = boxed_warning
}
if let warnings_and_precautions = result["warnings_and_precautions"] as? [String]{
self.warnings_and_precautions = warnings_and_precautions
}
if let user_safety_warnings = result["user_safety_warnings"] as? [String]{
self.user_safety_warnings = user_safety_warnings
}
if let precautions = result["precautions"] as? [String]{
self.precautions = precautions
}
if let warnings = result["warnings"] as? [String]{
self.warnings = warnings
}
if let general_precautions = result["general_precautions"] as? [String]{
self.general_precautions = general_precautions
}
// Other fields
if let laboratory_tests = result["laboratory_tests"] as? [String]{
self.laboratory_tests = laboratory_tests
}
if let recent_major_changes = result["recent_major_changes"] as? [String]{
self.recent_major_changes = recent_major_changes
}
if let microbiology = result["microbiology"] as? [String]{
self.microbiology = microbiology
}
if let package_label_principal_display_panel = result["package_label_principal_display_panel"] as? [String]{
self.package_label_principal_display_panel = package_label_principal_display_panel
}
if let spl_unclassified_section = result["spl_unclassified_section"] as? [String]{
self.spl_unclassified_section = spl_unclassified_section
}
// Open FDA
if let openfda = result["openfda"] as? NSDictionary{
self.openfda = openfda
}
}
// Returns list of properties in original format
func getDefinedProperties() -> [String]
{
var properties = [String]()
// ID and version
// if self.set_id != nil{
// properties.append("set_id")
// }
// if self.document_id != nil{
// properties.append("document_id")
// }
// if self.version != nil{
// properties.append("version")
// }
// if self.effective_time != nil{
// properties.append("effective_time")
// }
// Abuse and overdosage
if self.drug_abuse_and_dependence != nil{
properties.append("drug_abuse_and_dependence")
}
if self.controlled_substance != nil{
properties.append("controlled_substance")
}
if self.abuse != nil{
properties.append("abuse")
}
if self.dependence != nil{
properties.append("dependence")
}
if self.overdosage != nil{
properties.append("overdosage")
}
// Adverse effects and interactions
if self.adverse_reactions != nil{
properties.append("adverse_reactions")
}
if self.drug_interactions != nil{
properties.append("drug_interactions")
}
if self.drug_and_or_laboratory_test_interactions != nil{
properties.append("drug_and_or_laboratory_test_interactions")
}
// Clinical pharmacology
if self.clinical_pharmacology != nil{
properties.append("clinical_pharmacology")
}
if self.mechanism_of_action != nil{
properties.append("mechanism_of_action")
}
if self.pharmacodynamics != nil{
properties.append("pharmacodynamics")
}
if self.pharmacokinetics != nil{
properties.append("pharmacokinetics")
}
// Indications, usage, and dosage
if self.indications_and_usage != nil{
properties.append("indications_and_usage")
}
if self.contraindications != nil{
properties.append("contraindications")
}
if self.dosage_and_administration != nil{
properties.append("dosage_and_administration")
}
if self.dosage_forms_and_strengths != nil{
properties.append("dosage_forms_and_strengths")
}
if self.purpose != nil{
properties.append("purpose")
}
if self.product_description != nil{
properties.append("product_description")
}
if self.active_ingredient != nil{
properties.append("active_ingredient")
}
if self.inactive_ingredient != nil{
properties.append("inactive_ingredient")
}
if self.spl_product_data_elements != nil{
properties.append("spl_product_data_elements")
}
// Patient information
if self.spl_patient_package_insert != nil{
properties.append("spl_patient_package_insert")
}
if self.information_for_patients != nil{
properties.append("information_for_patients")
}
if self.information_for_owners_or_caregivers != nil{
properties.append("information_for_owners_or_caregivers")
}
if self.instructions_for_use != nil{
properties.append("instructions_for_use")
}
if self.ask_doctor != nil{
properties.append("ask_doctor")
}
if self.ask_doctor_or_pharmacist != nil{
properties.append("ask_doctor_or_pharmacist")
}
if self.do_not_use != nil{
properties.append("do_not_use")
}
if self.keep_out_of_reach_of_children != nil{
properties.append("keep_out_of_reach_of_children")
}
if self.other_safety_information != nil{
properties.append("other_safety_information")
}
if self.questions != nil{
properties.append("questions")
}
if self.stop_use != nil{
properties.append("stop_use")
}
if self.when_using != nil{
properties.append("when_using")
}
if self.patient_medication_information != nil{
properties.append("patient_medication_information")
}
if self.spl_medguide != nil{
properties.append("spl_medguide")
}
// Special Populations
if self.use_in_specific_populations != nil{
properties.append("use_in_specific_populations")
}
if self.pregnancy != nil{
properties.append("pregnancy")
}
if self.teratogenic_effects != nil{
properties.append("teratogenic_effects")
}
if self.nonteratogenic_effects != nil{
properties.append("nonteratogenic_effects")
}
if self.labor_and_delivery != nil{
properties.append("labor_and_delivery")
}
if self.nursing_mothers != nil{
properties.append("nursing_mothers")
}
if self.pregnancy_or_breast_feeding != nil{
properties.append("pregnancy_or_breast_feeding")
}
if self.pediatric_use != nil{
properties.append("pediatric_use")
}
if self.geriatric_use != nil{
properties.append("geriatric_use")
}
// Nonclinical toxicology
if self.nonclinical_toxicology != nil{
properties.append("nonclinical_toxicology")
}
if self.carcinogenesis_and_mutagenesis_and_impairment_of_fertility != nil{
properties.append("carcinogenesis_and_mutagenesis_and_impairment_of_fertility")
}
if self.animal_pharmacology_and_or_toxicology != nil{
properties.append("animal_pharmacology_and_or_toxicology")
}
// References
if self.clinical_studies != nil{
properties.append("clinical_studies")
}
if self.references != nil{
properties.append("references")
}
// Supply, storage, and handling
if self.how_supplied != nil{
properties.append("how_supplied")
}
if self.storage_and_handling != nil{
properties.append("storage_and_handling")
}
if self.safe_handling_warning != nil{
properties.append("safe_handling_warning")
}
// Warnings and precautions
if self.boxed_warning != nil{
properties.append("boxed_warning")
}
if self.warnings_and_precautions != nil{
properties.append("warnings_and_precautions")
}
if self.user_safety_warnings != nil{
properties.append("user_safety_warnings")
}
if self.precautions != nil{
properties.append("precautions")
}
if self.warnings != nil{
properties.append("warnings")
}
if self.general_precautions != nil{
properties.append("general_precautions")
}
// Other fields
if self.laboratory_tests != nil{
properties.append("laboratory_tests")
}
if self.recent_major_changes != nil{
properties.append("recent_major_changes")
}
if self.microbiology != nil{
properties.append("microbiology")
}
if self.package_label_principal_display_panel != nil{
properties.append("package_label_principal_display_panel")
}
if self.spl_unclassified_section != nil{
properties.append("spl_unclassified_section")
}
// Open FDA
if self.openfda != nil{
properties.append("openfda")
}
return properties
}
// Returns a list of properties in human readable format
func getPropertyTitles() -> [String]
{
var properties = [String]()
// ID and version
// if self.set_id != nil{
// properties.append("Set ID")
// }
// if self.document_id != nil{
// properties.append("Document ID")
// }
// if self.version != nil{
// properties.append("Version")
// }
// if self.effective_time != nil{
// properties.append("Effective Time")
// }
// Abuse and overdosage
if self.drug_abuse_and_dependence != nil{
properties.append("Drug Abuse and Dependence")
}
if self.controlled_substance != nil{
properties.append("Controlled Substance")
}
if self.abuse != nil{
properties.append("Abuse")
}
if self.dependence != nil{
properties.append("Dependence")
}
if self.overdosage != nil{
properties.append("Overdosage")
}
// Adverse effects and interactions
if self.adverse_reactions != nil{
properties.append("Adverse Reactions")
}
if self.drug_interactions != nil{
properties.append("Drug Interactions")
}
if self.drug_and_or_laboratory_test_interactions != nil{
properties.append("Drug and/or Laboratory Test Interactions")
}
// Clinical pharmacology
if self.clinical_pharmacology != nil{
properties.append("Clinical Pharmacology")
}
if self.mechanism_of_action != nil{
properties.append("Mechanism of Action")
}
if self.pharmacodynamics != nil{
properties.append("Pharmacodynamics")
}
if self.pharmacokinetics != nil{
properties.append("Pharmacokinetics")
}
// Indications, usage, and dosage
if self.indications_and_usage != nil{
properties.append("Indications and Usage")
}
if self.contraindications != nil{
properties.append("Contraindications")
}
if self.dosage_and_administration != nil{
properties.append("Dosage and Administration")
}
if self.dosage_forms_and_strengths != nil{
properties.append("Dosage Forms and Strengths")
}
if self.purpose != nil{
properties.append("Purpose")
}
if self.product_description != nil{
properties.append("Product Description")
}
if self.active_ingredient != nil{
properties.append("Active Ingredient")
}
if self.inactive_ingredient != nil{
properties.append("Inactive Ingredient")
}
if self.spl_product_data_elements != nil{
properties.append("SPL Product Data Elements")
}
// Patient information
if self.spl_patient_package_insert != nil{
properties.append("SPL Patient Package Insert")
}
if self.information_for_patients != nil{
properties.append("Information For Patients")
}
if self.information_for_owners_or_caregivers != nil{
properties.append("Information For Owners or Caregivers")
}
if self.instructions_for_use != nil{
properties.append("Instructions for use")
}
if self.ask_doctor != nil{
properties.append("Ask doctor")
}
if self.ask_doctor_or_pharmacist != nil{
properties.append("Ask doctor or pharmacist")
}
if self.do_not_use != nil{
properties.append("Do not use")
}
if self.keep_out_of_reach_of_children != nil{
properties.append("Keep out of reach of children")
}
if self.other_safety_information != nil{
properties.append("Other safety information")
}
if self.questions != nil{
properties.append("Questions")
}
if self.stop_use != nil{
properties.append("Stop use")
}
if self.when_using != nil{
properties.append("When using")
}
if self.patient_medication_information != nil{
properties.append("Patient medication information")
}
if self.spl_medguide != nil{
properties.append("SPL Medguide")
}
// Special Populations
if self.use_in_specific_populations != nil{
properties.append("Use in specific populations")
}
if self.pregnancy != nil{
properties.append("Pregnancy")
}
if self.teratogenic_effects != nil{
properties.append("Teratogenic Effects")
}
if self.nonteratogenic_effects != nil{
properties.append("Nonteratogenic Effects")
}
if self.labor_and_delivery != nil{
properties.append("Labor and delivery")
}
if self.nursing_mothers != nil{
properties.append("Nursing mothers")
}
if self.pregnancy_or_breast_feeding != nil{
properties.append("Pregnancy or breast feeding")
}
if self.pediatric_use != nil{
properties.append("Pediatric use")
}
if self.geriatric_use != nil{
properties.append("Geriatric use")
}
// Nonclinical toxicology
if self.nonclinical_toxicology != nil{
properties.append("Nonclinical toxicology")
}
if self.carcinogenesis_and_mutagenesis_and_impairment_of_fertility != nil{
properties.append("Carcinogenesis and Mutagenesis and Impairment of Fertility")
}
if self.animal_pharmacology_and_or_toxicology != nil{
properties.append("Animal pharmacology and or toxicology")
}
// References
if self.clinical_studies != nil{
properties.append("Clinical studies")
}
if self.references != nil{
properties.append("References")
}
// Supply, storage, and handling
if self.how_supplied != nil{
properties.append("How supplied")
}
if self.storage_and_handling != nil{
properties.append("Storage and handling")
}
if self.safe_handling_warning != nil{
properties.append("Safe handling warning")
}
// Warnings and precautions
if self.boxed_warning != nil{
properties.append("Boxed warning")
}
if self.warnings_and_precautions != nil{
properties.append("Warnings and precautions")
}
if self.user_safety_warnings != nil{
properties.append("User safety warnings")
}
if self.precautions != nil{
properties.append("Precautions")
}
if self.warnings != nil{
properties.append("Warnings")
}
if self.general_precautions != nil{
properties.append("General precautions")
}
// Other fields
if self.laboratory_tests != nil{
properties.append("Laboratory tests")
}
if self.recent_major_changes != nil{
properties.append("Recent major changes")
}
if self.microbiology != nil{
properties.append("Microbiology")
}
if self.package_label_principal_display_panel != nil{
properties.append("Package label principal display panel")
}
if self.spl_unclassified_section != nil{
properties.append("spl unclassified section")
}
// Open FDA
if self.openfda != nil{
properties.append("Open FDA")
}
return properties
}
}
|
17015927aa3a7c3da47a923fbc9a40b0
| 41.348981 | 176 | 0.618631 | false | false | false | false |
DingSoung/CCExtension
|
refs/heads/main
|
Sources/UIKit/UITableView+UIImage.swift
|
mit
|
2
|
// Created by Songwen Ding on 2017/8/9.
// Copyright © 2017年 DingSoung. All rights reserved.
#if canImport(UIKit)
import UIKit
extension UITableView {
public final var headerImage: UIImage? {
let offset = contentOffset
guard let rect = tableHeaderView?.frame else {return nil}
scrollRectToVisible(rect, animated: false)
let image = tableHeaderView?.image
setContentOffset(offset, animated: false)
return image
}
public final func headerImage(forSection section: Int) -> UIImage? {
let offset = contentOffset
let rect = rectForHeader(inSection: section)
scrollRectToVisible(rect, animated: false)
let image = headerView(forSection: section)?.image
setContentOffset(offset, animated: false)
return image
}
public final func imageForRow(at indexPath: IndexPath) -> UIImage? {
let offset = contentOffset
scrollToRow(at: indexPath, at: UITableView.ScrollPosition.top, animated: false)
let image = cellForRow(at: indexPath)?.image(scale: UIScreen.main.scale)
setContentOffset(offset, animated: false)
return image
}
public final func footerImage(forSection section: Int) -> UIImage? {
let offset = contentOffset
let rect = rectForFooter(inSection: section)
scrollRectToVisible(rect, animated: false)
let image = headerView(forSection: section)?.image
setContentOffset(offset, animated: false)
return image
}
public final var footerImage: UIImage? {
let offset = contentOffset
guard let rect = tableFooterView?.frame else {return nil}
scrollRectToVisible(rect, animated: false)
let image = tableHeaderView?.image
setContentOffset(offset, animated: false)
return image
}
public final func render(context: CGContext,
section: Int,
fromRow start: Int,
to end: Int,
withHeader header: Bool = false,
footer: Bool = false) -> Swift.Void {
context.saveGState()
let offset = contentOffset
if header == true {
let rect = rectForHeader(inSection: section)
scrollRectToVisible(rect, animated: false)
if let view = headerView(forSection: section) {
scrollRectToVisible(view.frame, animated: false)
view.layer.render(in: context)
context.concatenate(CGAffineTransform(translationX: 0, y: rect.size.height))
}
}
for row in start..<end {
let indexPath = IndexPath(row: row, section: section)
scrollToRow(at: indexPath, at: UITableView.ScrollPosition.top, animated: false)
if let cell = cellForRow(at: indexPath) {
cell.layer.render(in: context) // +1.6~1.8MB
context.concatenate(CGAffineTransform(translationX: 0, y: cell.bounds.size.height))
} else {
// draw empty
}
}
if footer == true {
let rect = rectForFooter(inSection: section)
scrollRectToVisible(rect, animated: false)
if let view = footerView(forSection: section) {
scrollRectToVisible(view.frame, animated: false)
view.layer.render(in: context)
context.concatenate(CGAffineTransform(translationX: 0, y: rect.size.height))
}
}
setContentOffset(offset, animated: false)
context.restoreGState()
}
/// ⚠️ hight memory require when lines > 100, get image for one section
public final func imageForSection(at section: Int,
fromRow start: Int,
to end: Int,
totalHeight: CGFloat,
withHeader header: Bool = false,
footer: Bool = false) -> UIImage? {
var height = totalHeight
if header == true {
height += rectForHeader(inSection: section).size.height
}
if footer == true {
height += rectForFooter(inSection: section).size.height
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: contentSize.width, height: height),
false,
UIScreen.main.scale) // +224.25MB
if let context = UIGraphicsGetCurrentContext() {
render(context: context, section: section, fromRow: start, to: end, withHeader: header, footer: footer)
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext(); //-245.3M
return image
}
/// ⚠️ hight memory require when lines > 20, get image from section and all rows in it
public final func imageFromSection(_ start: Int, to end: Int, withHeader header: Bool, footer: Bool) -> UIImage? {
var images: [UIImage] = []
if let herderImage = headerImage, header == true {
images.append(herderImage)
}
for section in start..<end {
let totalHeight = { () -> CGFloat in
var height: CGFloat = 0
let rows = numberOfRows(inSection: section)
for row in 0..<rows {
height += rectForRow(at: IndexPath(row: row, section: section)).size.height
}
return height
}()
if let image = imageForSection(at: section,
fromRow: 0,
to: numberOfRows(inSection: section),
totalHeight: totalHeight,
withHeader: true,
footer: true) {
images.append(image)
if images.count > 5 {
if let image = images.verticalImage {
images.removeAll() //? release memory?
images.append(image)
}
}
}
}
if let image = footerImage, footer == true {
images.append(image)
}
let image = images.verticalImage
images.removeAll()
return image
}
}
#endif
|
dd718463fffd4bcf363f84bf2c48c12e
| 42.972973 | 118 | 0.548709 | false | false | false | false |
PJayRushton/TeacherTools
|
refs/heads/master
|
TeacherTools/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// TeacherTools
//
// Created by Parker Rushton on 10/30/16.
// Copyright © 2016 AppsByPJ. All rights reserved.
//
import UIKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var core = App.core
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
Database.database().isPersistenceEnabled = true
core.fire(command: GetICloudUser())
return true
}
func applicationWillEnterForeground(_ application: UIApplication) {
if core.state.currentUser == nil {
core.fire(command: GetICloudUser())
}
if let mainVC = application.topViewController() as? MainViewController {
mainVC.loadingImageVC.appleImageView.rotate()
}
}
}
|
50b7d18573cf02af2a1da070af1b603d
| 26.257143 | 145 | 0.672956 | false | false | false | false |
AlbertXYZ/HDCP
|
refs/heads/master
|
HDCP/Pods/SnapKit/Source/ConstraintItem.swift
|
mit
|
3
|
//
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
open class ConstraintItem: Equatable {
internal weak var target: AnyObject?
internal let attributes: ConstraintAttributes
internal init(target: AnyObject?, attributes: ConstraintAttributes) {
self.target = target
self.attributes = attributes
}
internal var view: ConstraintView? {
return self.target as? ConstraintView
}
}
public func ==(lhs: ConstraintItem, rhs: ConstraintItem) -> Bool {
// pointer equality
guard lhs !== rhs else {
return true
}
// must both have valid targets and identical attributes
guard let target1 = lhs.target,
let target2 = rhs.target,
target1 === target2 && lhs.attributes == rhs.attributes else {
return false
}
return true
}
|
27831ce188de9407233a05a772a86d7e
| 32.754098 | 81 | 0.696455 | false | false | false | false |
dabing1022/AlgorithmRocks
|
refs/heads/master
|
LeetCodeSwift/Playground/LeetCode.playground/Pages/169 Majority Element.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Previous](@previous)
/*:
# [Majority Element](https://leetcode.com/problems/majority-element/)
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Tags: Divide and Conquer, Array, Bit manipulation
*/
class Solution {
func majorityElement(nums: [Int]) -> Int {
var candidate = nums[0]
var times = 1
for i in 1..<nums.count {
if (times == 0) {
candidate = nums[i]
times = 1
} else {
if (nums[i] == candidate) {
times += 1
} else {
times -= 1
}
}
}
return candidate
}
func majorityElement2(nums: [Int]) -> Int {
var hashMap: Dictionary = Dictionary<Int, Int>()
for i in 0..<nums.count {
if var numberTimes = hashMap[nums[i]] {
numberTimes += 1
hashMap[nums[i]] = numberTimes
} else {
hashMap[nums[i]] = 1
}
if (hashMap[nums[i]] > (nums.count >> 1)) {
return nums[i]
}
}
return 0
}
}
//: [Next](@next)
|
1f1da8f68a2d0a62aa8435ad11fe19d6
| 25.862745 | 126 | 0.480292 | false | false | false | false |
kingcos/Swift-3-Design-Patterns
|
refs/heads/master
|
24-Interpreter_Pattern.playground/Contents.swift
|
apache-2.0
|
1
|
//: Playground - noun: a place where people can play
// Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Design-Patterns
import UIKit
// 演奏内容
struct PlayContext {
var text: String
}
// 表达式
class Expression {
func interpret(_ context: inout PlayContext) {
if context.text.count != 0 {
let rangeA = Range(uncheckedBounds: (context.text.index(after: context.text.startIndex), context.text.index(context.text.startIndex, offsetBy: 2)))
let playKey = String(context.text[rangeA])
let index = context.text.index(context.text.startIndex, offsetBy: 3)
context.text = String(context.text[index...])
let rangeB = Range(uncheckedBounds: (context.text.characters.startIndex, context.text.characters.index(of: " ")!))
let playValue = context.text[rangeB]
context.text = context.text.substring(from: context.text.characters.index(of: " ")!)
execute(playKey, value: Double(playValue)!)
}
}
func execute(_ key: String, value: Double) {}
}
// 音符
class Note: Expression {
override func execute(_ key: String, value: Double) {
var note: String
switch key {
case "C":
note = "1"
case "D":
note = "2"
case "E":
note = "3"
case "F":
note = "4"
case "G":
note = "5"
case "A":
note = "6"
default:
note = ""
}
print("\(note)", separator: "", terminator: " ")
}
}
// 音域
class Scale: Expression {
override func execute(_ key: String, value: Double) {
var scale: String
switch value {
case 1:
scale = "低音"
case 2:
scale = "中音"
case 3:
scale = "高音"
default:
scale = ""
}
print("\(scale)", separator: "", terminator: " ")
}
}
// 音速
class Speed: Expression {
override func execute(_ key: String, value: Double) {
var speed: String
if value >= 1000 {
speed = "高速"
} else if value < 500 {
speed = "低速"
} else {
speed = "中速"
}
print("\(speed)", separator: "", terminator: " ")
}
}
var context = PlayContext(text:
" T 400 O 2 E 0.5 A 3 E 0.5 G 0.5 D 3 E 0.5 G 0.5 A 0.5 O 3 C 1 O 2 A 0.5 G 1 C 0.5 E 0.5 D 3 "
)
while context.text.characters.count > 1 {
let range = Range(uncheckedBounds: (context.text.index(after: context.text.startIndex), context.text.index(context.text.startIndex, offsetBy: 2)))
let str = context.text.substring(with: range)
var expression = Expression()
switch str {
case "T":
expression = Speed()
case "O":
expression = Scale()
case "C", "D", "E", "F", "G", "A", "B", "P":
expression = Note()
default: break
}
expression.interpret(&context)
}
|
f28aa6c8c89e28be205816d5d9d7ee17
| 25.6 | 159 | 0.522066 | false | false | false | false |
LoopKit/LoopKit
|
refs/heads/dev
|
LoopKitUI/Views/CustomOverrideCollectionViewCell.swift
|
mit
|
1
|
//
// CustomOverrideCollectionViewCell.swift
// LoopKitUI
//
// Created by Michael Pangburn on 11/5/19.
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import UIKit
final class CustomOverrideCollectionViewCell: UICollectionViewCell, IdentifiableClass {
@IBOutlet weak var titleLabel: UILabel!
private lazy var overlayDimmerView: UIView = {
let view = UIView()
view.backgroundColor = .systemBackground
view.alpha = 0
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func awakeFromNib() {
super.awakeFromNib()
let selectedBackgroundView = UIView()
self.selectedBackgroundView = selectedBackgroundView
selectedBackgroundView.backgroundColor = .tertiarySystemFill
backgroundColor = .secondarySystemGroupedBackground
layer.cornerCurve = .continuous
layer.cornerRadius = 16
addSubview(overlayDimmerView)
NSLayoutConstraint.activate([
overlayDimmerView.leadingAnchor.constraint(equalTo: leadingAnchor),
overlayDimmerView.trailingAnchor.constraint(equalTo: trailingAnchor),
overlayDimmerView.topAnchor.constraint(equalTo: topAnchor),
overlayDimmerView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
override func prepareForReuse() {
removeOverlay(animated: false)
}
func applyOverlayToFade(animated: Bool) {
if animated {
UIView.animate(withDuration: 0.3, animations: {
self.overlayDimmerView.alpha = 0.5
})
} else {
self.overlayDimmerView.alpha = 0.5
}
}
func removeOverlay(animated: Bool) {
if animated {
UIView.animate(withDuration: 0.3, animations: {
self.overlayDimmerView.alpha = 0
})
} else {
self.overlayDimmerView.alpha = 0
}
}
}
|
0cafc96edbb3600ef13e1253352431b5
| 27.955882 | 87 | 0.64906 | false | false | false | false |
Legoless/Alpha
|
refs/heads/master
|
Demo/UIKitCatalog/GradientMaskView.swift
|
mit
|
1
|
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A `UIView` subclass that is used to mask the contents of a `CollectionViewController`.
*/
import UIKit
class GradientMaskView: UIView {
// MARK: Properties
/// The position in points between which the gradient is drawn.
var maskPosition: (start: CGFloat, end: CGFloat) {
didSet {
updateGradientLayer()
}
}
/// The `CAGradientLayer` responsible for drawing the alpha gradient.
private let gradientLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.colors = [UIColor(white: 0.0, alpha: 0.0).cgColor, UIColor(white: 0.0, alpha: 1.0).cgColor]
return layer
}()
// MARK: Initialization
override init(frame: CGRect) {
maskPosition = (start: 0, end: 0)
super.init(frame: frame)
layer.addSublayer(gradientLayer)
updateGradientLayer()
}
required init?(coder aDecoder: NSCoder) {
maskPosition = (start: 0, end: 0)
super.init(coder: aDecoder)
layer.addSublayer(gradientLayer)
updateGradientLayer()
}
// MARK: UIView
override func layoutSubviews() {
super.layoutSubviews()
updateGradientLayer()
}
// MARK: Convenience
private func updateGradientLayer() {
// Update the `gradientLayer` frame to match the view's bounds.
gradientLayer.frame = CGRect(origin: CGPoint.zero, size: bounds.size)
/*
Update the `gradientLayer`'s gradient locations with the `maskPosition`
converted to the `gradientLayer`'s unit coordinate space.
*/
gradientLayer.locations = [maskPosition.end / bounds.size.height as NSNumber, maskPosition.start / bounds.size.height as NSNumber]
}
}
|
0a09aebcbbac5e8003355019643c38e4
| 27.492754 | 138 | 0.614446 | false | false | false | false |
iHunterX/SocketIODemo
|
refs/heads/master
|
DemoSocketIO/Utils/CustomTextField/iHUnderLineColorTextField.swift
|
gpl-3.0
|
1
|
//
// iHUnderLineColorTextField.swift
// DemoSocketIO
//
// Created by Đinh Xuân Lộc on 10/21/16.
// Copyright © 2016 Loc Dinh Xuan. All rights reserved.
//
import UIKit
@IBDesignable open class iHUnderLineColorTextField: TextFieldEffects {
/**
The color of the border when it has no content.
This property applies a color to the lower edge of the control. The default value for this property is a clear color.
*/
@IBInspectable dynamic open var borderInactiveColor: UIColor? {
didSet {
updateBorder()
}
}
/**
The color of the border when it has content.
This property applies a color to the lower edge of the control. The default value for this property is a clear color.
*/
@IBInspectable dynamic open var borderActiveColor: UIColor? {
didSet {
updateBorder()
}
}
@IBInspectable dynamic open var borderValidColor: UIColor? {
didSet {
updateBorder()
}
}
@IBInspectable dynamic open var borderInvalidColor: UIColor? {
didSet {
updateBorder()
}
}
/**
The color of the placeholder text.
This property applies a color to the complete placeholder string. The default value for this property is a black color.
*/
@IBInspectable dynamic open var placeholderColor: UIColor = .black {
didSet {
updatePlaceholder()
}
}
/**
The scale of the placeholder font.
This property determines the size of the placeholder label relative to the font size of the text field.
*/
@IBInspectable dynamic open var placeholderFontScale: CGFloat = 0.65 {
didSet {
updatePlaceholder()
}
}
override open var placeholder: String? {
didSet {
updatePlaceholder()
}
}
override open var bounds: CGRect {
didSet {
updateBorder()
updatePlaceholder()
}
}
public var validationRuleSet: ValidationRuleSet<String>? = ValidationRuleSet<String>() {
didSet { self.validationRules = validationRuleSet }
}
private let borderThickness: (active: CGFloat, inactive: CGFloat) = (active: 2, inactive: 0.5)
private let placeholderInsets = CGPoint(x: 0, y: 6)
private let textFieldInsets = CGPoint(x: 0, y: 12)
private let inactiveBorderLayer = CALayer()
private let activeBorderLayer = CALayer()
private var activePlaceholderPoint: CGPoint = CGPoint.zero
private let checkbox:M13Checkbox = M13Checkbox()
private var checkBoxHeight:CGFloat = 25
// MARK: - iHunterX's TextField-underline
override open func drawViewsForRect(_ rect: CGRect) {
autoresizesSubviews = true
checkBoxHeight = self.frame.size.height - 20
self.rightViewMode = .always
let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: rect.size.width, height: rect.size.height))
placeholderLabel.frame = frame.insetBy(dx: placeholderInsets.x, dy: placeholderInsets.y)
placeholderLabel.font = placeholderFontFromFont(font!)
setupErrorLabel(rect)
updateBorder()
updatePlaceholder()
layer.addSublayer(inactiveBorderLayer)
layer.addSublayer(activeBorderLayer)
addSubview(placeholderLabel)
}
// iHunter'sTextField
func setupErrorLabel(_ rect: CGRect){
textfieldErrors.textColor = borderInvalidColor
textfieldErrors.lineBreakMode = .byWordWrapping
textfieldErrors.textAlignment = .left
textfieldErrors.font = errorFontFromFont(font!)
textfieldErrors.numberOfLines = 2
let tfwidth = rect.size.width/2
textfieldErrors.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: tfwidth, height: 40))
addSubview(textfieldErrors)
textfieldErrors.translatesAutoresizingMaskIntoConstraints = false
let height = NSLayoutConstraint(item:textfieldErrors, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 20)
let topRightViewTrailing = NSLayoutConstraint(item: textfieldErrors, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal
, toItem: self, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 0)
let topRightViewTopConstraint = NSLayoutConstraint(item: textfieldErrors, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal
, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([height,topRightViewTrailing,topRightViewTopConstraint])
textfieldErrors.translatesAutoresizingMaskIntoConstraints = false
}
func setupCheckBox(_ checkBoxHeight:CGFloat = 25){
rightView = nil
checkbox.isUserInteractionEnabled = false
checkbox.frame = (frame: CGRect(x: 0.0, y: 0.0, width: checkBoxHeight, height: checkBoxHeight))
checkbox.animationDuration = 0.5
checkbox.boxLineWidth = 2
checkbox.checkmarkLineWidth = 2
checkbox.stateChangeAnimation = .spiral
checkbox.tintColor = borderValidColor
rightView = checkbox
}
override open func animateViewsForTextEntry() {
updateBorder()
if text!.isEmpty {
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.0, options: .beginFromCurrentState, animations: ({
self.placeholderLabel.frame.origin = CGPoint(x: 10, y: self.placeholderLabel.frame.origin.y)
self.placeholderLabel.alpha = 0
}), completion: { _ in
self.animationCompletionHandler?(.textEntry)
})
}
else{
updateBorder()
}
layoutPlaceholderInTextRect()
placeholderLabel.frame.origin = activePlaceholderPoint
UIView.animate(withDuration: 0.2, animations: {
self.placeholderLabel.alpha = 0.5
})
activeBorderLayer.frame = rectForBorder(borderThickness.active, isFilled: true)
}
override open func animateViewsForTextDisplay() {
updateBorder()
if text!.isEmpty {
UIView.animate(withDuration: 0.35, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.beginFromCurrentState, animations: ({
self.layoutPlaceholderInTextRect()
self.placeholderLabel.alpha = 1
}), completion: { _ in
self.animationCompletionHandler?(.textDisplay)
})
activeBorderLayer.frame = self.rectForBorder(self.borderThickness.active, isFilled: false)
}else if text == "" {
valid = -1
updateBorder()
}
}
override open func animateForErrorDisplay(isError:Bool, errorMessage:[String]?) {
if isError{
var errorFormatted:String = ""
if errorMessage != nil{
for errorTxt in errorMessage! {
if (errorMessage?.count)! > 1{
errorFormatted.append(errorTxt + "\n")
}else{
errorFormatted = errorTxt
}
}
}
textfieldErrors.text = errorFormatted
UIView.animate(withDuration: 0.9, delay: checkbox.animationDuration, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.beginFromCurrentState, animations: ({
self.textfieldErrors.alpha = 1
}), completion: nil)
} else {
textfieldErrors.text = ""
UIView.animate(withDuration: 0.9, delay: checkbox.animationDuration, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.beginFromCurrentState, animations: ({
self.textfieldErrors.alpha = 0
}), completion: nil)
}
}
// MARK: - Private
override open func updateBorder() {
setupCheckBox(checkBoxHeight)
switch valid {
case 1:
animateForErrorDisplay(isError: false, errorMessage: failureMsgs)
checkbox.isHidden = false
if checkbox.checkState != .checked{
checkbox.toggleCheckState(true,isHidden: false)
}
inactiveBorderLayer.frame = rectForBorder(borderThickness.inactive, isFilled: true)
inactiveBorderLayer.backgroundColor = borderValidColor?.cgColor
activeBorderLayer.frame = rectForBorder(borderThickness.active, isFilled: false)
activeBorderLayer.backgroundColor = borderValidColor?.cgColor
case 0:
if checkbox.checkState == .checked{
checkbox.toggleCheckState(true,isHidden: true)
}
inactiveBorderLayer.frame = rectForBorder(borderThickness.inactive, isFilled: true)
inactiveBorderLayer.backgroundColor = borderInvalidColor?.cgColor
activeBorderLayer.frame = rectForBorder(borderThickness.active, isFilled: false)
activeBorderLayer.backgroundColor = borderInvalidColor?.cgColor
animateForErrorDisplay(isError: true, errorMessage: failureMsgs)
default:
animateForErrorDisplay(isError: false, errorMessage: failureMsgs)
checkbox.isHidden = true
if checkbox.checkState == .checked{
checkbox.toggleCheckState(true)
}
inactiveBorderLayer.frame = rectForBorder(borderThickness.inactive, isFilled: true)
inactiveBorderLayer.backgroundColor = borderInactiveColor?.cgColor
activeBorderLayer.frame = rectForBorder(borderThickness.active, isFilled: false)
activeBorderLayer.backgroundColor = borderActiveColor?.cgColor
}
}
public func updatePlaceholder() {
updateBorder()
placeholderLabel.text = placeholder
placeholderLabel.textColor = placeholderColor
placeholderLabel.sizeToFit()
layoutPlaceholderInTextRect()
if isFirstResponder || text!.isNotEmpty {
animateViewsForTextEntry()
}
}
private func placeholderFontFromFont(_ font: UIFont) -> UIFont! {
let smallerFont = UIFont(name: font.fontName, size: font.pointSize * placeholderFontScale)
return smallerFont
}
private func errorFontFromFont(_ font: UIFont) -> UIFont! {
let smallerFont = UIFont(name: font.fontName, size: font.pointSize * placeholderFontScale)
return smallerFont
}
private func rectForBorder(_ thickness: CGFloat, isFilled: Bool) -> CGRect {
if isFilled {
return CGRect(origin: CGPoint(x: 0, y: frame.height-thickness), size: CGSize(width: frame.width, height: thickness))
} else {
return CGRect(origin: CGPoint(x: 0, y: frame.height-thickness), size: CGSize(width: 0, height: thickness))
}
}
private func layoutPlaceholderInTextRect() {
let textRect = self.textRect(forBounds: bounds)
var originX = textRect.origin.x
switch self.textAlignment {
case .center:
originX += textRect.size.width/2 - placeholderLabel.bounds.width/2
case .right:
originX += textRect.size.width - placeholderLabel.bounds.width
default:
break
}
placeholderLabel.frame = CGRect(x: originX, y: textRect.height/2,
width: placeholderLabel.bounds.width, height: placeholderLabel.bounds.height)
activePlaceholderPoint = CGPoint(x: placeholderLabel.frame.origin.x, y: placeholderLabel.frame.origin.y - placeholderLabel.frame.size.height - placeholderInsets.y)
}
// MARK: - Overrides
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
if checkbox.isHidden{
return bounds.offsetBy(dx: textFieldInsets.x, dy: textFieldInsets.y - 5)
}else{
return CGRect(x: textFieldInsets.x, y: textFieldInsets.y - 5, width: bounds.size.width - checkbox.frame.width, height: bounds.size.height)
}
}
override open func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.offsetBy(dx: textFieldInsets.x, dy: textFieldInsets.y - 5)
}
override open func rightViewRect(forBounds bounds: CGRect) -> CGRect {
let x = bounds.size.width - checkbox.frame.size.width
let y = bounds.offsetBy(dx: textFieldInsets.x, dy: textFieldInsets.y).origin.y
let rightBounds = CGRect(x: x, y: y ,width: checkbox.frame.size.width, height:checkbox.frame.size.height)
return rightBounds
}
//
}
|
15f1485a70bcc4c5042626919561a916
| 39.714286 | 233 | 0.640656 | false | false | false | false |
humeng12/DouYuZB
|
refs/heads/master
|
DouYuZB/DouYuZB/Classes/Main/ViewModel/BaseViewModel.swift
|
mit
|
1
|
//
// BaseViewModel.swift
// DouYuZB
//
// Created by 胡猛 on 2016/12/2.
// Copyright © 2016年 HuMeng. All rights reserved.
//
import UIKit
class BaseViewModel {
lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]()
}
extension BaseViewModel {
func loadAnchorData(isGroupData:Bool,URLString : String,parameters:[String : Any]?=nil,finishedCallBack : @escaping () -> ()){
NetworkTools.requestData(.get, URLString: URLString,parameters: parameters) {(result) in
guard let resultDict = result as? [String : Any] else {return}
guard let dataArray = resultDict["data"] as? [[String : Any]] else {return}
if isGroupData {
for dict in dataArray {
self.anchorGroups.append(AnchorGroup(dict: dict as! [String : NSObject]))
}
} else {
let group = AnchorGroup()
for dict in dataArray {
group.anchors.append(AnchorModel(dict: dict))
}
self.anchorGroups.append(group)
}
finishedCallBack()
}
}
}
|
8c80b8593859c42b7d1884ba27ed56a0
| 26 | 130 | 0.509062 | false | false | false | false |
Jay-Jiang/ABheartServer
|
refs/heads/master
|
Sources/App/Models/Hobby.swift
|
mit
|
1
|
//
// Hobby.swift
// ABheartServer
//
// Created by zimo on 2017/7/11.
//
//
import Vapor
import FluentProvider
// 爱好
final class Hobby: Model {
let storage: Storage = Storage()
static let nameKey = "name"
static let isCustomKey = "is_custom"
let name: String // 爱好
let isCustom: Bool //是否是自定义爱好
var isSelect: Bool = false // 标记这项爱好是否被选中(不被存入数据库,只在被返回客户端时使用)
init(name: String, isCustom: Bool = true) {
self.name = name
self.isCustom = isCustom
}
init(row: Row) throws {
name = try row.get(Hobby.nameKey)
isCustom = try row.get(Hobby.isCustomKey)
}
func makeRow() throws -> Row {
var row = Row()
try row.set(Hobby.nameKey, name)
try row.set(Hobby.isCustomKey, isCustom)
return row
}
}
extension Hobby: Preparation {
static func prepare(_ database: Database) throws {
try database.create(Hobby.self, closure: { (builder) in
builder.id()
builder.string(Hobby.nameKey)
builder.bool(Hobby.isCustomKey)
})
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
extension Hobby: JSONConvertible {
convenience init(json: JSON) throws {
let name: String = try json.get(Hobby.nameKey)
let isCustom: Bool = try json.get(Hobby.isCustomKey)
self.init(name: name, isCustom: isCustom)
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("hobby_name", name)
try json.set("is_custom", "\(isCustom.int)")
try json.set("is_select", "\(isSelect.int)")
return json
}
}
extension Hobby: Equatable {
static func == (lhs: Hobby, rhs: Hobby) -> Bool {
return lhs.id == rhs.id
}
// 获取服务器返回的默认爱好
class func getDefaultHobbies() throws -> [Hobby] {
return try Hobby.makeQuery().filter(Hobby.isCustomKey, false).all()
}
}
|
075b91a5f102fe7078009c4df703ee57
| 23.530864 | 75 | 0.591847 | false | false | false | false |
APUtils/APExtensions
|
refs/heads/master
|
APExtensions/Classes/Core/_Extensions/_UIKit/NSLayoutConstraint.Attribute+Extension.swift
|
mit
|
1
|
//
// NSLayoutConstraint.Attribute+Extension.swift
// APExtensions-example
//
// Created by Anton Plebanovich on 8.11.21.
// Copyright © 2021 Anton Plebanovich. All rights reserved.
//
import UIKit
public extension NSLayoutConstraint.Attribute {
/// Returns `true` if attribute is horizontal.
var isHorizontal: Bool {
self == NSLayoutConstraint.Attribute.left
|| self == NSLayoutConstraint.Attribute.leftMargin
|| self == NSLayoutConstraint.Attribute.right
|| self == NSLayoutConstraint.Attribute.rightMargin
|| self == NSLayoutConstraint.Attribute.leading
|| self == NSLayoutConstraint.Attribute.leadingMargin
|| self == NSLayoutConstraint.Attribute.trailing
|| self == NSLayoutConstraint.Attribute.trailingMargin
|| self == NSLayoutConstraint.Attribute.width
|| self == NSLayoutConstraint.Attribute.centerX
|| self == NSLayoutConstraint.Attribute.centerXWithinMargins
}
/// Returns `true` if attribute is vertical.
var isVertical: Bool {
self == NSLayoutConstraint.Attribute.top
|| self == NSLayoutConstraint.Attribute.topMargin
|| self == NSLayoutConstraint.Attribute.bottom
|| self == NSLayoutConstraint.Attribute.bottomMargin
|| self == NSLayoutConstraint.Attribute.height
|| self == NSLayoutConstraint.Attribute.centerY
|| self == NSLayoutConstraint.Attribute.centerYWithinMargins
}
/// Returns `true` if attribute is to the left side.
var isLeftSide: Bool {
if self == NSLayoutConstraint.Attribute.left || self == NSLayoutConstraint.Attribute.leftMargin {
return true
}
// TODO: Add support for per view layout direction later if needed
if UIApplication.shared.userInterfaceLayoutDirection == UIUserInterfaceLayoutDirection.leftToRight {
return self == NSLayoutConstraint.Attribute.leading || self == NSLayoutConstraint.Attribute.leadingMargin
} else {
return self == NSLayoutConstraint.Attribute.trailing || self == NSLayoutConstraint.Attribute.trailingMargin
}
}
/// Returns `true` if attribute is to the center X.
var isCenterX: Bool {
self == NSLayoutConstraint.Attribute.centerX || self == NSLayoutConstraint.Attribute.centerXWithinMargins
}
/// Returns `true` if attribute is to the right side.
var isRightSide: Bool {
if self == NSLayoutConstraint.Attribute.right || self == NSLayoutConstraint.Attribute.rightMargin {
return true
}
// TODO: Add support for per view layout direction later if needed
if UIApplication.shared.userInterfaceLayoutDirection == UIUserInterfaceLayoutDirection.leftToRight {
return self == NSLayoutConstraint.Attribute.trailing || self == NSLayoutConstraint.Attribute.trailingMargin
} else {
return self == NSLayoutConstraint.Attribute.leading || self == NSLayoutConstraint.Attribute.leadingMargin
}
}
/// Returns `true` if attribute is to the top side.
var isTopSide: Bool {
self == NSLayoutConstraint.Attribute.top || self == NSLayoutConstraint.Attribute.topMargin
}
/// Returns `true` if attribute is to the center Y.
var isCenterY: Bool {
self == NSLayoutConstraint.Attribute.centerY || self == NSLayoutConstraint.Attribute.centerYWithinMargins
}
/// Returns `true` if attribute is to the bottom side.
var isBottomSide: Bool {
self == NSLayoutConstraint.Attribute.bottom || self == NSLayoutConstraint.Attribute.bottomMargin
}
}
|
eea129d77e3c2b2f15ffa437eb011427
| 41.732558 | 119 | 0.680272 | false | false | false | false |
ontouchstart/swift3-playground
|
refs/heads/playgroundbook
|
single/🍎🍌🍒.playgroundbook/Contents/Chapters/🍎🍌🍒.playgroundchapter/Pages/🍎🍌🍒.playgroundpage/LiveView.swift
|
mit
|
1
|
import UIKit
import PlaygroundSupport
let frame = CGRect(x: 0, y:0, width: 400, height: 300)
let label = UILabel(frame: frame)
label.text = "🍎🍌🍒"
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 60)
PlaygroundPage.current.liveView = label
|
81708d33ab949a215928d3d0f1ff59eb
| 25.5 | 54 | 0.74717 | false | false | false | false |
jhaigler94/cs4720-iOS
|
refs/heads/master
|
Pensieve/Pensieve/TypesTableViewController.swift
|
apache-2.0
|
1
|
//
// TypesTableViewController.swift
// Feed Me
//
/*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
protocol TypesTableViewControllerDelegate: class {
func typesController(controller: TypesTableViewController, didSelectTypes types: [String])
}
class TypesTableViewController: UITableViewController {
let possibleTypesDictionary = ["bakery":"Bakery", "bar":"Bar", "cafe":"Cafe", "grocery_or_supermarket":"Supermarket", "restaurant":"Restaurant"]
var selectedTypes: [String]!
weak var delegate: TypesTableViewControllerDelegate!
var sortedKeys: [String] {
return possibleTypesDictionary.keys.sort()
}
// MARK: - Actions
@IBAction func donePressed(sender: AnyObject) {
delegate?.typesController(self, didSelectTypes: selectedTypes)
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return possibleTypesDictionary.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TypeCell", forIndexPath: indexPath)
let key = sortedKeys[indexPath.row]
let type = possibleTypesDictionary[key]!
cell.textLabel?.text = type
cell.imageView?.image = UIImage(named: key)
cell.accessoryType = (selectedTypes!).contains(key) ? .Checkmark : .None
return cell
}
// MARK: - Table view delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let key = sortedKeys[indexPath.row]
if (selectedTypes!).contains(key) {
selectedTypes = selectedTypes.filter({$0 != key})
} else {
selectedTypes.append(key)
}
tableView.reloadData()
}
}
|
06df60ecc76fda57c6cc80d2945ac4c2
| 38.351351 | 146 | 0.748283 | false | false | false | false |
yesidi/EYFlatKit
|
refs/heads/master
|
demo/EYFlatKit/Consts/EYFlatColorConstant.swift
|
mit
|
1
|
//
// EYFlatColorConstant.swift
// EYFlatKit
//
// Created by ye on 15/8/7.
// Copyright (c) 2015年 eddieyip. All rights reserved.
//
import Foundation
enum EYFlatColorType:String {
case turquoise = "#1ABC9C"
case greenSea = "#16A085"
case emerald = "#2ECC71"
case nephritis = "#27AE60"
case peterRiver = "#3498DB"
case belizeHole = "#2980B9"
case amethyst = "#9B59B6"
case wisteria = "#8E44AD"
case wetAsphalt = "#34495E"
case midnight_blue = "#2C3E50"
case sunFlower = "#F1C40F"
case orange = "#F39C12"
case carrot = "#E67E22"
case pumpkin = "#D35400"
case alizarin = "#E74C3C"
case pomegranate = "#C0392B"
case clouds = "#ECF0F1"
case silver = "#BDC3C7"
case concrete = "#95A5A6"
case asbestos = "#7F8C8D"
}
|
2235953a076b4fcf7cdb5ea9bbf72707
| 19.512195 | 54 | 0.590963 | false | false | false | false |
vakoc/particle-swift
|
refs/heads/master
|
Sources/ParticleCloud.swift
|
apache-2.0
|
1
|
// This source file is part of the vakoc.com open source project(s)
//
// Copyright © 2016, 2017 Mark Vakoc. All rights reserved.
// Licensed under Apache License v2.0
//
// See http://www.vakoc.com/LICENSE.txt for license information
import Foundation
import Dispatch
///
///
/// ParticleCloud methods are not generally stateful. Beyond authentication, which itself is stateful
/// only in that it stores credentials thorugh the secure storage delegate, does not
///
public class ParticleCloud: WebServiceCallable {
/// The base for the particle URLs
public static let defaultURL = URL(string: "https://api.particle.io/")!
/// The base URL used to interact with particle. Set during initialization
public let baseURL: URL
/// The OAuth realm
public var realm = ParticleSwiftInfo.realm
/// the networking stack used for this particle instance
public lazy var urlSession: URLSession = {
let configuration = URLSessionConfiguration.default
let urlSession = URLSession(configuration: configuration)
return urlSession
}()
/// the dispatch queue used to perform all opeartions for this cloud instance
public var dispatchQueue = DispatchQueue(label: "Particle", attributes: [.concurrent])
/// provider for secure credentials
public private(set) weak var secureStorage: SecureStorage?
/// The json decoder to use when interacting with Particle web services
public static var decoder: JSONDecoder = {
let ret = JSONDecoder()
let dateFormatter = DateFormatter()
// swift .iso8601 doesn't allow for milliseconds
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
ret.dateDecodingStrategy = .formatted(dateFormatter)
return ret
}()
/// The json encoder to use when interacting with Particle web services
public static var encoder: JSONEncoder = {
let ret = JSONEncoder()
let dateFormatter = DateFormatter()
// swift .iso8601 doesn't allow for milliseconds
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
ret.dateEncodingStrategy = .formatted(dateFormatter)
return ret
}()
/// Create a new instance of the particle cloud interface
///
/// Refer to https://docs.particle.io/guide/how-to-build-a-product/authentication/ for more information
/// about the OAuth related bits
/// https://docs.particle.io/reference/api/
///
/// - parameter baseURL: the base url to use, defaults to kParticleDefaultURL
/// - parameter secureStorage: provider of credentials
public init(baseURL:URL = defaultURL, secureStorage: SecureStorage?) {
self.baseURL = baseURL
self.secureStorage = secureStorage
}
/// Asynchronously lists the access tokens associated with the account
///
/// This mmethod will invoke authenticate with validateToken = false. Any authentication error will be returned
/// - parameter completion: completion handler. Contains a list of oauth tokens
public func accessTokens(_ completion: @escaping (Result<[OAuthTokenListEntry]>) -> Void ) {
var request = URLRequest(url: baseURL.appendingPathComponent("v1/access_tokens"))
guard let username = self.secureStorage?.username(self.realm), let password = self.secureStorage?.password(self.realm) else {
self.dispatchQueue.async {
completion(.failure(ParticleError.missingCredentials))
}
return
}
guard let data = "\(username):\(password)".data(using: String.Encoding.utf8) else {
return dispatchQueue.async { completion(.failure(ParticleError.missingCredentials)) }
}
let base64AuthCredentials = data.base64EncodedString(options: [])
request.setValue("Basic \(base64AuthCredentials)", forHTTPHeaderField: "Authorization")
let task = urlSession.dataTask(with: request, completionHandler: { (data, response, error) in
trace( "Get access tokens", request: request, data: data, response: response, error: error )
if let error = self.checkForInvalidToken(request: request, response: response, data: data) {
return completion(.failure(error))
}
if let error = error {
return completion(.failure(ParticleError.listAccessTokensFailed(error)))
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [[String : Any]], let j = json {
return completion(.success(j.compactMap() { return OAuthTokenListEntry(dictionary: $0)} ))
} else {
return completion(.failure(ParticleError.listAccessTokensFailed(ParticleError.httpResponseParseFailed(nil))))
}
})
task.resume()
}
/// Validates the returned resposne did not identify an invalid token
///
/// If an invalid token is discovered by virtue of the response being a 401 code and the
/// returned result containing "invalid_token" the secure storage delegate is instructed to
/// remove any persisted token. Subsequent requests may result in a new token being obtained
/// without any further use of the new invalid token
/// - Parameters:
/// - request: The request that initiated the service call
/// - response: The response received, if any
/// - data: The body of the response, if any
/// - Returns: An error indicating the problem, or nil if the token was O
func checkForInvalidToken(request: URLRequest, response: URLResponse?, data: Data?) -> Error? {
if let response = response as? HTTPURLResponse, response.statusCode == 401, let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any], let j = json, j["error"] as? String == "invalid_token" {
warn("The request \(request) detected an invalid token. The stored token will no longer be used.")
secureStorage?.updateOAuthToken(nil, forRealm: ParticleSwiftInfo.realm)
return ParticleError.invalidToken
}
return nil
}
}
extension ParticleCloud: OAuthAuthenticatable {
}
extension ParticleCloud: CustomStringConvertible {
public var description: String {
return "\(String(describing: secureStorage?.username)) -- \(String(describing: secureStorage?.oauthClientId))"
}
}
|
54defb7e8f828e080ec64ae9f85b280c
| 43.642384 | 249 | 0.662661 | false | false | false | false |
whitepaperclip/Exsilio-iOS
|
refs/heads/master
|
Exsilio/TabControlsView.swift
|
mit
|
1
|
//
// TabControlsView.swift
// Exsilio
//
// Created by Nick Kezhaya on 6/27/16.
//
//
import UIKit
import FontAwesome_swift
enum TabState {
case tourPreview
case activeTour
}
protocol TabControlsDelegate {
func willChangeTabState(_ state: TabState)
func willMoveToNextStep()
func willMoveToPreviousStep()
func willDisplayWaypointInfo()
}
class TabControlsView: UIStackView {
// Tour preview state
let takeTourButton = UIButton()
// Active tour state
let cancelButton = UIButton()
let backButton = UIButton()
let forwardButton = UIButton()
let infoButton = UIButton()
var delegate: TabControlsDelegate?
override func awakeFromNib() {
super.awakeFromNib()
self.takeTourButton.backgroundColor = UI.GreenColor
self.takeTourButton.setImage(UI.ForwardIcon, for: UIControlState())
self.takeTourButton.addTarget(self, action: #selector(takeTourButtonTapped), for: .touchUpInside)
self.cancelButton.backgroundColor = UIColor.white
self.cancelButton.setImage(UI.XIcon.imageWithTint(UI.RedColor), for: UIControlState())
self.cancelButton.addTarget(self, action: #selector(cancelButtonTapped), for: .touchUpInside)
// Disable the back button for the first load
self.backButton.isEnabled = false
self.backButton.backgroundColor = UIColor.white
self.backButton.setImage(UI.BackIcon.imageWithTint(UI.BarButtonColor), for: UIControlState())
self.backButton.setImage(UI.BackIcon.imageWithTint(UI.BarButtonColorDisabled), for: .disabled)
self.backButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
self.forwardButton.backgroundColor = UIColor.white
self.forwardButton.setImage(UI.ForwardIcon.imageWithTint(UI.BarButtonColor), for: UIControlState())
self.forwardButton.setImage(UI.ForwardIcon.imageWithTint(UI.BarButtonColorDisabled), for: .disabled)
self.forwardButton.addTarget(self, action: #selector(forwardButtonTapped), for: .touchUpInside)
let infoImage = UIImage.fontAwesomeIcon(name: .mapMarker, textColor: UI.BlueColor, size: UI.BarButtonSize)
self.infoButton.backgroundColor = UIColor.white
self.infoButton.setImage(infoImage.imageWithTint(UI.BarButtonColor), for: .normal)
self.infoButton.addTarget(self, action: #selector(infoButtonTapped), for: .touchUpInside)
self.setState(.tourPreview)
}
func setState(_ state: TabState) {
self.arrangedSubviews.forEach { $0.removeFromSuperview() }
if state == .tourPreview {
self.addArrangedSubview(self.takeTourButton)
} else if state == .activeTour {
self.addArrangedSubview(self.cancelButton)
self.addArrangedSubview(self.backButton)
self.addArrangedSubview(self.forwardButton)
self.addArrangedSubview(self.infoButton)
}
}
func takeTourButtonTapped() {
self.setState(.activeTour)
self.delegate?.willChangeTabState(.activeTour)
}
func cancelButtonTapped() {
self.setState(.tourPreview)
self.delegate?.willChangeTabState(.tourPreview)
}
func backButtonTapped() {
self.delegate?.willMoveToPreviousStep()
}
func forwardButtonTapped() {
self.delegate?.willMoveToNextStep()
}
func infoButtonTapped() {
self.delegate?.willDisplayWaypointInfo()
}
func updateStepIndex(_ index: Int, outOf: Int) {
self.backButton.isEnabled = true
self.forwardButton.isEnabled = true
if index == 0 {
self.backButton.isEnabled = false
}
if index + 1 >= outOf {
self.forwardButton.isEnabled = false
}
}
}
|
e1063287e26b323374a2cb6193d0b285
| 32.192982 | 114 | 0.690011 | false | false | false | false |
TalntsApp/media-picker-ios
|
refs/heads/master
|
MediaPicker/Extra/AssetsFetcher.swift
|
mit
|
1
|
import Photos
import Signals
// MARK: Assets
struct AssetsSection: Equatable {
let name: String?
let assets: [PHAsset]
}
func ==(lhs: AssetsSection, rhs: AssetsSection) -> Bool {
return lhs.name == rhs.name && lhs.assets == rhs.assets
}
func getAssets(photosOnly: Bool) -> Signal<AssetsSection> {
let signal:Signal<AssetsSection> = Signal()
let options = PHFetchOptions()
options.includeHiddenAssets = false
options.includeAllBurstAssets = false
let photoStreamResult = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumUserLibrary, options: options)
let favoritesResult = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumFavorites, options: options)
let videoResult = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumVideos, options: options)
let albumResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: options)
[photoStreamResult, favoritesResult, videoResult, albumResult].forEach { result in
result.forEach {
if let assetCollection = $0 as? PHAssetCollection {
let assets = enumerateAssets(assetCollection, photosOnly: photosOnly)
if assets.count > 0 {
async(.Main) {
if result == photoStreamResult {
signal.fire(AssetsSection(name: assetCollection.localizedTitle, assets: assets.sort({ $0.modificationDate > $1.modificationDate })))
}
else {
signal.fire(AssetsSection(name: assetCollection.localizedTitle, assets: assets))
}
}
}
}
}
}
return signal
}
private func enumerateAssets(assetCollection: PHAssetCollection, photosOnly: Bool) -> [PHAsset] {
let allowedTypes: Set<PHAssetMediaType>
if photosOnly {
allowedTypes = [.Image]
}
else {
allowedTypes = [.Image, .Video]
}
let assetsResult = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: nil)
let assets: [PHAsset] = assetsResult.map({ $0 as! PHAsset }).filter({ allowedTypes.contains($0.mediaType) })
return assets
}
extension NSDate: Comparable {}
/**
Compares time intervals since `reference date` of two dates.
- returns: `true` if first one is closer to `reference date`, otherwise `false`
*/
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate
}
/**
Compares time intervals since `reference date` of two dates.
- returns: `true` if second one is closer to `reference date`, otherwise `false`
*/
public func >(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate
}
extension PHFetchResult: CollectionType {
/**
Conformity to `SequenceType` protocol
- returns: `PHFetchResult` objects generator
*/
public func generate() -> PHFetchResultGenerator {
return Generator(fetchResult: self)
}
/// Index of first object in `PHFetchResult`
public var startIndex: Int {
return 0
}
/// Index of last object in `PHFetchResult`
public var endIndex: Int {
return self.count
}
public subscript (bounds: Range<Int>) -> [AnyObject] {
let range = NSMakeRange(bounds.startIndex, bounds.count)
let indexSet = NSIndexSet(indexesInRange: range)
return self.objectsAtIndexes(indexSet)
}
}
/// `PHFetchResult` objects generator
public struct PHFetchResultGenerator: GeneratorType {
private let fetchResult: PHFetchResult
init(fetchResult: PHFetchResult) {
self.fetchResult = fetchResult
self.currentIndex = fetchResult.startIndex
}
private var currentIndex: Int
/**
`GeneratorType` method
- returns: Next object from `PHFetchResult`
*/
public mutating func next() -> AnyObject? {
if currentIndex < fetchResult.endIndex {
let object = fetchResult[currentIndex]
currentIndex++
return object
}
else {
return nil
}
}
}
extension PHAsset {
private var scale: CGFloat {
let scale = UIScreen.screens().reduce(1.0, combine: { (maxScale, screen) -> CGFloat in
let scale = screen.scale
return max(maxScale, scale)
})
return scale
}
func talntsThumbnail(size: CGSize, deliveryMode: PHImageRequestOptionsDeliveryMode = .Opportunistic, adjustScale: Bool = true) -> Signal<UIImage?> {
let signal: Signal<UIImage?> = Signal()
let options = PHImageRequestOptions()
options.deliveryMode = deliveryMode
options.resizeMode = .Fast
options.synchronous = false
let adjustedSize: CGSize
if adjustScale {
adjustedSize = CGSize(width: size.width * scale, height: size.height * scale)
}
else {
adjustedSize = size
}
PHImageManager.defaultManager().requestImageForAsset(
self,
targetSize: adjustedSize,
contentMode: PHImageContentMode.AspectFill,
options: options
) { (image, info) -> Void in
signal.fire(image)
}
return signal
}
var talntsImage: Signal<UIImage?> {
let size = CGSize(width: CGFloat(self.pixelWidth), height: CGFloat(self.pixelHeight))
return self.talntsThumbnail(size, deliveryMode: .HighQualityFormat, adjustScale: false)
}
var urlAsset: Signal<AVURLAsset?> {
let signal: Signal<AVURLAsset?> = Signal()
let options = PHVideoRequestOptions()
options.deliveryMode = .HighQualityFormat
PHImageManager.defaultManager().requestAVAssetForVideo(
self, options:
options
) { (asset, mix, info) -> Void in
if let asset = asset as? AVURLAsset {
signal.fire(asset)
}
}
return signal
}
}
|
a1564b87072be6a2e2d95e9bb4863c63
| 31.269036 | 160 | 0.622404 | false | false | false | false |
RxSwiftCommunity/RxWebKit
|
refs/heads/master
|
Example/AuthChallengeViewController.swift
|
mit
|
1
|
//
// AuthChallengeViewController.swift
// Example
//
// Created by Bob Obi on 25.10.17.
// Copyright © 2017 RxSwift Community. All rights reserved.
//
import UIKit
import WebKit
import RxWebKit
import RxSwift
import RxCocoa
class AuthChallengeViewController: UIViewController {
let bag = DisposeBag()
let wkWebView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(wkWebView)
wkWebView.load(URLRequest(url: URL(string: "https://jigsaw.w3.org/HTTP/Basic/")!))
wkWebView.rx
.didReceiveChallenge
.debug("didReceiveChallenge")
.subscribe(onNext: {(webView, challenge, handler) in
guard challenge.previousFailureCount == 0 else {
handler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
return
}
/*
The correct credentials are:
user = guest
password = guest
You might want to start with the invalid credentials to get a sense of how this code works
*/
let credential = URLCredential(user: "bad-user", password: "bad-password", persistence: URLCredential.Persistence.forSession)
challenge.sender?.use(credential, for: challenge)
handler(URLSession.AuthChallengeDisposition.useCredential, credential)
})
.disposed(by: bag)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let originY = UIApplication.shared.statusBarFrame.maxY
wkWebView.frame = CGRect(x: 0, y: originY, width: view.bounds.width, height: view.bounds.height)
}
}
|
f1742bf93b4be7a517b9f7b0c070c5f9
| 32.574074 | 141 | 0.605626 | false | false | false | false |
kysonyangs/ysbilibili
|
refs/heads/master
|
ysbilibili/Classes/Player/NormalPlayer/Controller/Detail/View/ZHNplayerPageListTableViewCell.swift
|
mit
|
1
|
//
// ZHNplayerPageListTableViewCell.swift
// zhnbilibili
//
// Created by 张辉男 on 16/12/30.
// Copyright © 2016年 zhn. All rights reserved.
//
import UIKit
fileprivate let kpageCellKey = "kpageCellKey"
class ZHNplayerPageListTableViewCell: YSBaseLineCell {
/// 点击的事件
var pageSelectedAction: ((_ cid: Int,_ index: Int)->Void)?
/// page的数据数组
var pagesArray: [YSPageDetailModel]? {
didSet{
if let count = pagesArray?.count {
numberLabel.text = "(\(count))"
}
contentCollectionView.reloadData()
}
}
/// 当前选择的cell
var selectedIndex: Int = 0
// MARK - 懒加载的控件
fileprivate lazy var noticeLabel: UILabel = {
let noticeLabel = UILabel()
noticeLabel.text = "分集"
noticeLabel.font = UIFont.systemFont(ofSize: 15)
return noticeLabel
}()
lazy var numberLabel: UILabel = {
let numberLabel = UILabel()
numberLabel.textColor = UIColor.lightGray
numberLabel.font = UIFont.systemFont(ofSize: 14)
return numberLabel
}()
lazy var contentCollectionView: UICollectionView = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.minimumInteritemSpacing = 20
flowLayout.itemSize = CGSize(width: kScreenWidth/3, height: 60)
flowLayout.scrollDirection = .horizontal
let contentCollectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: flowLayout)
contentCollectionView.delegate = self
contentCollectionView.dataSource = self
contentCollectionView.register(pageCell.self, forCellWithReuseIdentifier: kpageCellKey)
contentCollectionView.backgroundColor = kHomeBackColor
contentCollectionView.contentInset = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 30)
return contentCollectionView
}()
// MARK - life cycle
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.addSubview(noticeLabel)
self.addSubview(numberLabel)
self.addSubview(contentCollectionView)
self.backgroundColor = kHomeBackColor
self.selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
noticeLabel.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(10)
make.top.equalTo(self).offset(5)
}
numberLabel.snp.makeConstraints { (make) in
make.centerY.equalTo(noticeLabel)
make.left.equalTo(noticeLabel.snp.right).offset(5)
}
contentCollectionView.snp.makeConstraints { (make) in
make.top.equalTo(noticeLabel.snp.bottom).offset(10)
make.left.right.equalTo(self)
make.bottom.equalTo(self).offset(-5)
}
}
class func instanceCell(tableView: UITableView) -> ZHNplayerPageListTableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "pagelist")
if cell == nil {
cell = ZHNplayerPageListTableViewCell(style: .default, reuseIdentifier: "pagelist")
}
return cell as! ZHNplayerPageListTableViewCell
}
}
//======================================================================
// MARK:- 数据源
//======================================================================
extension ZHNplayerPageListTableViewCell: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let count = pagesArray?.count else {return 0}
return count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kpageCellKey, for: indexPath) as! pageCell
let page = pagesArray?[indexPath.row]
cell.contentLabel.text = page?.part
if indexPath.row == selectedIndex {
cell.selectedCell()
}else {
cell.normalCell()
}
return cell
}
}
//======================================================================
// MARK:- 代理方法
//======================================================================
extension ZHNplayerPageListTableViewCell: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndex = indexPath.row
collectionView.reloadData()
let model = pagesArray?[indexPath.row]
guard let cid = model?.cid else {return}
pageSelectedAction!(cid,indexPath.row+1)
}
}
//======================================================================
// MARK:- 自定义cell
//======================================================================
class pageCell: UICollectionViewCell {
lazy var contentLabel: UILabel = {
let contentLabel = UILabel()
contentLabel.font = UIFont.systemFont(ofSize: 13)
contentLabel.numberOfLines = 0
return contentLabel
}()
// MARK - life cycle
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(contentLabel)
self.layer.borderWidth = 1
self.layer.borderColor = UIColor.lightGray.cgColor
self.layer.cornerRadius = 10
self.backgroundColor = UIColor.white
self.layer.masksToBounds = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
contentLabel.snp.makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10))
}
}
// MARK - 公共的方法
func normalCell() {
contentLabel.textColor = UIColor.black
self.layer.borderColor = UIColor.lightGray.cgColor
}
func selectedCell() {
contentLabel.textColor = kNavBarColor
self.layer.borderColor = kNavBarColor.cgColor
}
}
|
2830329ba6d10dfa049bb62f8e88a350
| 34.337017 | 134 | 0.608818 | false | false | false | false |
HabitRPG/habitrpg-ios
|
refs/heads/develop
|
HabitRPG/Views/ChallengeFilterAlert.swift
|
gpl-3.0
|
1
|
//
// ChallengeFilterAlert.swift
// Habitica
//
// Created by Phillip Thelen on 15/03/2017.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import Foundation
import PopupDialog
import Habitica_Models
import ReactiveSwift
protocol ChallengeFilterChangedDelegate: class {
func challengeFilterChanged(showOwned: Bool, showNotOwned: Bool, shownGuilds: [String])
}
class ChallengeFilterAlert: UIViewController, Themeable {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var topSeparator: UIView!
@IBOutlet weak var middleSeparator: UIView!
@IBOutlet weak var groupsTitleLabel: UILabel!
@IBOutlet weak var ownershipTitleLabel: UILabel!
@IBOutlet weak private var doneButton: UIButton!
@IBOutlet weak private var allGroupsButton: UIButton!
@IBOutlet weak private var noGroupsButton: UIButton!
@IBOutlet weak private var groupListView: UIStackView!
@IBOutlet weak private var ownedButton: LabeledCheckboxView!
@IBOutlet weak private var notOwnedButton: LabeledCheckboxView!
@IBOutlet weak private var heightConstraint: NSLayoutConstraint!
weak var delegate: ChallengeFilterChangedDelegate?
private let socialRepository = SocialRepository()
private let disposable = ScopedDisposable(CompositeDisposable())
var showOwned = true
var showNotOwned = true
var shownGuilds = [String]()
var initShownGuilds = false
var groups = [GroupProtocol]()
init() {
super.init(nibName: "ChallengeFilterAlert", bundle: nil)
}
func applyTheme(theme: Theme) {
view.backgroundColor = theme.contentBackgroundColor
titleLabel.textColor = theme.primaryTextColor
topSeparator.backgroundColor = theme.separatorColor
middleSeparator.backgroundColor = theme.separatorColor
groupsTitleLabel.textColor = theme.ternaryTextColor
ownershipTitleLabel.textColor = theme.ternaryTextColor
doneButton.setTitleColor(theme.tintColor, for: .normal)
allGroupsButton.setTitleColor(theme.tintColor, for: .normal)
noGroupsButton.setTitleColor(theme.tintColor, for: .normal)
ownedButton.tintColor = theme.tintColor
ownedButton.textColor = theme.primaryTextColor
notOwnedButton.tintColor = theme.tintColor
notOwnedButton.textColor = theme.primaryTextColor
groupListView.arrangedSubviews.forEach { (view) in
if let checkview = view as? LabeledCheckboxView {
checkview.tintColor = theme.tintColor
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
groupListView.axis = .vertical
groupListView.spacing = 12
ownedButton.isChecked = showOwned
notOwnedButton.isChecked = showNotOwned
ownedButton.checkedAction = {[weak self] isChecked in
self?.showOwned = isChecked
self?.updateDelegate()
}
notOwnedButton.checkedAction = {[weak self] isChecked in
self?.showNotOwned = isChecked
self?.updateDelegate()
}
disposable.inner.add(socialRepository.getChallengesDistinctGroups().on(value: {[weak self]challenges in
self?.set(challenges: challenges.value)
}).start())
ThemeService.shared.addThemeable(themable: self)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let window = self.view.window {
self.heightConstraint.constant = window.frame.size.height - 200
}
}
@IBAction func doneTapped(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func allGroupsTapped(_ sender: Any) {
shownGuilds.removeAll()
for group in groups {
shownGuilds.append(group.id ?? "")
}
if let subviews = groupListView.arrangedSubviews as? [LabeledCheckboxView] {
for view in subviews {
view.isChecked = true
}
}
updateDelegate()
}
@IBAction func noGroupsTapped(_ sender: Any) {
shownGuilds.removeAll()
if let subviews = groupListView.arrangedSubviews as? [LabeledCheckboxView] {
for view in subviews {
view.isChecked = false
}
}
updateDelegate()
}
private func updateDelegate() {
delegate?.challengeFilterChanged(showOwned: self.ownedButton.isChecked, showNotOwned: self.notOwnedButton.isChecked, shownGuilds: shownGuilds)
}
private func set(challenges: [ChallengeProtocol]) {
for challenge in challenges {
guard let groupID = challenge.groupID else {
return
}
let groupView = LabeledCheckboxView(frame: CGRect.zero)
groupView.text = challenge.groupName
if initShownGuilds {
shownGuilds.append(groupID)
}
groupView.isChecked = shownGuilds.contains(groupID)
groupView.numberOfLines = 0
groupView.textColor = ThemeService.shared.theme.secondaryTextColor
groupView.tintColor = ThemeService.shared.theme.tintColor
groupView.checkedAction = { [weak self] isChecked in
if isChecked {
self?.shownGuilds.append(groupID)
} else {
if let index = self?.shownGuilds.firstIndex(of: groupID) {
self?.shownGuilds.remove(at: index)
}
}
self?.updateDelegate()
}
groupListView.addArrangedSubview(groupView)
}
}
}
|
fe96790b5448bce65b0354032a1323f1
| 34.527607 | 150 | 0.651183 | false | false | false | false |
ewhitley/CDAKit
|
refs/heads/master
|
CDAKit/health-data-standards/lib/models/reference.swift
|
mit
|
1
|
//
// reference.swift
// CDAKit
//
// Created by Eric Whitley on 11/30/15.
// Copyright © 2015 Eric Whitley. All rights reserved.
//
import Foundation
/**
CDA Reference
*/
public class CDAKReference: CDAKJSONInstantiable {
// MARK: CDA properties
///type
public var type: String?
///referenced type
public var referenced_type: String = ""
///reference
public var referenced_id: String = ""
///Entry
public var entry: CDAKEntry?
public init(entry: CDAKEntry) {
self.entry = entry
}
public init(type: String?, referenced_type: String, referenced_id: String?, entry: CDAKEntry? = nil ) {
self.type = type
self.referenced_type = referenced_type
if let referenced_id = referenced_id {
self.referenced_id = referenced_id
} else {
self.referenced_id = ""
}
self.entry = entry
}
// MARK: - Deprecated - Do not use
///Do not use - will be removed. Was used in HDS Ruby.
required public init(event: [String:Any?]) {
initFromEventList(event)
}
///Do not use - will be removed. Was used in HDS Ruby.
private func initFromEventList(event: [String:Any?]) {
for (key, value) in event {
CDAKUtility.setProperty(self, property: key, value: value)
}
}
// MARK: Health-Data-Standards Functions
internal func resolve_reference() -> CDAKEntry? {
var an_entry: CDAKEntry?
if let entry = self.entry {
if let record = entry.record {
an_entry = (record.entries.filter({ e in
String(e.dynamicType) == referenced_type &&
e.identifier_as_string == referenced_id
})).first
}
}
return an_entry
}
internal func resolve_referenced_id() {
if let entry = self.entry {
if let record = entry.record {
let resolved_reference = (record.entries.filter({ e in
String(e.dynamicType) == referenced_type &&
e.identifier_as_string == referenced_id
})).first
if let resolved_reference = resolved_reference {
self.referenced_id = resolved_reference.id == nil ? "" : (resolved_reference.id)!
}
}
}
}
}
extension CDAKReference: CDAKJSONExportable {
// MARK: - JSON Generation
///Dictionary for JSON data
public var jsonDict: [String: AnyObject] {
var dict: [String: AnyObject] = [:]
if let type = type {
dict["type"] = type
}
dict["referenced_type"] = referenced_type
dict["referenced_id"] = referenced_id
if let entry = entry {
dict["entry"] = entry.jsonDict
}
return dict
}
}
|
72e3b6ed856d732a6089a323de8cc4b4
| 23.40566 | 105 | 0.616783 | false | false | false | false |
chengxianghe/MissGe
|
refs/heads/master
|
MissGe/MissGe/Class/Project/Request/Square/MLPostTopicRequest.swift
|
mit
|
1
|
//
// MLPostTopicRequest.swift
// MissLi
//
// Created by chengxianghe on 16/7/20.
// Copyright © 2016年 cn. All rights reserved.
//
import UIKit
//http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=post&a=addpost&token=X%2FZTO4eBrq%2FnmgZSoqA9eshEbpWRSs7%2B%2BkqAtMZAf5mvzTo&fid=3&detail=有工程师给看看么?这是怎么了?&title=有工程师给看看么?这&anonymous=0&ids=25339,25340
class MLPostTopicRequest: MLBaseRequest {
var anonymous = 0
var detail = ""
var ids:[String]?
//c=post&a=addpost&token=X%2FZTO4eBrq%2FnmgZSoqA9eshEbpWRSs7%2B%2BkqAtMZAf5mvzTo&fid=3&detail=有工程师给看看么?这是怎么了?&title=有工程师给看看么?这&anonymous=0&ids=25339,25340
override func requestParameters() -> [String : Any]? {
let title: String = detail.length > 10 ? (detail as NSString).substring(to: 10) : detail;
var dict: [String : String] = ["c":"post","a":"addpost","token":MLNetConfig.shareInstance.token,"detail":"\(detail)","anonymous":"\(anonymous)", "title":title, "fid":"3"]
if ids != nil && ids!.count > 0 {
dict["ids"] = ids!.joined(separator: ",")
}
return dict
}
override func requestHandleResult() {
print("requestHandleResult -- \(self.classForCoder)")
}
override func requestVerifyResult() -> Bool {
guard let dict = self.responseObject as? NSDictionary else {
return false
}
return (dict["result"] as? String) == "200"
}
}
/*
传图
POST http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=upload&a=postUpload&token=X%252FZTO4eBrq%252FnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5mvzTo
body 带图
返回
{"result":"200","msg":"\u56fe\u50cf\u4e0a\u4f20\u6210\u529f","content":{"image_name":"uploadImg_0.png","url":"http:\/\/img.gexiaojie.com\/post\/2016\/0718\/160718100723P003873V86.png","image_id":25339}}
*/
//class MLUploadImageRequest: MLBaseRequest {
//
// var fileURL: NSURL!
// var fileBodyblock: AFConstructingBlock!
// var uploadProgress: AFProgressBlock = { (progress: NSProgress) in
// print("uploadProgressBlock:" + progress.localizedDescription)
// }
//
//
// override func requestMethod() -> TURequestMethod {
// return TURequestMethod.Post
// }
//
// //c=upload&a=postUpload&token=X%252FZTO4eBrq%252FnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5mvzTo
//
// override func requestUrl() -> String {
// return "c=upload&a=postUpload&token=\(MLNetConfig.shareInstance.token)"
// }
//
// override func requestHandleResult() {
// print("requestHandleResult -- \(self.classForCoder)")
// }
//
// override func requestVerifyResult() -> Bool {
// return (self.responseObject?["result"] as? String) == "200"
// }
//
//}
|
f8b37be2438537e18963df116a1cf61e
| 35.620253 | 285 | 0.663671 | false | false | false | false |
abertelrud/swift-package-manager
|
refs/heads/main
|
Sources/PackageCollections/Storage/PackageCollectionsSourcesStorage.swift
|
apache-2.0
|
2
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2020-2021 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
//
//===----------------------------------------------------------------------===//
public protocol PackageCollectionsSourcesStorage {
/// Lists all `PackageCollectionSource`s.
///
/// - Parameters:
/// - callback: The closure to invoke when result becomes available
func list(callback: @escaping (Result<[PackageCollectionsModel.CollectionSource], Error>) -> Void)
/// Adds the given source.
///
/// - Parameters:
/// - source: The `PackageCollectionSource` to add
/// - order: Optional. The order that the source should take after being added.
/// By default the new source is appended to the end (i.e., the least relevant order).
/// - callback: The closure to invoke when result becomes available
func add(source: PackageCollectionsModel.CollectionSource,
order: Int?,
callback: @escaping (Result<Void, Error>) -> Void)
/// Removes the given source.
///
/// - Parameters:
/// - source: The `PackageCollectionSource` to remove
/// - profile: The `Profile` to remove source
/// - callback: The closure to invoke when result becomes available
func remove(source: PackageCollectionsModel.CollectionSource,
callback: @escaping (Result<Void, Error>) -> Void)
/// Moves source to a different order.
///
/// - Parameters:
/// - source: The `PackageCollectionSource` to move
/// - order: The order that the source should take.
/// - callback: The closure to invoke when result becomes available
func move(source: PackageCollectionsModel.CollectionSource,
to order: Int,
callback: @escaping (Result<Void, Error>) -> Void)
/// Checks if a source has already been added.
///
/// - Parameters:
/// - source: The `PackageCollectionSource`
/// - callback: The closure to invoke when result becomes available
func exists(source: PackageCollectionsModel.CollectionSource,
callback: @escaping (Result<Bool, Error>) -> Void)
/// Updates the given source.
///
/// - Parameters:
/// - source: The `PackageCollectionSource` to update
/// - callback: The closure to invoke when result becomes available
func update(source: PackageCollectionsModel.CollectionSource,
callback: @escaping (Result<Void, Error>) -> Void)
}
|
1b152e6a231fcc6968168a600790255b
| 42.523077 | 102 | 0.61824 | false | false | false | false |
nodes-ios/NStackSDK
|
refs/heads/master
|
NStackSDK/NStackSDK/Classes/Other/UIButton+NStackLocalizable.swift
|
mit
|
1
|
//
// UIButton+NStackLocalizable.swift
// NStackSDK
//
// Created by Nicolai Harbo on 30/07/2019.
// Copyright © 2019 Nodes ApS. All rights reserved.
//
import Foundation
import UIKit
extension UIButton: NStackLocalizable {
private static var _backgroundColor = [String: UIColor?]()
private static var _userInteractionEnabled = [String: Bool]()
private static var _translationIdentifier = [String: TranslationIdentifier]()
@objc public func localize(for stringIdentifier: String) {
guard let identifier = SectionKeyHelper.transform(stringIdentifier) else { return }
NStack.sharedInstance.translationsManager?.localize(component: self, for: identifier)
}
@objc public func setLocalizedValue(_ localizedValue: String) {
setTitle(localizedValue, for: .normal)
}
public var translatableValue: String? {
get {
return titleLabel?.text
}
set {
titleLabel?.text = newValue
}
}
public var translationIdentifier: TranslationIdentifier? {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UIButton._translationIdentifier[tmpAddress]
}
set {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UIButton._translationIdentifier[tmpAddress] = newValue
}
}
public var originalBackgroundColor: UIColor? {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UIButton._backgroundColor[tmpAddress] ?? .clear
}
set {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UIButton._backgroundColor[tmpAddress] = newValue
}
}
public var originalIsUserInteractionEnabled: Bool {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UIButton._userInteractionEnabled[tmpAddress] ?? false
}
set {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UIButton._userInteractionEnabled[tmpAddress] = newValue
}
}
public var backgroundViewToColor: UIView? {
return titleLabel
}
}
|
4f1a9cc440976ac2f3bf3ed51e4eb570
| 30.821918 | 93 | 0.632372 | false | false | false | false |
ThumbWorks/i-meditated
|
refs/heads/master
|
Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/ObserveOnSerialDispatchQueue.swift
|
mit
|
6
|
//
// ObserveOnSerialDispatchQueue.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/31/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if TRACE_RESOURCES
/**
Counts number of `SerialDispatchQueueObservables`.
Purposed for unit tests.
*/
public var numberOfSerialDispatchQueueObservables: AtomicInt = 0
#endif
class ObserveOnSerialDispatchQueueSink<O: ObserverType> : ObserverBase<O.E> {
let scheduler: SerialDispatchQueueScheduler
let observer: O
let subscription = SingleAssignmentDisposable()
var cachedScheduleLambda: ((ObserveOnSerialDispatchQueueSink<O>, Event<E>) -> Disposable)!
init(scheduler: SerialDispatchQueueScheduler, observer: O) {
self.scheduler = scheduler
self.observer = observer
super.init()
cachedScheduleLambda = { sink, event in
sink.observer.on(event)
if event.isStopEvent {
sink.dispose()
}
return Disposables.create()
}
}
override func onCore(_ event: Event<E>) {
let _ = self.scheduler.schedule((self, event), action: cachedScheduleLambda)
}
override func dispose() {
super.dispose()
subscription.dispose()
}
}
class ObserveOnSerialDispatchQueue<E> : Producer<E> {
let scheduler: SerialDispatchQueueScheduler
let source: Observable<E>
init(source: Observable<E>, scheduler: SerialDispatchQueueScheduler) {
self.scheduler = scheduler
self.source = source
#if TRACE_RESOURCES
let _ = AtomicIncrement(&resourceCount)
let _ = AtomicIncrement(&numberOfSerialDispatchQueueObservables)
#endif
}
override func run<O : ObserverType>(_ observer: O) -> Disposable where O.E == E {
let sink = ObserveOnSerialDispatchQueueSink(scheduler: scheduler, observer: observer)
sink.subscription.disposable = source.subscribe(sink)
return sink
}
#if TRACE_RESOURCES
deinit {
let _ = AtomicDecrement(&resourceCount)
let _ = AtomicDecrement(&numberOfSerialDispatchQueueObservables)
}
#endif
}
|
e5a0407a16f78ab34adcb19551e46435
| 25.703704 | 94 | 0.668516 | false | false | false | false |
GraphQLSwift/GraphQL
|
refs/heads/main
|
Sources/GraphQL/Instrumentation/DispatchQueueInstrumentationWrapper.swift
|
mit
|
1
|
import Dispatch
import NIO
/// Proxies calls through to another `Instrumentation` instance via a DispatchQueue
///
/// Has two primary use cases:
/// 1. Allows a non thread safe Instrumentation implementation to be used along side a multithreaded execution strategy
/// 2. Allows slow or heavy instrumentation processing to happen outside of the current query execution
public class DispatchQueueInstrumentationWrapper: Instrumentation {
let instrumentation: Instrumentation
let dispatchQueue: DispatchQueue
let dispatchGroup: DispatchGroup?
public init(
_ instrumentation: Instrumentation,
label: String = "GraphQL instrumentation wrapper",
qos: DispatchQoS = .utility,
attributes: DispatchQueue.Attributes = [],
dispatchGroup: DispatchGroup? = nil
) {
self.instrumentation = instrumentation
dispatchQueue = DispatchQueue(label: label, qos: qos, attributes: attributes)
self.dispatchGroup = dispatchGroup
}
public init(
_ instrumentation: Instrumentation,
dispatchQueue: DispatchQueue,
dispatchGroup: DispatchGroup? = nil
) {
self.instrumentation = instrumentation
self.dispatchQueue = dispatchQueue
self.dispatchGroup = dispatchGroup
}
public var now: DispatchTime {
return instrumentation.now
}
public func queryParsing(
processId: Int,
threadId: Int,
started: DispatchTime,
finished: DispatchTime,
source: Source,
result: Result<Document, GraphQLError>
) {
dispatchQueue.async(group: dispatchGroup) {
self.instrumentation.queryParsing(
processId: processId,
threadId: threadId,
started: started,
finished: finished,
source: source,
result: result
)
}
}
public func queryValidation(
processId: Int,
threadId: Int,
started: DispatchTime,
finished: DispatchTime,
schema: GraphQLSchema,
document: Document,
errors: [GraphQLError]
) {
dispatchQueue.async(group: dispatchGroup) {
self.instrumentation.queryValidation(
processId: processId,
threadId: threadId,
started: started,
finished: finished,
schema: schema,
document: document,
errors: errors
)
}
}
public func operationExecution(
processId: Int,
threadId: Int,
started: DispatchTime,
finished: DispatchTime,
schema: GraphQLSchema,
document: Document,
rootValue: Any,
eventLoopGroup: EventLoopGroup,
variableValues: [String: Map],
operation: OperationDefinition?,
errors: [GraphQLError],
result: Map
) {
dispatchQueue.async(group: dispatchGroup) {
self.instrumentation.operationExecution(
processId: processId,
threadId: threadId,
started: started,
finished: finished,
schema: schema,
document: document,
rootValue: rootValue,
eventLoopGroup: eventLoopGroup,
variableValues: variableValues,
operation: operation,
errors: errors,
result: result
)
}
}
public func fieldResolution(
processId: Int,
threadId: Int,
started: DispatchTime,
finished: DispatchTime,
source: Any,
args: Map,
eventLoopGroup: EventLoopGroup,
info: GraphQLResolveInfo,
result: Result<Future<Any?>, Error>
) {
dispatchQueue.async(group: dispatchGroup) {
self.instrumentation.fieldResolution(
processId: processId,
threadId: threadId,
started: started,
finished: finished,
source: source,
args: args,
eventLoopGroup: eventLoopGroup,
info: info,
result: result
)
}
}
}
|
4d5fc8a224e5f6213f944b5d8a650637
| 29.834532 | 119 | 0.577228 | false | false | false | false |
cjcaufield/SecretKit
|
refs/heads/master
|
SecretKit/ios/SGCellData.swift
|
mit
|
1
|
//
// SGRowData.swift
// TermKit
//
// Created by Colin Caufield on 2016-01-13.
// Copyright © 2016 Secret Geometry. All rights reserved.
//
import Foundation
public let BASIC_CELL_ID = "BasicCell"
public let LABEL_CELL_ID = "LabelCell"
public let TEXT_FIELD_CELL_ID = "TextFieldCell"
public let SWITCH_CELL_ID = "SwitchCell"
public let SLIDER_CELL_ID = "SliderCell"
public let TIME_LABEL_CELL_ID = "TimeLabelCell"
public let TIME_PICKER_CELL_ID = "TimePickerCell"
public let PICKER_LABEL_CELL_ID = "PickerLabelCell"
public let PICKER_CELL_ID = "PickerCell"
public let DATE_LABEL_CELL_ID = "DateLabelCell"
public let DATE_PICKER_CELL_ID = "DatePickerCell"
public let SEGMENTED_CELL_ID = "SegmentedCell"
public let TEXT_VIEW_CELL_ID = "TextViewCell"
public let COLOR_CELL_ID = "ColorCell"
public let OTHER_CELL_ID = "OtherCell"
public enum SGRowDataTargetType {
case ViewController
case Object
}
public class SGRowData: Equatable {
public var cellIdentifier: String
public var title: String
public var modelPath: String?
public var targetType: SGRowDataTargetType
public var action: Selector?
public var segueName: String?
public var checked: Bool?
public var range: NSRange
public var expandable = false
public var hidden = false
public init(cellIdentifier: String = OTHER_CELL_ID,
title: String = "",
modelPath: String? = nil,
targetType: SGRowDataTargetType = .Object,
action: Selector? = nil,
segueName: String? = nil,
checked: Bool? = nil,
range: NSRange = NSMakeRange(0, 1),
expandable: Bool = false,
hidden: Bool = false) {
self.cellIdentifier = cellIdentifier
self.title = title
self.modelPath = modelPath
self.targetType = targetType
self.action = action
self.segueName = segueName
self.checked = checked
self.range = range
self.expandable = expandable
self.hidden = hidden
}
}
public func ==(a: SGRowData, b: SGRowData) -> Bool {
return ObjectIdentifier(a) == ObjectIdentifier(b)
}
public class SGSliderRowData : SGRowData {
/*
public init(title: String = "",
targetType: SGRowDataTargetType = .Object,
modelPath: String? = nil,
range: NSRange = NSMakeRange(0, 1)) {
super.init(cellIdentifier: SLIDER_CELL_ID,
title: title,
targetType: targetType,
modelPath: modelPath)
self.range = range
}
*/
}
public class SGSectionData {
public var rows = [SGRowData]()
public var title = ""
public init(_ rows: SGRowData..., title: String = "") {
self.rows = rows
}
}
public class SGTableData {
public var sections = [SGSectionData]()
public init() {
// nothing
}
public init(_ sections: SGSectionData...) {
self.sections = sections
}
}
|
7a729dedaba0cf88725eb70e179a02af
| 27.196429 | 59 | 0.60133 | false | false | false | false |
zakkhoyt/ColorPicKit
|
refs/heads/1.2.3
|
ColorPicKit/Classes/HSBWheelView.swift
|
mit
|
1
|
//
// HSBWheelView.swift
// ColorPicKitExample
//
// Created by Zakk Hoyt on 10/8/16.
// Copyright © 2016 Zakk Hoyt. All rights reserved.
//
import UIKit
class HSBWheelView: WheelView {
override func rgbaFor(point: CGPoint) -> RGBA {
let center = CGPoint(x: radius, y: radius)
let angle = atan2(point.x - center.x, point.y - center.y) + CGFloat.pi
let dist = pointDistance(point, CGPoint(x: center.x, y: center.y))
var hue = angle / (CGFloat.pi * 2.0)
hue = min(hue, 1.0 - 0.0000001)
hue = max(hue, 0.0)
var sat = dist / radius
sat = min(sat, 1.0)
sat = max(sat, 0.0)
let rgba = UIColor.hsbaToRGBA(hsba: HSBA(hue: hue, saturation: sat, brightness: brightness))
return rgba
}
}
|
dee20895c5d00bce67440e7e803f08a3
| 26.586207 | 100 | 0.5825 | false | false | false | false |
itechline/bonodom_new
|
refs/heads/master
|
SlideMenuControllerSwift/MenuItemView.swift
|
mit
|
1
|
//
// MenuItemViewController.swift
// Bonodom
//
// Created by Attila Dán on 2016. 06. 06..
// Copyright © 2016. Itechline. All rights reserved.
//
import UIKit
/*struct MenuItemViewCellData {
init(imageUrl_menu: String, text_menu: String) {
self.imageUrl_menu = imageUrl_menu
self.text_menu = text_menu
}
var imageUrl_menu: String
var text_menu: String
}*/
struct MenuItemViewCellData2{
init(imagePath_menu: UIImage, text_menu: String, messages: Int, appointment: Int){
self.imagePath_menu = imagePath_menu
self.text_menu = text_menu
self.messages = messages
self.appointment = appointment
}
var imagePath_menu: UIImage
var text_menu: String
var messages: Int
var appointment: Int
}
class MenuItemView: BaseMenuItemViewController {
@IBOutlet weak var dataImage: UIImageView!
@IBOutlet weak var dataText: UILabel!
@IBOutlet weak var messages_text: UILabel!
override func awakeFromNib() {
self.dataText?.font = UIFont.boldSystemFontOfSize(16)
self.dataText?.textColor = UIColor(hex: "000000")
}
override class func height() -> CGFloat {
return 60
}
/*override func setData(data: Any?) {
if let data = data as? MenuItemViewCellData {
self.dataImage.setRandomDownloadImage(50, height: 50)
self.dataText.text = data.text_menu
}
}*/
override func setData(data: Any?){
if let data = data as? MenuItemViewCellData2{
self.dataImage.image = data.imagePath_menu
self.dataText.text = data.text_menu
if (data.messages != 0) {
self.messages_text.hidden = false
self.messages_text.text = String(data.messages)
} else {
self.messages_text.hidden = true
}
if (data.appointment != 0) {
self.messages_text.hidden = false
self.messages_text.text = String(data.appointment)
} else {
self.messages_text.hidden = true
}
if (data.messages != 0) {
self.messages_text.hidden = false
}
}
}
}
|
30ea507d00e2515dca2e266413e7557f
| 27.833333 | 86 | 0.590929 | false | false | false | false |
AngelLandoni/MVVM-R
|
refs/heads/master
|
MVVMR/Application/Login/LoginController.swift
|
gpl-3.0
|
1
|
//
// LoginController.swift
// MVVMR
//
// Created by Angel Landoni on 2/6/17.
// Copyright © 2017 Angel Landoni. All rights reserved.
//
import Foundation
// MARK: Delegate
// This protocol sent the signal to the view.
@objc protocol LoginControllerDelegate: class {
optional func loginSuccess()
optional func loginFail()
}
// MARK: Controller.
final class LoginController<TypeDelegate : LoginControllerDelegate> {
var router : LoginRouter? = nil
weak var delegate : TypeDelegate? = nil
init() { }
init(withDelegate customDelegate: TypeDelegate) {
delegate = customDelegate
}
}
// MARK: Public methods.
extension LoginController {
// This method logins the user into the app.
func performLogin(withName name: String, andPassword password: String) {
// Keep in memory the delegate with a strong ref.
guard let strongDelegate = delegate else { return }
// If the data is incorrect extecute the login fail callback.
// It should be loaded from a persistence storage.
guard name == "name" && password == "password" else {
strongDelegate.loginFail?()
return
}
guard let strongRouter = router else { return }
// Redirect to the correct view.
strongRouter.moveToApp()
// If the login is correct it should show the
// correct view controller using the
// TODO: implement router.
strongDelegate.loginSuccess?()
}
func showTermsAndConditions() {
// Keep in memory the delegate with a strong ref.
guard let strongRouter = router else { fatalError("LoginController router is null.") }
strongRouter.moveTermsAndConditions()
}
}
|
986eac5ef07a5ed8320cb6929fb835aa
| 28.266667 | 94 | 0.654131 | false | false | false | false |
silence0201/Swift-Study
|
refs/heads/master
|
Learn/19.Foundation/NSDate/NSCalendar、Calendar、NSDateComponents和DateComponents.playground/Contents.swift
|
mit
|
1
|
import Foundation
//创建NSDateComponents对象
let comps = NSDateComponents()
//设置开幕式时间是2020-8-5
//设置NSDateComponents中的日期
comps.day = 5
//设置NSDateComponents中的月份
comps.month = 8
//设置NSDateComponents中的年份
comps.year = 2020
//创建日历对象
let calender = NSCalendar(calendarIdentifier: .gregorian)
//从日历中获得2020-8-5日期对象
let destinationDate = calender!.date(from: comps as DateComponents)
let now = Date()
//获得当前日期到2020-8-5的时间段的NSDateComponents对象
let components = calender!.components(.day, from: now, to: destinationDate!, options: [])
//获得当前日期到2020-8-5相差的天数
let days = components.day
let units: NSCalendar.Unit = [.year, .month, .day, .hour, .minute, .second]
|
03c66e92bb94887cd6030c72742fcacb
| 21.482759 | 89 | 0.76227 | false | false | false | false |
livioso/cpib
|
refs/heads/master
|
Compiler/Compiler/context/context.swift
|
mit
|
1
|
import Foundation
enum ContextError: ErrorType {
case IdentifierAlreadyDeclared
case Not_R_Value
case Not_L_Value
case NotInScope
case IdentifierNotDeclared
case NotAllowedType
case VariableIsConstant
case TypeErrorInOperator
case RecordCanNotBeInitializedDirectly
case IdentifierAlreadyInitialized
case IdentifierNotInitialized
case NotWriteable
case RecordsNotSupportedAsRightValue
case InitialisationInTheRightSide
case RoutineDeclarationNotGlobal
case RecordIsConstButNotTheirFields
case ThisExpressionNotAllowedWithDebugin
case SomethingWentWrong //shouldn't be called!
}
enum ValueType {
case BOOL
case INT32
case RECORD
case Unknown //Has to be replaced at the end!
}
enum RoutineType {
case FUN
case PROC
}
enum Side {
case LEFT
case RIGHT
}
enum ExpressionType {
case L_Value
case R_Value
}
enum MechModeType {
case COPY
case REF
}
enum ChangeModeType {
case VAR
case CONST
}
class ContextParameter {
let mechMode:MechModeType
let changeMode:ChangeModeType
let ident:String
let type:ValueType
init(mechMode:MechModeType, changeMode:ChangeModeType, ident:String, type:ValueType) {
self.mechMode = mechMode
self.changeMode = changeMode
self.ident = ident
self.type = type
}
}
class Scope {
var storeTable: [String:Store]
var recordTable:[String:Record] = [:]
init(storeTable:[String:Store]) {
self.storeTable = storeTable
}
init() {
storeTable = [:]
}
}
class Symbol {
var ident:String
var type:ValueType
init(ident:String, type:ValueType){
self.ident = ident
self.type = type
}
}
class Store : Symbol{
var initialized:Bool
var isConst:Bool
var adress:Int = Int.min
var reference:Bool = false
var relative:Bool = false
init(ident:String, type:ValueType, isConst:Bool){
self.initialized = false
self.isConst = isConst
super.init(ident: ident, type: type)
}
func paramCode(let loc:Int, let mechMode:MechModeType) -> Int {
var loc1:Int = loc
AST.codeArray[loc1++] = buildCommand(.LoadImInt, param: "\(adress)")
if(mechMode == MechModeType.COPY) {
AST.codeArray[loc1++] = buildCommand(.Deref)
}
return loc1
}
func code(let loc:Int) -> Int {
var loc1 = codeReference(loc)
AST.codeArray[loc1++] = buildCommand(.Deref)
return loc1
}
func codeReference(let loc:Int) -> Int {
var loc1 = loc
if(relative) {
AST.codeArray[loc1++] = buildCommand(.LoadAddrRel, param: "\(adress)")
} else {
AST.codeArray[loc1++] = buildCommand(.LoadImInt, param: "\(adress)")
}
if(reference){
AST.codeArray[loc1++] = buildCommand(.Deref)
}
return loc1
}
}
class Routine {
let scope:Scope
let ident:String
let routineType:RoutineType
let returnValue:Store?
var parameterList: [ContextParameter] = []
var adress:Int?
var calls: [Int] = []
init(ident:String, routineType: RoutineType, returnValue:Store? = nil) {
self.ident = ident
self.routineType = routineType
self.scope = Scope()
self.returnValue = returnValue
}
}
class Record {
let ident:String
let scope:Scope
var recordFields: [Store] = []
init(ident:String) {
self.ident = ident
self.scope = Scope()
}
func setInitialized(identifier:String) {
scope.storeTable[identifier]?.initialized = true
scope.storeTable[identifier]?.isConst = false
for store in recordFields {
if(store.ident == (ident + "." + identifier)) {
store.initialized = true
}
}
}
func setInitializedDot(identifier:String) {
for store in recordFields {
if(store.ident == identifier) {
store.initialized = true
}
}
let idList = identifier.characters.split{ $0 == "." }.map(String.init)
scope.storeTable[idList[1]]?.initialized = true
scope.storeTable[idList[1]]?.isConst = false
}
}
|
59c3632f8cbff0f5aeb4faa3125b2cc8
| 22.576087 | 90 | 0.615172 | false | false | false | false |
Electrode-iOS/ELControls
|
refs/heads/master
|
ELControls/Extensions/UIView.swift
|
mit
|
2
|
//
// UIView.swift
// ELFoundation
//
// Created by Brandon Sneed on 3/29/16.
// Copyright © 2016 WalmartLabs. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
public func replaceView(view: UIView, newView: UIView) {
let frame = view.frame
newView.frame = frame
view.copyConstraintsToView(newView)
self.addSubview(newView)
view.removeFromSuperview()
}
public func copyConstraintsToView(view: UIView) {
if let superview = self.superview {
for constraint in superview.constraints {
if constraint.firstItem as! NSObject == self {
let newConstraint = NSLayoutConstraint(
item: view,
attribute: constraint.firstAttribute,
relatedBy: constraint.relation,
toItem: constraint.secondItem,
attribute: constraint.secondAttribute,
multiplier: constraint.multiplier,
constant: constraint.constant)
superview.addConstraint(newConstraint)
} else if constraint.secondItem as! NSObject == self {
let newConstraint = NSLayoutConstraint(
item: constraint.firstItem,
attribute: constraint.firstAttribute,
relatedBy: constraint.relation,
toItem: view,
attribute: constraint.secondAttribute,
multiplier: constraint.multiplier,
constant: constraint.constant)
superview.addConstraint(newConstraint)
}
}
}
}
}
|
12d8462047028582f6b8ca6268facd8a
| 34.843137 | 70 | 0.531472 | false | false | false | false |
Octadero/TensorFlow
|
refs/heads/master
|
Sources/TensorFlowKit/Scope.swift
|
gpl-3.0
|
1
|
/* Copyright 2017 The Octadero Authors. All Rights Reserved.
Created by Volodymyr Pavliukevych on 2017.
Licensed under the GPL License, Version 3.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.gnu.org/licenses/gpl-3.0.txt
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 CAPI
import Proto
import CTensorFlow
import Dispatch
public enum ScopeError: Error {
case operationNotFoundByname
}
/// Scope encapsulates common operation properties when building a Graph.
///
/// A Scope object (and its derivates, e.g., obtained from Scope.SubScope)
/// act as a builder for graphs. They allow common properties (such as
/// a name prefix) to be specified for multiple operations being added
/// to the graph.
///
/// A Scope object and all its derivates (e.g., obtained from Scope.SubScope)
/// are not safe for concurrent use by multiple goroutines.
public class Scope {
public var graph: Graph
var namemap = [String : Int]()
var namespace: String?
var controlDependencies = [Operation]()
public init(graph: Graph? = nil, namespace: String? = nil) {
if let graph = graph {
self.graph = graph
} else {
self.graph = Graph()
}
self.namespace = namespace
}
//FIXME: Add mutex https://www.cocoawithlove.com/blog/2016/06/02/threads-and-mutexes.html
/// Add controlDependencies to scope.
public func with<T>(controlDependencies: [Operation], scopeClosure: (_ scope: Scope) throws -> T) throws -> T {
self.controlDependencies = controlDependencies
let result = try scopeClosure(self)
self.controlDependencies.removeAll()
return result
}
/// Add controlDependencies to scope.
public func with<T>(controlDependencyNames: [String], scopeClosure: (_ scope: Scope) throws -> T) throws -> T {
let operations = try controlDependencyNames.map({ (name) -> Operation in
guard let operation = try self.graph.operation(by: name) else {
throw ScopeError.operationNotFoundByname
}
return operation
})
return try self.with(controlDependencies: operations, scopeClosure: scopeClosure)
}
/// Finalize returns the Graph on which this scope operates on and renders s
/// unusable. If there was an error during graph construction, that error is
/// returned instead.
func finalize() throws -> Graph {
return self.graph
}
/// AddOperation adds the operation to the Graph managed by s.
///
/// If there is a name prefix associated with s (such as if s was created
/// by a call to SubScope), then this prefix will be applied to the name
/// of the operation being added. See also Graph.AddOperation.
public func addOperation(specification: OpSpec, controlDependencies: [Operation]? = nil) throws -> Operation {
var specification = specification
if specification.name.isEmpty {
specification.name = specification.type
}
if let namespace = self.namespace {
specification.name = namespace + "/" + specification.name
}
let operation = try self.graph.addOperation(specification: specification, controlDependencies: controlDependencies)
return operation
}
/// SubScope returns a new Scope which will cause all operations added to the
/// graph to be namespaced with 'namespace'. If namespace collides with an
/// existing namespace within the scope, then a suffix will be added.
public func subScope(namespace: String) -> Scope {
var namespace = self.uniqueName(namespace)
if let selfNamespace = self.namespace {
namespace = selfNamespace + "/" + namespace
}
return Scope(graph: graph, namespace: namespace)
}
func uniqueName(_ name:String) -> String {
if let count = self.namemap[name], count > 0{
return"\(name)_\(count)"
}
return name
}
func opName(type:String) -> String {
guard let namespace = self.namespace else {
return type
}
return namespace + "/" + type
}
public func graphDef() throws -> Tensorflow_GraphDef {
return try self.graph.graphDef()
}
}
|
8c5c7c46a408c9c763b5a04ddfa64848
| 34.062992 | 123 | 0.698855 | false | false | false | false |
justindhill/Facets
|
refs/heads/master
|
Facets/Models/OZLModelIssue.swift
|
mit
|
1
|
//
// OZLModelIssue.swift
// Facets
//
// Created by Justin Hill on 4/30/16.
// Copyright © 2016 Justin Hill. All rights reserved.
//
import Foundation
@objc class OZLModelIssue: NSObject, NSCopying {
private static var __once: () = {
OZLModelIssue.dateFormatter.dateFormat = "yyyy-MM-dd"
}()
static let dateFormatter = DateFormatter()
@objc var modelDiffingEnabled: Bool = false {
didSet(oldValue) {
if oldValue != modelDiffingEnabled {
self.changeDictionary = modelDiffingEnabled ? [:] : nil
}
}
}
@objc fileprivate(set) var changeDictionary: [String: AnyObject]? = nil
@objc var tracker: OZLModelTracker? {
didSet {
if let tracker = tracker, self.modelDiffingEnabled {
self.changeDictionary?["tracker_id"] = tracker.trackerId as AnyObject?
}
}
}
@objc var author: OZLModelUser? {
didSet {
if let author = author, self.modelDiffingEnabled {
self.changeDictionary?["author_id"] = author.userId as AnyObject?
}
}
}
@objc var assignedTo: OZLModelUser? {
didSet {
if let assignedTo = assignedTo, self.modelDiffingEnabled {
self.changeDictionary?["assigned_to_id"] = assignedTo.userId as AnyObject?
}
}
}
@objc var priority: OZLModelIssuePriority? {
didSet {
if let priority = priority, self.modelDiffingEnabled {
self.changeDictionary?["priority_id"] = priority.priorityId as AnyObject?
}
}
}
@objc var status: OZLModelIssueStatus? {
didSet {
if let status = status, self.modelDiffingEnabled {
self.changeDictionary?["status_id"] = status.statusId as AnyObject?
}
}
}
@objc var category: OZLModelIssueCategory? {
didSet {
if let category = category, self.modelDiffingEnabled {
self.changeDictionary?["category_id"] = category.categoryId as AnyObject?
}
}
}
@objc var targetVersion: OZLModelVersion? {
didSet {
if let targetVersion = targetVersion, self.modelDiffingEnabled {
self.changeDictionary?["fixed_version_id"] = targetVersion.versionId as AnyObject?
}
}
}
@objc var attachments: [OZLModelAttachment]?
@objc var journals: [OZLModelJournal]?
@objc var customFields: [OZLModelCustomField]?
@objc var index: Int = 0
var projectId: Int? {
didSet {
if let projectId = projectId, self.modelDiffingEnabled {
self.changeDictionary?["project_id"] = projectId as AnyObject?
}
}
}
var parentIssueId: Int? {
didSet {
if let parentIssueId = parentIssueId, self.modelDiffingEnabled {
self.changeDictionary?["parent_issue_id"] = parentIssueId as AnyObject?
}
}
}
@objc var subject: String? {
didSet {
if let subject = subject, self.modelDiffingEnabled {
self.changeDictionary?["subject"] = subject as AnyObject?
}
}
}
@objc var issueDescription: String? {
didSet {
if let issueDescription = issueDescription, self.modelDiffingEnabled {
self.changeDictionary?["description"] = issueDescription as AnyObject?
}
}
}
@objc var startDate: Date? {
didSet {
if let startDate = startDate, self.modelDiffingEnabled {
self.changeDictionary?["start_date"] = OZLModelIssue.dateFormatter.string(from: startDate) as AnyObject?
}
}
}
@objc var dueDate: Date? {
didSet {
if let dueDate = dueDate, self.modelDiffingEnabled {
self.changeDictionary?["due_date"] = OZLModelIssue.dateFormatter.string(from: dueDate) as AnyObject?
}
}
}
@objc var createdOn: Date? {
didSet {
if let createdOn = createdOn, self.modelDiffingEnabled {
self.changeDictionary?["created_on"] = OZLModelIssue.dateFormatter.string(from: createdOn) as AnyObject?
}
}
}
@objc var updatedOn: Date? {
didSet {
if let updatedOn = updatedOn, self.modelDiffingEnabled {
self.changeDictionary?["updated_on"] = OZLModelIssue.dateFormatter.string(from: updatedOn) as AnyObject?
}
}
}
var doneRatio: Float? {
didSet {
if let doneRatio = doneRatio, self.modelDiffingEnabled {
self.changeDictionary?["done_ratio"] = doneRatio as AnyObject?
}
}
}
var spentHours: Float? {
didSet {
if let spentHours = spentHours, self.modelDiffingEnabled {
self.changeDictionary?["spent_hours"] = spentHours as AnyObject?
}
}
}
var estimatedHours: Float? {
didSet {
if let estimatedHours = estimatedHours, self.modelDiffingEnabled {
self.changeDictionary?["estimated_hours"] = estimatedHours as AnyObject?
}
}
}
static var classInitToken = Int()
@objc override init() {
super.init()
setup()
}
@objc init(dictionary d: [String: AnyObject]) {
if let id = d["id"] as? Int {
self.index = id
}
if let project = d["project"] as? [String: AnyObject], let projectId = project["id"] as? Int {
self.projectId = projectId
}
if let parent = d["parent"] as? [String: AnyObject], let parentId = parent["id"] as? Int {
self.parentIssueId = parentId
} else {
self.parentIssueId = -1
}
if let tracker = d["tracker"] as? [AnyHashable: Any] {
self.tracker = OZLModelTracker(attributeDictionary: tracker)
}
if let author = d["author"] as? [AnyHashable: Any] {
self.author = OZLModelUser(attributeDictionary: author)
}
if let assignedTo = d["assigned_to"] as? [AnyHashable: Any] {
self.assignedTo = OZLModelUser(attributeDictionary: assignedTo)
}
if let category = d["category"] as? [AnyHashable: Any] {
self.category = OZLModelIssueCategory(attributeDictionary: category)
}
if let priority = d["priority"] as? [AnyHashable: Any] {
self.priority = OZLModelIssuePriority(attributeDictionary: priority)
}
if let status = d["status"] as? [AnyHashable: Any] {
self.status = OZLModelIssueStatus(attributeDictionary: status)
}
if let customFields = d["custom_fields"] as? [[AnyHashable: Any]] {
self.customFields = customFields.map({ (field) -> OZLModelCustomField in
return OZLModelCustomField(attributeDictionary: field)
})
}
self.subject = d["subject"] as? String
self.issueDescription = d["description"] as? String
if let startDate = d["start_date"] as? String {
self.startDate = NSDate(iso8601String: startDate) as Date?
}
if let dueDate = d["due_date"] as? String {
self.dueDate = NSDate(iso8601String: dueDate) as Date?
}
if let createdOn = d["created_on"] as? String {
self.createdOn = NSDate(iso8601String: createdOn) as Date?
}
if let updatedOn = d["updated_on"] as? String {
self.updatedOn = NSDate(iso8601String: updatedOn) as Date?
}
if let doneRatio = d["done_ratio"] as? Float {
self.doneRatio = doneRatio
}
if let targetVersion = d["fixed_version"] as? [AnyHashable: Any] {
self.targetVersion = OZLModelVersion(attributeDictionary: targetVersion)
}
if let spentHours = d["spent_hours"] as? Float {
self.spentHours = spentHours
}
if let estimatedHours = d["estimated_hours"] as? Float {
self.estimatedHours = estimatedHours
}
if let attachments = d["attachments"] as? [[AnyHashable: Any]] {
self.attachments = attachments.map({ (attachment) -> OZLModelAttachment in
return OZLModelAttachment(dictionary: attachment)
})
}
if let journals = d["journals"] as? [[String: AnyObject]] {
self.journals = journals.map({ (journal) -> OZLModelJournal in
return OZLModelJournal(attributes: journal)
})
}
super.init()
setup()
}
func setup() {
_ = OZLModelIssue.__once
}
@objc func setUpdateComment(_ comment: String) {
if self.modelDiffingEnabled {
self.changeDictionary?["notes"] = comment as AnyObject?
}
}
@objc func setValueOnDiff(_ value: Any, forCustomFieldId fieldId: Int) {
guard value is String || value is Int || value is Float else {
fatalError()
}
if var changeDictionary = self.changeDictionary {
if changeDictionary["custom_fields"] == nil {
changeDictionary["custom_fields"] = [Int: AnyObject]() as AnyObject?
}
if var customFields = changeDictionary["custom_fields"] as? [Int: Any], fieldId > 0 {
customFields[fieldId] = value
changeDictionary["custom_fields"] = customFields as AnyObject
}
self.changeDictionary = changeDictionary
}
}
@objc func setDateOnDiff(_ date: Date, forCustomFieldId fieldId: Int) {
let dateString = OZLModelIssue.dateFormatter.string(from: date)
self.setValueOnDiff(dateString, forCustomFieldId: fieldId)
}
@objc class func displayValueForAttributeName(_ name: String?, attributeId id: Int) -> String? {
if let name = name {
switch name {
case "project_id": return OZLModelProject(forPrimaryKey: id)?.name
case "tracker_id": return OZLModelTracker(forPrimaryKey: id)?.name
case "fixed_version_id": return OZLModelVersion(forPrimaryKey: id)?.name
case "status_id": return OZLModelIssueStatus(forPrimaryKey: id)?.name
case "assigned_to_id": return OZLModelUser(forPrimaryKey: String(id))?.name
case "category_id": return OZLModelIssueCategory(forPrimaryKey: id)?.name
case "priority_id": return OZLModelIssuePriority(forPrimaryKey: id)?.name
default:
return String(id)
}
}
return nil
}
@objc class func displayNameForAttributeName(_ name: String?) -> String {
if let name = name {
switch name {
case "author": return "Author"
case "project_id": return "Project"
case "tracker_id": return "Tracker"
case "fixed_version_id": return "Target version"
case "status_id": return "Status"
case "assigned_to_id": return "Assignee"
case "category_id": return "Category"
case "priority_id": return "Priority"
case "due_date": return "Due date"
case "start_date": return "Start date"
case "done_ratio": return "Percent complete"
case "spent_hours": return "Spent hours"
case "estimated_hours": return "Estimated hours"
case "description": return "Description"
case "subject": return "Subject"
default:
assertionFailure("We were asked for a display name for an attribute we don't know of!")
return name
}
}
return ""
}
@objc func copy(with zone: NSZone?) -> Any {
let copy = OZLModelIssue()
copy.index = self.index
copy.projectId = self.projectId
copy.parentIssueId = self.parentIssueId
copy.tracker = self.tracker
copy.author = self.author
copy.assignedTo = self.assignedTo
copy.priority = self.priority
copy.status = self.status
copy.category = self.category
copy.targetVersion = self.targetVersion
copy.customFields = self.customFields
copy.subject = self.subject
copy.issueDescription = self.issueDescription
copy.startDate = self.startDate
copy.dueDate = self.dueDate
copy.createdOn = self.createdOn
copy.updatedOn = self.updatedOn
copy.doneRatio = self.doneRatio
copy.spentHours = self.spentHours
copy.estimatedHours = self.estimatedHours
copy.attachments = self.attachments
copy.journals = self.journals
return copy
}
}
|
82c66ab0983af962f15e14df1ec21acf
| 32.727979 | 120 | 0.57393 | false | false | false | false |
jovito-royeca/CardMagusKit
|
refs/heads/master
|
CardMagusKit/Classes/NetworkingManager.swift
|
mit
|
1
|
//
// NetworkingManager.swift
// Flag Ceremony
//
// Created by Jovit Royeca on 01/11/2016.
// Copyright © 2016 Jovit Royeca. All rights reserved.
//
import UIKit
import Networking
import ReachabilitySwift
enum HTTPMethod: String {
case post = "Post",
get = "Get",
head = "Head",
put = "Put"
}
typealias NetworkingResult = (_ result: [[String : Any]], _ error: NSError?) -> Void
class NetworkingManager: NSObject {
// var networkers = [String: Any]()
let reachability = Reachability()!
func doOperation(_ baseUrl: String,
path: String,
method: HTTPMethod,
headers: [String: String]?,
paramType: Networking.ParameterType,
params: AnyObject?,
completionHandler: @escaping NetworkingResult) -> Void {
if !reachability.isReachable {
let error = NSError(domain: "network", code: 408, userInfo: [NSLocalizedDescriptionKey: "Network error."])
completionHandler([[String : Any]](), error)
} else {
let networker = networking(forBaseUrl: baseUrl)
if let headers = headers {
networker.headerFields = headers
}
switch (method) {
case .post:
networker.post(path, parameterType: paramType, parameters: params, completion: {(result) in
switch result {
case .success(let response):
if response.json.dictionary.count > 0 {
completionHandler([response.json.dictionary], nil)
} else if response.json.array.count > 0 {
completionHandler(response.json.array, nil)
} else {
completionHandler([[String : Any]](), nil)
}
case .failure(let response):
let error = response.error
print("Networking error: \(error)")
completionHandler([[String : Any]](), error)
}
})
case .get:
networker.get(path, parameters: params, completion: {(result) in
switch result {
case .success(let response):
if response.json.dictionary.count > 0 {
completionHandler([response.json.dictionary], nil)
} else if response.json.array.count > 0 {
completionHandler(response.json.array, nil)
} else {
completionHandler([[String : Any]](), nil)
}
case .failure(let response):
let error = response.error
print("Networking error: \(error)")
completionHandler([[String : Any]](), error)
}
})
case .head:
()
case .put:
networker.put(path, parameterType: paramType, parameters: params, completion: {(result) in
switch result {
case .success(let response):
if response.json.dictionary.count > 0 {
completionHandler([response.json.dictionary], nil)
} else if response.json.array.count > 0 {
completionHandler(response.json.array, nil)
} else {
completionHandler([[String : Any]](), nil)
}
case .failure(let response):
let error = response.error
print("Networking error: \(error)")
completionHandler([[String : Any]](), error)
}
})
}
}
}
func downloadImage(_ url: URL, completionHandler: @escaping (_ origURL: URL?, _ image: UIImage?, _ error: NSError?) -> Void) {
let networker = networking(forUrl: url)
var path = url.path
if let query = url.query {
path += "?\(query)"
}
networker.downloadImage(path, completion: {(result) in
switch result {
case .success(let response):
// skip from iCloud backups!
do {
var destinationURL = try networker.destinationURL(for: path)
var resourceValues = URLResourceValues()
resourceValues.isExcludedFromBackup = true
try destinationURL.setResourceValues(resourceValues)
}
catch {}
completionHandler(url, response.image, nil)
case .failure(let response):
let error = response.error
print("Networking error: \(error)")
completionHandler(nil, nil, error)
}
})
}
func localImageFromURL(_ url: URL) -> UIImage? {
let networker = networking(forUrl: url)
var path = url.path
if let query = url.query {
path += "?\(query)"
}
do {
let destinationURL = try networker.destinationURL(for: path)
if FileManager.default.fileExists(atPath: destinationURL.path) {
return UIImage(contentsOfFile: destinationURL.path)
}
} catch {}
return nil
}
func downloadFile(_ url: URL, completionHandler: @escaping (Data?, NSError?) -> Void) {
let networker = networking(forUrl: url)
let path = url.path
networker.downloadData(path, cacheName: nil, completion: {(result) in
switch result {
case .success(let response):
completionHandler(response.data, nil)
case .failure(let response):
let error = response.error
print("Networking error: \(error)")
completionHandler(nil, error)
}
})
}
func fileExistsAt(_ url : URL, completion: @escaping (Bool) -> Void) {
let checkSession = Foundation.URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
request.timeoutInterval = 1.0 // Adjust to your needs
let task = checkSession.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if let httpResp: HTTPURLResponse = response as? HTTPURLResponse {
completion(httpResp.statusCode == 200)
}
})
task.resume()
}
// MARK: Private methods
fileprivate func networking(forBaseUrl url: String) -> Networking {
var networker:Networking?
//
// if let n = networkers[url] as? Networking {
// networker = n
// } else {
// let newN = Networking(baseURL: url, configurationType: .default)
//
// networkers[url] = newN
// networker = newN
// }
//
networker = Networking(baseURL: url, configurationType: .default)
return networker!
}
fileprivate func networking(forUrl url: URL) -> Networking {
var networker:Networking?
var baseUrl = ""
if let scheme = url.scheme {
baseUrl = "\(scheme)://"
}
if let host = url.host {
baseUrl.append(host)
}
// if let n = networkers[baseUrl] as? Networking {
// networker = n
// } else {
// let newN = Networking(baseURL: baseUrl, configurationType: .default)
//
// networkers[baseUrl] = newN
// networker = newN
// }
networker = Networking(baseURL: baseUrl, configurationType: .default)
return networker!
}
// MARK: - Shared Instance
static let sharedInstance = NetworkingManager()
}
|
52294bd6742ed29bf1eedf525d496f62
| 36.072072 | 130 | 0.49842 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/WordPressShareExtension/ShareModularViewController.swift
|
gpl-2.0
|
1
|
import UIKit
import WordPressKit
import WordPressShared
class ShareModularViewController: ShareExtensionAbstractViewController {
// MARK: - Private Properties
fileprivate var isPublishingPost: Bool = false
fileprivate var isFetchingCategories: Bool = false
/// StackView container for the tables
///
@IBOutlet fileprivate var verticalStackView: UIStackView!
/// Height constraint for modules tableView
///
@IBOutlet weak var modulesHeightConstraint: NSLayoutConstraint!
/// TableView for modules
///
@IBOutlet fileprivate var modulesTableView: UITableView!
/// TableView for site list
///
@IBOutlet fileprivate var sitesTableView: UITableView!
/// Back Bar Button
///
fileprivate lazy var backButton: UIBarButtonItem = {
let backTitle = NSLocalizedString("Back", comment: "Back action on share extension site picker screen. Takes the user to the share extension editor screen.")
let button = UIBarButtonItem(title: backTitle, style: .plain, target: self, action: #selector(backWasPressed))
button.accessibilityIdentifier = "Back Button"
return button
}()
/// Cancel Bar Button
///
fileprivate lazy var cancelButton: UIBarButtonItem = {
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel action on the app extension modules screen.")
let button = UIBarButtonItem(title: cancelTitle, style: .plain, target: self, action: #selector(cancelWasPressed))
button.accessibilityIdentifier = "Cancel Button"
return button
}()
/// Publish Bar Button
///
fileprivate lazy var publishButton: UIBarButtonItem = {
let publishTitle: String
if self.originatingExtension == .share {
publishTitle = NSLocalizedString("Publish", comment: "Publish post action on share extension site picker screen.")
} else {
publishTitle = NSLocalizedString("Save", comment: "Save draft post action on share extension site picker screen.")
}
let button = UIBarButtonItem(title: publishTitle, style: .plain, target: self, action: #selector(publishWasPressed))
if self.originatingExtension == .share {
button.accessibilityIdentifier = "Publish Button"
} else {
button.accessibilityIdentifier = "Draft Button"
}
return button
}()
/// Refresh Control
///
fileprivate lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(pullToRefresh(sender:)), for: .valueChanged)
return refreshControl
}()
/// Activity indicator used when loading categories
///
fileprivate lazy var categoryActivityIndicator = UIActivityIndicatorView(style: .medium)
/// No results view
///
fileprivate lazy var noResultsViewController = NoResultsViewController.controller()
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Initialize Interface
setupNavigationBar()
setupSitesTableView()
setupModulesTableView()
// Setup Autolayout
view.setNeedsUpdateConstraints()
// Load Data
loadContentIfNeeded()
setupPrimarySiteIfNeeded()
setupCategoriesIfNeeded()
reloadSitesIfNeeded()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
verifyAuthCredentials(onSuccess: nil)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
view.setNeedsUpdateConstraints()
}
// MARK: - Setup Helpers
fileprivate func loadContentIfNeeded() {
// Only attempt loading data from the context when launched from the draft extension
guard originatingExtension != .share, let extensionContext = context else {
return
}
ShareExtractor(extensionContext: extensionContext)
.loadShare { share in
self.shareData.title = share.title
self.shareData.contentBody = share.combinedContentHTML
share.images.forEach({ extractedImage in
let imageURL = extractedImage.url
self.shareData.sharedImageDict.updateValue(UUID().uuidString, forKey: imageURL)
// Use the filename as the uploadID here.
if extractedImage.insertionState == .requiresInsertion {
self.shareData.contentBody = self.shareData.contentBody.stringByAppendingMediaURL(mediaURL: imageURL.absoluteString, uploadID: imageURL.lastPathComponent)
}
})
// Clear out the extension context after loading it once. We don't need it anymore.
self.context = nil
self.refreshModulesTable()
}
}
fileprivate func setupPrimarySiteIfNeeded() {
// If the selected site ID is empty, prefill the selected site with what was already used
guard shareData.selectedSiteID == nil else {
return
}
shareData.selectedSiteID = primarySiteID
shareData.selectedSiteName = primarySiteName
}
fileprivate func setupCategoriesIfNeeded() {
if shareData.allCategoriesForSelectedSite == nil {
// Set to `true` so, on first load, the publish button is not enabled until the
// catagories for the selected site are fully loaded
isFetchingCategories = true
}
refreshModulesTable()
}
fileprivate func setupNavigationBar() {
self.navigationItem.hidesBackButton = true
if originatingExtension == .share {
navigationItem.leftBarButtonItem = backButton
} else {
navigationItem.leftBarButtonItem = cancelButton
}
navigationItem.rightBarButtonItem = publishButton
}
fileprivate func setupModulesTableView() {
// Register the cells
modulesTableView.register(WPTableViewCellValue1.self, forCellReuseIdentifier: Constants.modulesReuseIdentifier)
modulesTableView.estimatedRowHeight = Constants.defaultRowHeight
// Hide the separators, whenever the table is empty
modulesTableView.tableFooterView = UIView()
// Style!
WPStyleGuide.configureColors(view: view, tableView: modulesTableView)
WPStyleGuide.configureAutomaticHeightRows(for: modulesTableView)
view.layoutIfNeeded()
}
fileprivate func setupSitesTableView() {
// Register the cells
sitesTableView.register(ShareSitesTableViewCell.self, forCellReuseIdentifier: Constants.sitesReuseIdentifier)
sitesTableView.estimatedRowHeight = Constants.siteRowHeight
// Hide the separators, whenever the table is empty
sitesTableView.tableFooterView = UIView()
// Refresh Control
sitesTableView.refreshControl = refreshControl
// Style!
WPStyleGuide.configureColors(view: view, tableView: sitesTableView)
WPStyleGuide.configureAutomaticHeightRows(for: sitesTableView)
sitesTableView.separatorColor = .divider
}
override func updateViewConstraints() {
super.updateViewConstraints()
// Update the height constraint to match the number of modules * row height
let modulesTableHeight = modulesTableView.rectForRow(at: IndexPath(row: 0, section: 0)).height
modulesHeightConstraint.constant = (CGFloat(ModulesSection.count) * modulesTableHeight)
}
}
// MARK: - Actions
extension ShareModularViewController {
fileprivate func dismiss() {
dismissalCompletionBlock?(true)
}
@objc func cancelWasPressed() {
tracks.trackExtensionCancelled()
cleanUpSharedContainerAndCache()
dismiss()
}
@objc func backWasPressed() {
if let editor = navigationController?.previousViewController() as? ShareExtensionEditorViewController {
editor.sites = sites
editor.shareData = shareData
editor.originatingExtension = originatingExtension
}
_ = navigationController?.popViewController(animated: true)
}
@objc func publishWasPressed() {
savePostToRemoteSite()
}
@objc func pullToRefresh(sender: UIRefreshControl) {
ShareExtensionAbstractViewController.clearCache()
isFetchingCategories = true
clearCategoriesAndRefreshModulesTable()
clearSiteDataAndRefreshSitesTable()
reloadSitesIfNeeded()
}
func showTagsPicker() {
guard let siteID = shareData.selectedSiteID, isPublishingPost == false else {
return
}
let tagsPicker = ShareTagsPickerViewController(siteID: siteID, tags: shareData.tags)
tagsPicker.onValueChanged = { [weak self] tagString in
if self?.shareData.tags != tagString {
self?.tracks.trackExtensionTagsSelected(tagString)
self?.shareData.tags = tagString
self?.refreshModulesTable()
}
}
tracks.trackExtensionTagsOpened()
navigationController?.pushViewController(tagsPicker, animated: true)
}
func showCategoriesPicker() {
guard let siteID = shareData.selectedSiteID,
let allSiteCategories = shareData.allCategoriesForSelectedSite,
isFetchingCategories == false,
isPublishingPost == false else {
return
}
let categoryInfo = SiteCategories(siteID: siteID, allCategories: allSiteCategories, selectedCategories: shareData.userSelectedCategories, defaultCategoryID: shareData.defaultCategoryID)
let categoriesPicker = ShareCategoriesPickerViewController(categoryInfo: categoryInfo)
categoriesPicker.onValueChanged = { [weak self] categoryInfo in
self?.shareData.allCategoriesForSelectedSite = categoryInfo.allCategories
self?.shareData.userSelectedCategories = categoryInfo.selectedCategories
self?.tracks.trackExtensionCategoriesSelected(self?.shareData.selectedCategoriesNameString ?? "")
self?.refreshModulesTable()
}
tracks.trackExtensionCategoriesOpened()
navigationController?.pushViewController(categoriesPicker, animated: true)
}
}
// MARK: - UITableView DataSource Conformance
extension ShareModularViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
if tableView == modulesTableView {
return ModulesSection.count
} else {
// Only 1 section in the sites table
return 1
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == modulesTableView {
switch ModulesSection(rawValue: section)! {
case .categories:
return 1
case .tags:
return 1
case .summary:
return 1
}
} else {
return rowCountForSites
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == modulesTableView {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.modulesReuseIdentifier)!
configureModulesCell(cell, indexPath: indexPath)
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.sitesReuseIdentifier)!
configureSiteCell(cell, indexPath: indexPath)
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return tableView.estimatedRowHeight
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if tableView == modulesTableView {
if isModulesSectionEmpty(section) {
// Hide when the section is empty!
return nil
}
let theSection = ModulesSection(rawValue: section)!
return theSection.headerText()
} else {
// No header for sites table
return nil
}
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if tableView == modulesTableView {
if isModulesSectionEmpty(section) {
// Hide when the section is empty!
return nil
}
let theSection = ModulesSection(rawValue: section)!
return theSection.footerText()
} else {
// No footer for sites table
return nil
}
}
func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
WPStyleGuide.configureTableViewSectionFooter(view)
}
}
// MARK: - UITableView Delegate Conformance
extension ShareModularViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == sitesTableView {
selectedSitesTableRowAt(indexPath)
} else {
selectedModulesTableRowAt(indexPath)
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
guard tableView == sitesTableView else {
return
}
guard let cell = tableView.cellForRow(at: indexPath) else {
return
}
cell.accessoryType = .none
}
}
// MARK: - Modules UITableView Helpers
fileprivate extension ShareModularViewController {
func configureModulesCell(_ cell: UITableViewCell, indexPath: IndexPath) {
switch indexPath.section {
case ModulesSection.categories.rawValue:
WPStyleGuide.Share.configureModuleCell(cell)
cell.textLabel?.text = NSLocalizedString("Category", comment: "Category menu item in share extension.")
cell.accessibilityLabel = "Category"
if isFetchingCategories {
cell.isUserInteractionEnabled = false
cell.accessoryType = .none
cell.accessoryView = categoryActivityIndicator
categoryActivityIndicator.startAnimating()
} else {
switch shareData.categoryCountForSelectedSite {
case 0, 1:
categoryActivityIndicator.stopAnimating()
cell.accessoryView = nil
cell.accessoryType = .none
cell.isUserInteractionEnabled = false
default:
categoryActivityIndicator.stopAnimating()
cell.accessoryView = nil
cell.accessoryType = .disclosureIndicator
cell.isUserInteractionEnabled = true
}
}
cell.detailTextLabel?.text = shareData.selectedCategoriesNameString
if (shareData.userSelectedCategories == nil || shareData.userSelectedCategories?.count == 0)
&& shareData.defaultCategoryID == Constants.unknownDefaultCategoryID {
cell.detailTextLabel?.textColor = .neutral(.shade30)
} else {
cell.detailTextLabel?.textColor = .neutral(.shade70)
}
case ModulesSection.tags.rawValue:
WPStyleGuide.Share.configureModuleCell(cell)
cell.textLabel?.text = NSLocalizedString("Tags", comment: "Tags menu item in share extension.")
cell.accessoryType = .disclosureIndicator
cell.accessibilityLabel = "Tags"
if let tags = shareData.tags, !tags.isEmpty {
cell.detailTextLabel?.text = tags
cell.detailTextLabel?.textColor = .neutral(.shade70)
} else {
cell.detailTextLabel?.text = NSLocalizedString("Add tags", comment: "Placeholder text for tags module in share extension.")
cell.detailTextLabel?.textColor = .neutral(.shade30)
}
default:
// Summary section
cell.textLabel?.text = summaryRowText()
cell.textLabel?.textAlignment = .natural
cell.accessoryType = .none
cell.isUserInteractionEnabled = false
WPStyleGuide.Share.configureTableViewSummaryCell(cell)
}
}
func isModulesSectionEmpty(_ sectionIndex: Int) -> Bool {
switch ModulesSection(rawValue: sectionIndex)! {
case .categories:
return false
case .tags:
return false
case .summary:
return false
}
}
func selectedModulesTableRowAt(_ indexPath: IndexPath) {
switch ModulesSection(rawValue: indexPath.section)! {
case .categories:
if shareData.categoryCountForSelectedSite > 1 {
modulesTableView.flashRowAtIndexPath(indexPath,
scrollPosition: .none,
flashLength: Constants.flashAnimationLength,
completion: nil)
showCategoriesPicker()
}
return
case .tags:
modulesTableView.flashRowAtIndexPath(indexPath,
scrollPosition: .none,
flashLength: Constants.flashAnimationLength,
completion: nil)
showTagsPicker()
return
case .summary:
return
}
}
func summaryRowText() -> String {
if originatingExtension == .share {
return SummaryText.summaryPublishing
} else if originatingExtension == .saveToDraft && shareData.sharedImageDict.isEmpty {
return SummaryText.summaryDraftDefault
} else if originatingExtension == .saveToDraft && !shareData.sharedImageDict.isEmpty {
return ShareNoticeText.pluralize(shareData.sharedImageDict.count,
singular: SummaryText.summaryDraftSingular,
plural: SummaryText.summaryDraftPlural)
} else {
return String()
}
}
func refreshModulesTable(categoriesLoaded: Bool = false) {
if categoriesLoaded {
self.isFetchingCategories = false
self.updatePublishButtonStatus()
}
modulesTableView.reloadData()
}
func clearCategoriesAndRefreshModulesTable() {
shareData.clearCategoryInfo()
refreshModulesTable()
}
}
// MARK: - Sites UITableView Helpers
fileprivate extension ShareModularViewController {
func configureSiteCell(_ cell: UITableViewCell, indexPath: IndexPath) {
guard let site = siteForRowAtIndexPath(indexPath) else {
return
}
// Site's Details
let displayURL = URL(string: site.url)?.host ?? ""
if let name = site.name.nonEmptyString() {
cell.textLabel?.text = name
cell.detailTextLabel?.isEnabled = true
cell.detailTextLabel?.text = displayURL
} else {
cell.textLabel?.text = displayURL
cell.detailTextLabel?.isEnabled = false
cell.detailTextLabel?.text = nil
}
// Site's Blavatar
cell.imageView?.image = WPStyleGuide.Share.blavatarPlaceholderImage
if let siteIconPath = site.icon,
let siteIconUrl = URL(string: siteIconPath) {
cell.imageView?.downloadBlavatar(from: siteIconUrl)
} else {
cell.imageView?.image = WPStyleGuide.Share.blavatarPlaceholderImage
}
if site.blogID.intValue == shareData.selectedSiteID {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
WPStyleGuide.Share.configureTableViewSiteCell(cell)
}
var rowCountForSites: Int {
return sites?.count ?? 0
}
func selectedSitesTableRowAt(_ indexPath: IndexPath) {
sitesTableView.flashRowAtIndexPath(indexPath,
scrollPosition: .none,
flashLength: Constants.flashAnimationLength,
completion: nil)
guard let cell = sitesTableView.cellForRow(at: indexPath),
let site = siteForRowAtIndexPath(indexPath),
site.blogID.intValue != shareData.selectedSiteID else {
return
}
clearAllSelectedSiteRows()
cell.accessoryType = .checkmark
shareData.selectedSiteID = site.blogID.intValue
shareData.selectedSiteName = (site.name?.count)! > 0 ? site.name : URL(string: site.url)?.host
fetchCategoriesForSelectedSite()
updatePublishButtonStatus()
self.refreshModulesTable()
}
func siteForRowAtIndexPath(_ indexPath: IndexPath) -> RemoteBlog? {
guard let sites = sites else {
return nil
}
return sites[indexPath.row]
}
func clearAllSelectedSiteRows() {
for row in 0 ..< rowCountForSites {
let cell = sitesTableView.cellForRow(at: IndexPath(row: row, section: 0))
cell?.accessoryType = .none
}
}
func clearSiteDataAndRefreshSitesTable() {
sites = nil
sitesTableView.reloadData()
}
}
// MARK: - No Results Helpers
fileprivate extension ShareModularViewController {
func showLoadingView() {
updatePublishButtonStatus()
configureAndDisplayStatus(title: StatusText.loadingTitle, accessoryView: NoResultsViewController.loadingAccessoryView())
}
func showPublishingView() {
let title: String = {
if self.originatingExtension == .share {
return StatusText.publishingTitle
}
return StatusText.savingTitle
}()
updatePublishButtonStatus()
configureAndDisplayStatus(title: title, accessoryView: NoResultsViewController.loadingAccessoryView())
}
func showCancellingView() {
updatePublishButtonStatus()
configureAndDisplayStatus(title: StatusText.cancellingTitle, accessoryView: NoResultsViewController.loadingAccessoryView())
}
func showEmptySitesIfNeeded() {
updatePublishButtonStatus()
noResultsViewController.removeFromView()
refreshControl.endRefreshing()
guard !hasSites else {
return
}
configureAndDisplayStatus(title: StatusText.noSitesTitle)
}
func configureAndDisplayStatus(title: String, accessoryView: UIView? = nil) {
noResultsViewController.removeFromView()
noResultsViewController.configure(title: title, accessoryView: accessoryView)
addChild(noResultsViewController)
view.addSubview(noResultsViewController.view)
noResultsViewController.didMove(toParent: self)
}
func updatePublishButtonStatus() {
guard hasSites, shareData.selectedSiteID != nil, shareData.allCategoriesForSelectedSite != nil,
isFetchingCategories == false, isPublishingPost == false else {
publishButton.isEnabled = false
return
}
publishButton.isEnabled = true
}
}
// MARK: - Backend Interaction
fileprivate extension ShareModularViewController {
func fetchCategoriesForSelectedSite() {
guard let _ = oauth2Token, let siteID = shareData.selectedSiteID else {
return
}
isFetchingCategories = true
clearCategoriesAndRefreshModulesTable()
if let cachedCategories = ShareExtensionAbstractViewController.cachedCategoriesForSite(NSNumber(value: siteID)), !cachedCategories.isEmpty {
shareData.allCategoriesForSelectedSite = cachedCategories
self.fetchDefaultCategoryForSelectedSite(onSuccess: { defaultCategoryID in
self.loadDefaultCategory(defaultCategoryID, from: cachedCategories)
}, onFailure: {
self.loadDefaultCategory(Constants.unknownDefaultCategoryID, from: cachedCategories)
})
} else {
let networkService = AppExtensionsService()
networkService.fetchCategoriesForSite(siteID, onSuccess: { categories in
ShareExtensionAbstractViewController.storeCategories(categories, for: NSNumber(value: siteID))
self.shareData.allCategoriesForSelectedSite = categories
self.fetchDefaultCategoryForSelectedSite(onSuccess: { defaultCategoryID in
self.loadDefaultCategory(defaultCategoryID, from: categories)
}, onFailure: {
self.loadDefaultCategory(Constants.unknownDefaultCategoryID, from: categories)
})
}, onFailure: { error in
let error = self.createErrorWithDescription("Could not successfully fetch categories for site: \(siteID). Error: \(String(describing: error))")
self.tracks.trackExtensionError(error)
self.loadDefaultCategory(Constants.unknownDefaultCategoryID, from: [])
})
}
}
func fetchDefaultCategoryForSelectedSite (onSuccess: @escaping (NSNumber) -> (), onFailure: @escaping () -> ()) {
guard let _ = oauth2Token, let siteID = shareData.selectedSiteID else {
return
}
if let cachedDefaultCategoryID = ShareExtensionAbstractViewController.cachedDefaultCategoryIDForSite(NSNumber(value: siteID)) {
onSuccess(cachedDefaultCategoryID)
} else {
let networkService = AppExtensionsService()
networkService.fetchSettingsForSite(siteID, onSuccess: { settings in
guard let settings = settings, let defaultCategoryID = settings.defaultCategoryID else {
onFailure()
return
}
ShareExtensionAbstractViewController.storeDefaultCategoryID(defaultCategoryID, for: NSNumber(value: siteID))
onSuccess(defaultCategoryID)
}) { error in
// The current user probably does not have permissions to access site settings OR needs to be VPNed.
let error = self.createErrorWithDescription("Could not successfully fetch the settings for site: \(siteID). Error: \(String(describing: error))")
self.tracks.trackExtensionError(error)
onFailure()
}
}
}
func loadDefaultCategory(_ defaultCategoryID: NSNumber, from categories: [RemotePostCategory]) {
if defaultCategoryID == Constants.unknownDefaultCategoryID {
self.shareData.setDefaultCategory(categoryID: defaultCategoryID, categoryName: Constants.unknownDefaultCategoryName)
} else {
let defaultCategoryArray = categories.filter { $0.categoryID == defaultCategoryID }
if !defaultCategoryArray.isEmpty, let defaultCategory = defaultCategoryArray.first {
self.shareData.setDefaultCategory(categoryID: defaultCategoryID, categoryName: defaultCategory.name)
}
}
self.refreshModulesTable(categoriesLoaded: true)
}
func reloadSitesIfNeeded() {
guard !hasSites else {
sitesTableView.reloadData()
showEmptySitesIfNeeded()
return
}
let networkService = AppExtensionsService()
networkService.fetchSites(onSuccess: { blogs in
DispatchQueue.main.async {
self.sites = (blogs) ?? [RemoteBlog]()
self.sitesTableView.reloadData()
self.showEmptySitesIfNeeded()
self.fetchCategoriesForSelectedSite()
}
}) {
DispatchQueue.main.async {
self.sites = [RemoteBlog]()
self.sitesTableView.reloadData()
self.showEmptySitesIfNeeded()
self.refreshModulesTable(categoriesLoaded: true)
}
}
showLoadingView()
}
func savePostToRemoteSite() {
guard let _ = oauth2Token, let siteID = shareData.selectedSiteID else {
let error = createErrorWithDescription("Could not save post to remote site: oauth token or site ID is nil.")
self.tracks.trackExtensionError(error)
return
}
guard let _ = sites else {
let error = createErrorWithDescription("Could not save post to remote site: remote sites list missing.")
self.tracks.trackExtensionError(error)
return
}
// Next, save the selected site for later use
if let selectedSiteName = shareData.selectedSiteName {
ShareExtensionService.configureShareExtensionLastUsedSiteID(siteID, lastUsedSiteName: selectedSiteName)
}
// Then proceed uploading the actual post
let localImageURLs = [URL](shareData.sharedImageDict.keys)
if localImageURLs.isEmpty {
// No media. just a simple post
saveAndUploadSimplePost(siteID: siteID)
} else {
// We have media, so let's upload it with the post
uploadPostAndMedia(siteID: siteID, localImageURLs: localImageURLs)
}
}
func prepareForPublishing() {
// We are preemptively logging the Tracks posted event here because if handled in a completion handler,
// there is a good chance iOS will invalidate that network call and the event is never received server-side.
// See https://github.com/wordpress-mobile/WordPress-iOS/issues/9789 for more details.
self.tracks.trackExtensionPosted(self.shareData.postStatus.rawValue)
////
isPublishingPost = true
sitesTableView.refreshControl = nil
clearSiteDataAndRefreshSitesTable()
showPublishingView()
ShareExtensionAbstractViewController.clearCache()
}
func saveAndUploadSimplePost(siteID: Int) {
let service = AppExtensionsService()
prepareForPublishing()
service.saveAndUploadPost(title: shareData.title,
body: shareData.contentBody,
tags: shareData.tags,
categories: shareData.selectedCategoriesIDString,
status: shareData.postStatus.rawValue,
siteID: siteID,
onComplete: {
self.dismiss()
}, onFailure: {
let error = self.createErrorWithDescription("Failed to save and upload post with no media.")
self.tracks.trackExtensionError(error)
self.showRetryAlert()
})
}
func uploadPostAndMedia(siteID: Int, localImageURLs: [URL]) {
guard let siteList = sites else {
return
}
let service = AppExtensionsService()
let isAuthorizedToUploadFiles = service.isAuthorizedToUploadMedia(in: siteList, for: siteID)
guard isAuthorizedToUploadFiles else {
// Error: this role is unable to upload media.
let error = self.createErrorWithDescription("This role is unable to upload media.")
self.tracks.trackExtensionError(error)
showPermissionsAlert()
return
}
prepareForPublishing()
service.uploadPostWithMedia(title: shareData.title,
body: shareData.contentBody,
tags: shareData.tags,
categories: shareData.selectedCategoriesIDString,
status: shareData.postStatus.rawValue,
siteID: siteID,
localMediaFileURLs: localImageURLs,
requestEnqueued: {
self.dismiss()
}, onFailure: {
let error = self.createErrorWithDescription("Failed to save and upload post with media.")
self.tracks.trackExtensionError(error)
self.showRetryAlert()
})
}
func showRetryAlert() {
let title: String = NSLocalizedString("Sharing Error", comment: "Share extension error dialog title.")
let message: String = NSLocalizedString("Whoops, something went wrong while sharing. You can try again, maybe it was a glitch.", comment: "Share extension error dialog text.")
let dismiss: String = NSLocalizedString("Dismiss", comment: "Share extension error dialog cancel button label.")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let acceptButtonText = NSLocalizedString("Try again", comment: "Share extension error dialog retry button label.")
let acceptAction = UIAlertAction(title: acceptButtonText, style: .default) { (action) in
self.savePostToRemoteSite()
}
alertController.addAction(acceptAction)
let dismissButtonText = dismiss
let dismissAction = UIAlertAction(title: dismissButtonText, style: .cancel) { (action) in
self.showCancellingView()
self.cleanUpSharedContainerAndCache()
self.dismiss()
}
alertController.addAction(dismissAction)
present(alertController, animated: true)
}
func showPermissionsAlert() {
let title = NSLocalizedString("Sharing Error", comment: "Share extension error dialog title.")
let message = NSLocalizedString("Your account does not have permission to upload media to this site. The Site Administrator can change these permissions.", comment: "Share extension error dialog text.")
let dismiss = NSLocalizedString("Return to post", comment: "Share extension error dialog cancel button text")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let dismissAction = UIAlertAction(title: dismiss, style: .cancel) { [weak self] (action) in
self?.noResultsViewController.removeFromView()
}
alertController.addAction(dismissAction)
present(alertController, animated: true)
}
}
// MARK: - Table Sections
fileprivate extension ShareModularViewController {
enum ModulesSection: Int {
case categories
case tags
case summary
func headerText() -> String {
switch self {
case .categories:
return String()
case .tags:
return String()
case .summary:
return String()
}
}
func footerText() -> String {
switch self {
case .categories:
return String()
case .tags:
return String()
case .summary:
return String()
}
}
static let count: Int = {
var max: Int = 0
while let _ = ModulesSection(rawValue: max) { max += 1 }
return max
}()
}
}
// MARK: - Constants
fileprivate extension ShareModularViewController {
struct Constants {
static let sitesReuseIdentifier = String(describing: ShareSitesTableViewCell.self)
static let modulesReuseIdentifier = String(describing: ShareModularViewController.self)
static let siteRowHeight = CGFloat(74.0)
static let defaultRowHeight = CGFloat(44.0)
static let emptyCount = 0
static let flashAnimationLength = 0.2
static let unknownDefaultCategoryID = NSNumber(value: -1)
static let unknownDefaultCategoryName = NSLocalizedString("Default", comment: "Placeholder text displayed in the share extension's summary view. It lets the user know the default category will be used on their post.")
}
struct SummaryText {
static let summaryPublishing = NSLocalizedString("Publish post on:", comment: "Text displayed in the share extension's summary view. It describes the publish post action.")
static let summaryDraftDefault = NSLocalizedString("Save draft post on:", comment: "Text displayed in the share extension's summary view that describes the save draft post action.")
static let summaryDraftSingular = NSLocalizedString("Save 1 photo as a draft post on:", comment: "Text displayed in the share extension's summary view that describes the action of saving a single photo in a draft post.")
static let summaryDraftPlural = NSLocalizedString("Save %ld photos as a draft post on:", comment: "Text displayed in the share extension's summary view that describes the action of saving multiple photos in a draft post.")
}
struct StatusText {
static let loadingTitle = NSLocalizedString("Fetching sites...", comment: "A short message to inform the user data for their sites are being fetched.")
static let publishingTitle = NSLocalizedString("Publishing post...", comment: "A short message that informs the user a post is being published to the server from the share extension.")
static let savingTitle = NSLocalizedString("Saving post…", comment: "A short message that informs the user a draft post is being saved to the server from the share extension.")
static let cancellingTitle = NSLocalizedString("Canceling...", comment: "A short message that informs the user the share extension is being canceled.")
static let noSitesTitle = NSLocalizedString("No available sites", comment: "A short message that informs the user no sites could be loaded in the share extension.")
}
}
// MARK: - UITableView Cells
class ShareSitesTableViewCell: WPTableViewCell {
// MARK: - Initializers
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public required override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
public convenience init() {
self.init(style: .subtitle, reuseIdentifier: nil)
}
}
|
aecdd4540af83047d764cc241d2df7af
| 39.348233 | 232 | 0.636043 | false | false | false | false |
khizkhiz/swift
|
refs/heads/master
|
validation-test/compiler_crashers_fixed/00207-swift-parser-parseexprcallsuffix.swift
|
apache-2.0
|
1
|
// RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
}
class f<p : k, p : k n p.d> : o {
}
class fclass func i()
}
i
(d() as e).j.i()
d
protocol i : d { func d
a=1 as a=1
}
func a<g>() -> (g, g -> g) -> g {
var b: ((g, g -> g) -> g)!
return b
}
func f<g : d {
return !(a)
enum g {
func g
var _ = g
func f<T : Boolean>(b: T) {
}
f(true as Boolean)
struct c<d: Sequence, b where Optional<b> == d.Iterator.Element>
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
classwhere A.B == D>(e: A.B) {
}
}
func a() as a).dynamicType.c()
func prefix(with: String) -> <T>(() -> T) -> String {
return { g in "\(with): \(g())" }
}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
typealias h
}
protocol a : a {
}
funcol n {
j q
}
protocol k : k {
}
class k<f : l, q : l p f.q == q> {
}
protocol l {
j q
j o
}
struct n<r : l>
class c {
func b((Any, c))(a: (Any, AnyObject)) {
b(a)
}
}
|
81fc16d9e75d76384f540b3746be0ee5
| 16.059701 | 87 | 0.52231 | false | false | false | false |
wealon/myActivityButton
|
refs/heads/master
|
myActivityButton/myActivityButton/MainViewController.swift
|
mit
|
1
|
//
// MainViewController.swift
// myActivityButton
//
// Created by wealon on 15/8/18.
// Copyright (c) 2015年 com.8ni. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
let btn: ActivityButton = ActivityButton(frame: CGRectMake(20, 320, 200, 30))
// 保存成功
@IBAction func saveSuccess(sender: AnyObject) {
self.btnClick()
}
override func viewDidLoad() {
super.viewDidLoad()
// 1. Round ImageView
setupRoundImageView()
// 2. about the TipButton
setupActivityButton()
}
func setupActivityButton() {
// 设置Activity 为居中展示
self.btn.activitySytle = ActivityPosition.Center
self.btn.setTitle("保存房源", forState: UIControlState.Normal)
self.btn.addTarget(self, action: "btnClick", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(self.btn)
}
func setupRoundImageView() {
// 1. about the RoundImageView
var twoRoundView = RoundImageView(frame: CGRectMake(20, 84, 80, 80))
twoRoundView.backgroundColor = UIColor.yellowColor()
twoRoundView.image = UIImage(named: "redsmile")
self.view.addSubview(twoRoundView)
twoRoundView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func btnClick() {
let curAnimate = self.btn.animate
// printLog("btnClick --- \(curAnimate)")
self.btn.animate = !curAnimate!
if curAnimate == false {
self.btn.enabled = false
self.btn.setTitle("", forState: UIControlState.Normal)
} else {
self.btn.enabled = true
self.btn.setTitle("保存成功", forState: UIControlState.Normal)
}
}
}
extension ViewController: RoundImageViewDelegate {
func roundImageViewClicked(#image: RoundImageView) {
println("点击了图片")
}
}
|
1feb4e3d01a86737ab7896c77c6c454b
| 25.831169 | 101 | 0.617619 | false | false | false | false |
Dimentar/SwiftGen
|
refs/heads/master
|
Pods/PathKit/Sources/PathKit.swift
|
mit
|
2
|
// PathKit - Effortless path operations
import Darwin
import Foundation
/// Represents a filesystem path.
public struct Path {
/// The character used by the OS to separate two path elements
public static let separator = "/"
/// The underlying string representation
internal var path: String
internal static var fileManager = NSFileManager.defaultManager()
// MARK: Init
public init() {
self.path = ""
}
/// Create a Path from a given String
public init(_ path: String) {
self.path = path
}
/// Create a Path by joining multiple path components together
public init<S : CollectionType where S.Generator.Element == String>(components: S) {
if components.isEmpty {
path = "."
} else if components.first == Path.separator && components.count > 1 {
let p = components.joinWithSeparator(Path.separator)
path = p.substringFromIndex(p.startIndex.successor())
} else {
path = components.joinWithSeparator(Path.separator)
}
}
}
// MARK: StringLiteralConvertible
extension Path : StringLiteralConvertible {
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public typealias UnicodeScalarLiteralType = StringLiteralType
public init(extendedGraphemeClusterLiteral path: StringLiteralType) {
self.init(stringLiteral: path)
}
public init(unicodeScalarLiteral path: StringLiteralType) {
self.init(stringLiteral: path)
}
public init(stringLiteral value: StringLiteralType) {
self.path = value
}
}
// MARK: CustomStringConvertible
extension Path : CustomStringConvertible {
public var description: String {
return self.path
}
}
// MARK: Hashable
extension Path : Hashable {
public var hashValue: Int {
return path.hashValue
}
}
// MARK: Path Info
extension Path {
/// Test whether a path is absolute.
///
/// - Returns: `true` iff the path begings with a slash
///
public var isAbsolute: Bool {
return path.hasPrefix(Path.separator)
}
/// Test whether a path is relative.
///
/// - Returns: `true` iff a path is relative (not absolute)
///
public var isRelative: Bool {
return !isAbsolute
}
/// Concatenates relative paths to the current directory and derives the normalized path
///
/// - Returns: the absolute path in the actual filesystem
///
public func absolute() -> Path {
if isAbsolute {
return normalize()
}
return (Path.current + self).normalize()
}
/// Normalizes the path, this cleans up redundant ".." and ".", double slashes
/// and resolves "~".
///
/// - Returns: a new path made by removing extraneous path components from the underlying String
/// representation.
///
public func normalize() -> Path {
return Path((self.path as NSString).stringByStandardizingPath)
}
/// De-normalizes the path, by replacing the current user home directory with "~".
///
/// - Returns: a new path made by removing extraneous path components from the underlying String
/// representation.
///
public func abbreviate() -> Path {
return Path((self.path as NSString).stringByAbbreviatingWithTildeInPath)
}
/// Returns the path of the item pointed to by a symbolic link.
///
/// - Returns: the path of directory or file to which the symbolic link refers
///
public func symlinkDestination() throws -> Path {
let symlinkDestination = try Path.fileManager.destinationOfSymbolicLinkAtPath(path)
let symlinkPath = Path(symlinkDestination)
if symlinkPath.isRelative {
return self + ".." + symlinkPath
} else {
return symlinkPath
}
}
}
// MARK: Path Components
extension Path {
/// The last path component
///
/// - Returns: the last path component
///
public var lastComponent: String {
return (path as NSString).lastPathComponent
}
/// The last path component without file extension
///
/// - Note: This returns "." for "..".
///
/// - Returns: the last path component without file extension
///
public var lastComponentWithoutExtension: String {
return (lastComponent as NSString).stringByDeletingPathExtension
}
/// Splits the string representation on the directory separator.
/// Absolute paths remain the leading slash as first component.
///
/// - Returns: all path components
///
public var components: [String] {
return (path as NSString).pathComponents
}
/// The file extension behind the last dot of the last component.
///
/// - Returns: the file extension
///
public var `extension`: String? {
let pathExtension = (path as NSString).pathExtension
if pathExtension.isEmpty {
return nil
}
return pathExtension
}
}
// MARK: File Info
extension Path {
/// Test whether a file or directory exists at a specified path
///
/// - Returns: `false` iff the path doesn't exist on disk or its existence could not be
/// determined
///
public var exists: Bool {
return Path.fileManager.fileExistsAtPath(self.path)
}
/// Test whether a path is a directory.
///
/// - Returns: `true` if the path is a directory or a symbolic link that points to a directory;
/// `false` if the path is not a directory or the path doesn't exist on disk or its existence
/// could not be determined
///
public var isDirectory: Bool {
var directory = ObjCBool(false)
guard Path.fileManager.fileExistsAtPath(normalize().path, isDirectory: &directory) else {
return false
}
return directory.boolValue
}
/// Test whether a path is a regular file.
///
/// - Returns: `true` if the path is neither a directory nor a symbolic link that points to a
/// directory; `false` if the path is a directory or a symbolic link that points to a
/// directory or the path doesn't exist on disk or its existence
/// could not be determined
///
public var isFile: Bool {
var directory = ObjCBool(false)
guard Path.fileManager.fileExistsAtPath(normalize().path, isDirectory: &directory) else {
return false
}
return !directory.boolValue
}
/// Test whether a path is a symbolic link.
///
/// - Returns: `true` if the path is a symbolic link; `false` if the path doesn't exist on disk
/// or its existence could not be determined
///
public var isSymlink: Bool {
do {
let _ = try Path.fileManager.destinationOfSymbolicLinkAtPath(path)
return true
} catch {
return false
}
}
/// Test whether a path is readable
///
/// - Returns: `true` if the current process has read privileges for the file at path;
/// otherwise `false` if the process does not have read privileges or the existence of the
/// file could not be determined.
///
public var isReadable: Bool {
return Path.fileManager.isReadableFileAtPath(self.path)
}
/// Test whether a path is writeable
///
/// - Returns: `true` if the current process has write privileges for the file at path;
/// otherwise `false` if the process does not have write privileges or the existence of the
/// file could not be determined.
///
public var isWritable: Bool {
return Path.fileManager.isWritableFileAtPath(self.path)
}
/// Test whether a path is executable
///
/// - Returns: `true` if the current process has execute privileges for the file at path;
/// otherwise `false` if the process does not have execute privileges or the existence of the
/// file could not be determined.
///
public var isExecutable: Bool {
return Path.fileManager.isExecutableFileAtPath(self.path)
}
/// Test whether a path is deletable
///
/// - Returns: `true` if the current process has delete privileges for the file at path;
/// otherwise `false` if the process does not have delete privileges or the existence of the
/// file could not be determined.
///
public var isDeletable: Bool {
return Path.fileManager.isDeletableFileAtPath(self.path)
}
}
// MARK: File Manipulation
extension Path {
/// Create the directory.
///
/// - Note: This method fails if any of the intermediate parent directories does not exist.
/// This method also fails if any of the intermediate path elements corresponds to a file and
/// not a directory.
///
public func mkdir() throws -> () {
try Path.fileManager.createDirectoryAtPath(self.path, withIntermediateDirectories: false, attributes: nil)
}
/// Create the directory and any intermediate parent directories that do not exist.
///
/// - Note: This method fails if any of the intermediate path elements corresponds to a file and
/// not a directory.
///
public func mkpath() throws -> () {
try Path.fileManager.createDirectoryAtPath(self.path, withIntermediateDirectories: true, attributes: nil)
}
/// Delete the file or directory.
///
/// - Note: If the path specifies a directory, the contents of that directory are recursively
/// removed.
///
public func delete() throws -> () {
try Path.fileManager.removeItemAtPath(self.path)
}
/// Move the file or directory to a new location synchronously.
///
/// - Parameter destination: The new path. This path must include the name of the file or
/// directory in its new location.
///
public func move(destination: Path) throws -> () {
try Path.fileManager.moveItemAtPath(self.path, toPath: destination.path)
}
/// Copy the file or directory to a new location synchronously.
///
/// - Parameter destination: The new path. This path must include the name of the file or
/// directory in its new location.
///
public func copy(destination: Path) throws -> () {
try Path.fileManager.copyItemAtPath(self.path, toPath: destination.path)
}
/// Creates a hard link at a new destination.
///
/// - Parameter destination: The location where the link will be created.
///
public func link(destination: Path) throws -> () {
try Path.fileManager.linkItemAtPath(self.path, toPath: destination.path)
}
/// Creates a symbolic link at a new destination.
///
/// - Parameter destintation: The location where the link will be created.
///
public func symlink(destination: Path) throws -> () {
try Path.fileManager.createSymbolicLinkAtPath(self.path, withDestinationPath: destination.path)
}
}
// MARK: Current Directory
extension Path {
/// The current working directory of the process
///
/// - Returns: the current working directory of the process
///
public static var current: Path {
get {
return self.init(Path.fileManager.currentDirectoryPath)
}
set {
Path.fileManager.changeCurrentDirectoryPath(newValue.description)
}
}
/// Changes the current working directory of the process to the path during the execution of the
/// given block.
///
/// - Note: The original working directory is restored when the block returns or throws.
/// - Parameter closure: A closure to be executed while the current directory is configured to
/// the path.
///
public func chdir(@noescape closure: () throws -> ()) rethrows {
let previous = Path.current
Path.current = self
defer { Path.current = previous }
try closure()
}
}
// MARK: Temporary
extension Path {
/// - Returns: the path to either the user’s or application’s home directory,
/// depending on the platform.
///
public static var home: Path {
return Path(NSHomeDirectory())
}
/// - Returns: the path of the temporary directory for the current user.
///
public static var temporary: Path {
return Path(NSTemporaryDirectory())
}
/// - Returns: the path of a temporary directory unique for the process.
/// - Note: Based on `NSProcessInfo.globallyUniqueString`.
///
public static func processUniqueTemporary() throws -> Path {
let path = temporary + NSProcessInfo.processInfo().globallyUniqueString
if !path.exists {
try path.mkdir()
}
return path
}
/// - Returns: the path of a temporary directory unique for each call.
/// - Note: Based on `NSUUID`.
///
public static func uniqueTemporary() throws -> Path {
let path = try processUniqueTemporary() + NSUUID().UUIDString
try path.mkdir()
return path
}
}
// MARK: Contents
extension Path {
/// Reads the file.
///
/// - Returns: the contents of the file at the specified path.
///
public func read() throws -> NSData {
return try NSData(contentsOfFile: path, options: NSDataReadingOptions(rawValue: 0))
}
/// Reads the file contents and encoded its bytes to string applying the given encoding.
///
/// - Parameter encoding: the encoding which should be used to decode the data.
/// (by default: `NSUTF8StringEncoding`)
///
/// - Returns: the contents of the file at the specified path as string.
///
public func read(encoding: NSStringEncoding = NSUTF8StringEncoding) throws -> String {
return try NSString(contentsOfFile: path, encoding: encoding) as String
}
/// Write a file.
///
/// - Note: Works atomically: the data is written to a backup file, and then — assuming no
/// errors occur — the backup file is renamed to the name specified by path.
///
/// - Parameter data: the contents to write to file.
///
public func write(data: NSData) throws {
try data.writeToFile(normalize().path, options: .DataWritingAtomic)
}
/// Reads the file.
///
/// - Note: Works atomically: the data is written to a backup file, and then — assuming no
/// errors occur — the backup file is renamed to the name specified by path.
///
/// - Parameter string: the string to write to file.
///
/// - Parameter encoding: the encoding which should be used to represent the string as bytes.
/// (by default: `NSUTF8StringEncoding`)
///
/// - Returns: the contents of the file at the specified path as string.
///
public func write(string: String, encoding: NSStringEncoding = NSUTF8StringEncoding) throws {
try string.writeToFile(normalize().path, atomically: true, encoding: encoding)
}
}
// MARK: Traversing
extension Path {
/// Get the parent directory
///
/// - Returns: the normalized path of the parent directory
///
public func parent() -> Path {
return self + ".."
}
/// Performs a shallow enumeration in a directory
///
/// - Returns: paths to all files, directories and symbolic links contained in the directory
///
public func children() throws -> [Path] {
return try Path.fileManager.contentsOfDirectoryAtPath(path).map {
self + Path($0)
}
}
/// Performs a deep enumeration in a directory
///
/// - Returns: paths to all files, directories and symbolic links contained in the directory or
/// any subdirectory.
///
public func recursiveChildren() throws -> [Path] {
return try Path.fileManager.subpathsOfDirectoryAtPath(path).map {
self + Path($0)
}
}
}
// MARK: Globbing
extension Path {
public static func glob(pattern: String) -> [Path] {
var gt = glob_t()
let cPattern = strdup(pattern)
defer {
globfree(>)
free(cPattern)
}
let flags = GLOB_TILDE | GLOB_BRACE | GLOB_MARK
if Darwin.glob(cPattern, flags, nil, >) == 0 {
return (0..<Int(gt.gl_matchc)).flatMap { index in
if let path = String.fromCString(gt.gl_pathv[index]) {
return Path(path)
}
return nil
}
}
// GLOB_NOMATCH
return []
}
public func glob(pattern: String) -> [Path] {
return Path.glob((self + pattern).description)
}
}
// MARK: SequenceType
extension Path : SequenceType {
/// Enumerates the contents of a directory, returning the paths of all files and directories
/// contained within that directory. These paths are relative to the directory.
public struct DirectoryEnumerator : GeneratorType {
public typealias Element = Path
let path: Path
let directoryEnumerator: NSDirectoryEnumerator
init(path: Path) {
self.path = path
self.directoryEnumerator = Path.fileManager.enumeratorAtPath(path.path)!
}
public func next() -> Path? {
if let next = directoryEnumerator.nextObject() as! String? {
return path + next
}
return nil
}
/// Skip recursion into the most recently obtained subdirectory.
public func skipDescendants() {
directoryEnumerator.skipDescendants()
}
}
/// Perform a deep enumeration of a directory.
///
/// - Returns: a directory enumerator that can be used to perform a deep enumeration of the
/// directory.
///
public func generate() -> DirectoryEnumerator {
return DirectoryEnumerator(path: self)
}
}
// MARK: Equatable
extension Path : Equatable {}
/// Determines if two paths are identical
///
/// - Note: The comparison is string-based. Be aware that two different paths (foo.txt and
/// ./foo.txt) can refer to the same file.
///
public func ==(lhs: Path, rhs: Path) -> Bool {
return lhs.path == rhs.path
}
// MARK: Pattern Matching
/// Implements pattern-matching for paths.
///
/// - Returns: `true` iff one of the following conditions is true:
/// - the paths are equal (based on `Path`'s `Equatable` implementation)
/// - the paths can be normalized to equal Paths.
///
public func ~=(lhs: Path, rhs: Path) -> Bool {
return lhs == rhs
|| lhs.normalize() == rhs.normalize()
}
// MARK: Comparable
extension Path : Comparable {}
/// Defines a strict total order over Paths based on their underlying string representation.
public func <(lhs: Path, rhs: Path) -> Bool {
return lhs.path < rhs.path
}
// MARK: Operators
/// Appends a Path fragment to another Path to produce a new Path
public func +(lhs: Path, rhs: Path) -> Path {
return lhs.path + rhs.path
}
/// Appends a String fragment to another Path to produce a new Path
public func +(lhs: Path, rhs: String) -> Path {
return lhs.path + rhs
}
/// Appends a String fragment to another String to produce a new Path
internal func +(lhs: String, rhs: String) -> Path {
if rhs.hasPrefix(Path.separator) {
// Absolute paths replace relative paths
return Path(rhs)
} else {
var lSlice = (lhs as NSString).pathComponents.fullSlice
var rSlice = (rhs as NSString).pathComponents.fullSlice
// Get rid of trailing "/" at the left side
if lSlice.count > 1 && lSlice.last == Path.separator {
lSlice.removeLast()
}
// Advance after the first relevant "."
lSlice = lSlice.filter { $0 != "." }.fullSlice
rSlice = rSlice.filter { $0 != "." }.fullSlice
// Eats up trailing components of the left and leading ".." of the right side
while lSlice.last != ".." && rSlice.first == ".." {
if (lSlice.count > 1 || lSlice.first != Path.separator) && !lSlice.isEmpty {
// A leading "/" is never popped
lSlice.removeLast()
}
if !rSlice.isEmpty {
rSlice.removeFirst()
}
switch (lSlice.isEmpty, rSlice.isEmpty) {
case (true, _):
break
case (_, true):
break
default:
continue
}
}
return Path(components: lSlice + rSlice)
}
}
extension Array {
var fullSlice: ArraySlice<Element> {
return self[0..<self.endIndex]
}
}
|
e17b5ea10c89dd7f951534ee86c78dc4
| 27.415929 | 110 | 0.670508 | false | false | false | false |
ydi-core/nucleus-ios
|
refs/heads/master
|
Nucleus/VenueController.swift
|
bsd-2-clause
|
1
|
//
// VenueController.swift
// Nucleus
//
// Created by Bezaleel Ashefor on 26/11/2017.
// Copyright © 2017 Ephod. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
import GoogleMaps
import UberRides
class VenueController: UIViewController, CLLocationManagerDelegate {
var latitude: CLLocationDegrees = 6.676057699999999
var longitude: CLLocationDegrees = 3.1714785000000347
@IBOutlet weak var uberBtn: UIButton!
let button = RideRequestButton()
@IBAction func uberBtnClick(_ sender: Any) {
button.sendActions(for: .touchUpInside)
}
let mainStoryBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
@IBOutlet weak var directionsBtn: UIButton!
@IBAction func directionClick(_ sender: Any) {
goToMap()
}
@IBAction func officialsBtn(_ sender: Any) {
let nextController = mainStoryBoard.instantiateViewController(withIdentifier: "detailsView") as! OfficialsController
self.present(nextController, animated: true, completion: nil)
}
@IBAction func progBtn(_ sender: Any) {
let nextController = mainStoryBoard.instantiateViewController(withIdentifier: "programmeView") as! ProgrammeController
self.present(nextController, animated: true, completion: nil)
}
@IBAction func speakersBtn(_ sender: Any) {
let nextController = mainStoryBoard.instantiateViewController(withIdentifier: "speakersView") as! SpeakersController
self.present(nextController, animated: true, completion: nil)
}
@IBAction func profileBtn(_ sender: Any) {
let nextController = mainStoryBoard.instantiateViewController(withIdentifier: "profileView") as! ProfileController
self.present(nextController, animated: true, completion: nil)
}
@IBOutlet weak var mapView: GMSMapView!
func goToMap(){
if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {
UIApplication.shared.open(NSURL(string:"comgooglemaps://?saddr=&daddr=\(latitude),\(longitude)&directionsmode=driving")! as URL, options: [:], completionHandler: nil)
} else {
//NSLog("Can't use comgooglemaps://");
//let latitude: CLLocationDegrees = latitude
//let longitude: CLLocationDegrees = longitude
let regionDistance:CLLocationDistance = 10000
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
let options = [
MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)
]
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = "CJ 2017 - Faith Academy, Canaanland, Ota"
mapItem.openInMaps(launchOptions: options)
}
}
override func viewDidLoad() {
super.viewDidLoad()
removeAttr()
setButtons()
let dropoffLocation = CLLocation(latitude: latitude, longitude: longitude)
let builder = RideParametersBuilder()
builder.dropoffLocation = dropoffLocation
builder.dropoffNickname = "CJ 2017 - Faith Academy, Canaanland, Ota"
button.rideParameters = builder.build()
button.center = view.center
button.isHidden = true
//put the button in the view
view.addSubview(button)
//uberBtn.rideParameters = builder.build()
//determineMyCurrentLocation()
//AIzaSyArNf1B72BOCukW8C5FI5PgJvMKeMN-KQ0
// Do any additional setup after loading the view, typically from a nib.
}
func setButtons(){
uberBtn.layer.shadowColor = UIColor.black.cgColor
uberBtn.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
uberBtn.layer.shadowRadius = 20
uberBtn.layer.shadowOpacity = 0.3
uberBtn.layer.cornerRadius = 5
directionsBtn.layer.shadowColor = UIColor.black.cgColor
directionsBtn.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
directionsBtn.layer.shadowRadius = 20
directionsBtn.layer.shadowOpacity = 0.3
directionsBtn.layer.cornerRadius = 5
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
func removeAttr(){
let camera = GMSCameraPosition.camera(withLatitude: 6.678, longitude: 3.1714785000000347, zoom: 15.5)
mapView.camera = camera
do {
// Set the map style by passing the URL of the local file.
if let styleURL = Bundle.main.url(forResource: "dark_style", withExtension: "json") {
mapView.mapStyle = try GMSMapStyle(contentsOfFileURL: styleURL)
} else {
NSLog("Unable to find style.json")
}
} catch {
NSLog("One or more of the map styles failed to load. \(error)")
}
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: 6.676057699999999, longitude: 3.1714785000000347)
//marker.title = "Faith Academy, Canaanland, Ota"
//marker.snippet = "Venue of CJ 2017"
marker.icon = UIImage(named: "marker")
marker.map = mapView
mapView.isBuildingsEnabled = true
mapView.isIndoorEnabled = true
mapView.isTrafficEnabled = true
mapView.isMyLocationEnabled = true
}
var locManager = CLLocationManager()
var currentLocation = CLLocation()
func determineMyCurrentLocation() {
locManager.delegate = self
locManager.desiredAccuracy = kCLLocationAccuracyBest
locManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locManager.startUpdatingLocation()
//locationManager.startUpdatingHeading()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
currentLocation = userLocation
locManager.stopUpdatingLocation()
latitude = currentLocation.coordinate.latitude
longitude = currentLocation.coordinate.longitude
getPolylineRoute(from: CLLocationCoordinate2D(latitude: latitude, longitude: longitude), to: CLLocationCoordinate2D(latitude: 6.676057699999999, longitude: 3.1714785000000347))
// Call stopUpdatingLocation() to stop listening for location updates,
// other wise this function will be called every time when user location changes.
// manager.stopUpdatingLocation()
//print("user latitude = \(userLocation.coordinate.latitude)")
//print("user longitude = \(userLocation.coordinate.longitude)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print("Error \(error)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//draw distance from you to Ota
func getPolylineRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D){
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: "http://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=false&mode=driving")!
let task = session.dataTask(with: url, completionHandler: {
(data, response, error) in
if error != nil {
print(error!.localizedDescription)
}else{
do {
if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{
let routes = json["routes"] as? [Any]
let overview_polyline = routes?[0] as?[String:Any]
let polyString = overview_polyline?["points"] as?String
//Call this method to draw path on map
self.showPath(polyStr: polyString!)
}
}catch{
print("error in JSONSerialization")
}
}
})
task.resume()
}
func showPath(polyStr :String){
let path = GMSPath(fromEncodedPath: polyStr)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 3.0
polyline.strokeColor = UIColor.white
polyline.map = mapView // Your map view
}
}
|
4b0273d24a8b87177b21c7c2793e01a2
| 37.090164 | 218 | 0.630945 | false | false | false | false |
HassanEskandari/Eureka
|
refs/heads/master
|
Pods/Eureka/Source/Rows/SelectableRows/ListCheckRow.swift
|
apache-2.0
|
4
|
// ListCheckRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class ListCheckCell<T: Equatable> : Cell<T>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func update() {
super.update()
accessoryType = row.value != nil ? .checkmark : .none
editingAccessoryType = accessoryType
selectionStyle = .default
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
if row.isDisabled {
tintColor = UIColor(red: red, green: green, blue: blue, alpha: 0.3)
selectionStyle = .none
} else {
tintColor = UIColor(red: red, green: green, blue: blue, alpha: 1)
}
}
open override func setup() {
super.setup()
accessoryType = .checkmark
editingAccessoryType = accessoryType
}
open override func didSelect() {
row.deselect()
row.updateCell()
}
}
public final class ListCheckRow<T>: Row<ListCheckCell<T>>, SelectableRowType, RowType where T: Equatable {
public var selectableValue: T?
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
}
}
|
64fa826d1b81980281f0b191eb7a1509
| 36.380282 | 106 | 0.682366 | false | false | false | false |
kaltura/playkit-ios
|
refs/heads/develop
|
Classes/Player/PlayerEngineWrapper.swift
|
agpl-3.0
|
1
|
import Foundation
public class PlayerEngineWrapper: NSObject, PlayerEngine {
public var playerEngine: PlayerEngine?
public var onEventBlock: ((PKEvent) -> Void)? {
get {
return playerEngine?.onEventBlock
}
set {
playerEngine?.onEventBlock = newValue
}
}
public var startPosition: TimeInterval {
get {
return playerEngine?.startPosition ?? 0.0
}
set {
playerEngine?.startPosition = newValue
}
}
public var currentPosition: TimeInterval {
get {
return playerEngine?.currentPosition ?? 0.0
}
set {
playerEngine?.currentPosition = newValue
}
}
public var mediaConfig: MediaConfig? {
get {
return playerEngine?.mediaConfig
}
set {
playerEngine?.mediaConfig = newValue
}
}
public var playbackType: String? {
return playerEngine?.playbackType
}
public var duration: TimeInterval {
return playerEngine?.duration ?? 0.0
}
public var currentState: PlayerState {
return playerEngine?.currentState ?? .unknown
}
public var isPlaying: Bool {
return playerEngine?.isPlaying ?? false
}
public var view: PlayerView? {
get {
return playerEngine?.view
}
set {
playerEngine?.view = newValue
}
}
public var currentTime: TimeInterval {
get {
return playerEngine?.currentTime ?? 0.0
}
set {
playerEngine?.currentTime = newValue
}
}
public var currentProgramTime: Date? {
return playerEngine?.currentProgramTime
}
public var currentAudioTrack: String? {
return playerEngine?.currentAudioTrack
}
public var currentTextTrack: String? {
return playerEngine?.currentTextTrack
}
public var rate: Float {
get {
return playerEngine?.rate ?? 0.0
}
set {
playerEngine?.rate = newValue
}
}
public var volume: Float {
get {
return playerEngine?.volume ?? 0.0
}
set {
playerEngine?.volume = newValue
}
}
public var loadedTimeRanges: [PKTimeRange]? {
return playerEngine?.loadedTimeRanges
}
public var bufferedTime: TimeInterval {
return playerEngine?.bufferedTime ?? self.currentTime
}
public func loadMedia(from mediaSource: PKMediaSource?, handler: AssetHandler) {
playerEngine?.loadMedia(from: mediaSource, handler: handler)
}
public func playFromLiveEdge() {
playerEngine?.playFromLiveEdge()
}
public func updateTextTrackStyling(_ textTrackStyling: PKTextTrackStyling) {
playerEngine?.updateTextTrackStyling(textTrackStyling)
}
public func play() {
playerEngine?.play()
}
public func pause() {
playerEngine?.pause()
}
public func resume() {
playerEngine?.resume()
}
public func stop() {
playerEngine?.stop()
}
public func replay() {
playerEngine?.replay()
}
public func seek(to time: TimeInterval) {
playerEngine?.seek(to: time)
}
public func seekToLiveEdge() {
playerEngine?.seekToLiveEdge()
}
public func selectTrack(trackId: String) {
playerEngine?.selectTrack(trackId: trackId)
}
public func destroy() {
playerEngine?.destroy()
}
public func prepare(_ config: MediaConfig) {
playerEngine?.prepare(config)
}
public func startBuffering() {
playerEngine?.startBuffering()
}
}
|
9aac9f572e72f1e4921b140574d47deb
| 21.633721 | 84 | 0.562291 | false | false | false | false |
yaslab/Harekaze-iOS
|
refs/heads/feature-tvos
|
Harekaze-tvOS/Views/VideoPlaybackControllerView.swift
|
bsd-3-clause
|
1
|
//
// VideoPlaybackControllerView.swift
// Harekaze
//
// Created by Yasuhiro Hatta on 2016/08/27.
// Copyright © 2016年 Yuki MIZUNO. All rights reserved.
//
import UIKit
class VideoPlaybackControllerView: UIView, NibInstantiatable {
@IBOutlet private weak var seekCursorView: UIView!
@IBOutlet weak var progressView: UIProgressView!
private var seekCursorViewLocation: CGPoint = .zero
override func awakeFromNib() {
super.awakeFromNib()
seekCursorView.isHidden = true
}
override var isHidden: Bool {
didSet {
if isHidden {
seekCursorView.isHidden = true
}
}
}
@IBAction private func handlePanGestureRecognizer(_ sender: UIPanGestureRecognizer) {
switch sender.state {
case .began:
var frame: CGRect = seekCursorView.frame
frame.size.width = 20
frame.size.height = 100
if !seekCursorView.isHidden {
frame.origin.x = progressView.frame.minX
+ (progressView.frame.width * CGFloat(progressView.progress))
}
frame.origin.y = progressView.frame.minY - frame.height - 10
seekCursorView.frame = frame
seekCursorViewLocation = frame.origin
seekCursorView.isHidden = false
setNeedsLayout()
case .changed:
let translation = sender.translation(in: sender.view)
var frame = seekCursorView.frame
frame.origin.x = clamp(
seekCursorViewLocation.x + translation.x,
min: progressView.frame.minX,
max: progressView.frame.maxX
)
seekCursorView.frame = frame
setNeedsLayout()
case .ended:
break
default:
break
}
}
var seekCursorProgress: Float? {
if seekCursorView.isHidden {
return nil
}
let position = seekCursorView.frame.minX - progressView.frame.minX
let width = progressView.frame.width
return clamp(Float(position / width), min: 0, max: 1)
}
}
|
123cf3cf7b6d52c20a8707acdfb6767a
| 27.675325 | 89 | 0.579257 | false | false | false | false |
CocoaHeads-Shanghai/MeetupPresentations
|
refs/heads/master
|
10_SwiftRAC/Pods/ReactiveCocoa/ReactiveCocoa/Swift/Signal.swift
|
apache-2.0
|
25
|
import Result
/// A push-driven stream that sends Events over time, parameterized by the type
/// of values being sent (`Value`) and the type of failure that can occur (`Error`).
/// If no failures should be possible, NoError can be specified for `Error`.
///
/// An observer of a Signal will see the exact same sequence of events as all
/// other observers. In other words, events will be sent to all observers at the
/// same time.
///
/// Signals are generally used to represent event streams that are already “in
/// progress,” like notifications, user input, etc. To represent streams that
/// must first be _started_, see the SignalProducer type.
///
/// Signals do not need to be retained. A Signal will be automatically kept
/// alive until the event stream has terminated.
public final class Signal<Value, Error: ErrorType> {
public typealias Observer = ReactiveCocoa.Observer<Value, Error>
private let atomicObservers: Atomic<Bag<Observer>?> = Atomic(Bag())
/// Initializes a Signal that will immediately invoke the given generator,
/// then forward events sent to the given observer.
///
/// The disposable returned from the closure will be automatically disposed
/// if a terminating event is sent to the observer. The Signal itself will
/// remain alive until the observer is released.
public init(@noescape _ generator: Observer -> Disposable?) {
/// Used to ensure that events are serialized during delivery to observers.
let sendLock = NSLock()
sendLock.name = "org.reactivecocoa.ReactiveCocoa.Signal"
let generatorDisposable = SerialDisposable()
/// When set to `true`, the Signal should interrupt as soon as possible.
let interrupted = Atomic(false)
let observer = Observer { event in
if case .Interrupted = event {
// Normally we disallow recursive events, but
// Interrupted is kind of a special snowflake, since it
// can inadvertently be sent by downstream consumers.
//
// So we'll flag Interrupted events specially, and if it
// happened to occur while we're sending something else,
// we'll wait to deliver it.
interrupted.value = true
if sendLock.tryLock() {
self.interrupt()
sendLock.unlock()
generatorDisposable.dispose()
}
} else {
if let observers = (event.isTerminating ? self.atomicObservers.swap(nil) : self.atomicObservers.value) {
sendLock.lock()
for observer in observers {
observer.action(event)
}
let shouldInterrupt = !event.isTerminating && interrupted.value
if shouldInterrupt {
self.interrupt()
}
sendLock.unlock()
if event.isTerminating || shouldInterrupt {
// Dispose only after notifying observers, so disposal logic
// is consistently the last thing to run.
generatorDisposable.dispose()
}
}
}
}
generatorDisposable.innerDisposable = generator(observer)
}
/// A Signal that never sends any events to its observers.
public static var never: Signal {
return self.init { _ in nil }
}
/// Creates a Signal that will be controlled by sending events to the given
/// observer.
///
/// The Signal will remain alive until a terminating event is sent to the
/// observer.
public static func pipe() -> (Signal, Observer) {
var observer: Observer!
let signal = self.init { innerObserver in
observer = innerObserver
return nil
}
return (signal, observer)
}
/// Interrupts all observers and terminates the stream.
private func interrupt() {
if let observers = self.atomicObservers.swap(nil) {
for observer in observers {
observer.sendInterrupted()
}
}
}
/// Observes the Signal by sending any future events to the given observer. If
/// the Signal has already terminated, the observer will immediately receive an
/// `Interrupted` event.
///
/// Returns a Disposable which can be used to disconnect the observer. Disposing
/// of the Disposable will have no effect on the Signal itself.
public func observe(observer: Observer) -> Disposable? {
var token: RemovalToken?
atomicObservers.modify { observers in
guard var observers = observers else { return nil }
token = observers.insert(observer)
return observers
}
if let token = token {
return ActionDisposable {
self.atomicObservers.modify { observers in
guard var observers = observers else { return nil }
observers.removeValueForToken(token)
return observers
}
}
} else {
observer.sendInterrupted()
return nil
}
}
}
public protocol SignalType {
/// The type of values being sent on the signal.
typealias Value
/// The type of error that can occur on the signal. If errors aren't possible
/// then `NoError` can be used.
typealias Error: ErrorType
/// Extracts a signal from the receiver.
var signal: Signal<Value, Error> { get }
/// Observes the Signal by sending any future events to the given observer.
func observe(observer: Signal<Value, Error>.Observer) -> Disposable?
}
extension Signal: SignalType {
public var signal: Signal {
return self
}
}
extension SignalType {
/// Convenience override for observe(_:) to allow trailing-closure style
/// invocations.
public func observe(action: Signal<Value, Error>.Observer.Action) -> Disposable? {
return observe(Observer(action))
}
/// Observes the Signal by invoking the given callback when `next` events are
/// received.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callbacks. Disposing of the Disposable will have no effect on the Signal
/// itself.
public func observeNext(next: Value -> ()) -> Disposable? {
return observe(Observer(next: next))
}
/// Observes the Signal by invoking the given callback when a `completed` event is
/// received.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callback. Disposing of the Disposable will have no effect on the Signal
/// itself.
public func observeCompleted(completed: () -> ()) -> Disposable? {
return observe(Observer(completed: completed))
}
/// Observes the Signal by invoking the given callback when a `failed` event is
/// received.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callback. Disposing of the Disposable will have no effect on the Signal
/// itself.
public func observeFailed(error: Error -> ()) -> Disposable? {
return observe(Observer(failed: error))
}
/// Observes the Signal by invoking the given callback when an `interrupted` event is
/// received. If the Signal has already terminated, the callback will be invoked
/// immediately.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callback. Disposing of the Disposable will have no effect on the Signal
/// itself.
public func observeInterrupted(interrupted: () -> ()) -> Disposable? {
return observe(Observer(interrupted: interrupted))
}
/// Maps each value in the signal to a new value.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func map<U>(transform: Value -> U) -> Signal<U, Error> {
return Signal { observer in
return self.observe { event in
observer.action(event.map(transform))
}
}
}
/// Maps errors in the signal to a new error.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func mapError<F>(transform: Error -> F) -> Signal<Value, F> {
return Signal { observer in
return self.observe { event in
observer.action(event.mapError(transform))
}
}
}
/// Catches any failure that may occur on the input signal, mapping to a new producer
/// that starts in its place.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMapError<F>(handler: Error -> SignalProducer<Value, F>) -> Signal<Value, F> {
return Signal { observer in
let serialDisposable = SerialDisposable()
serialDisposable.innerDisposable = self.observe { event in
switch event {
case let .Next(value):
observer.sendNext(value)
case let .Failed(error):
handler(error).startWithSignal { signal, signalDisposable in
serialDisposable.innerDisposable = signalDisposable
signal.observe(observer)
}
case .Completed:
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
return serialDisposable
}
}
/// Preserves only the values of the signal that pass the given predicate.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func filter(predicate: Value -> Bool) -> Signal<Value, Error> {
return Signal { observer in
return self.observe { (event: Event<Value, Error>) -> () in
if case let .Next(value) = event {
if predicate(value) {
observer.sendNext(value)
}
} else {
observer.action(event)
}
}
}
}
}
/// Describes how multiple producers should be joined together.
public enum FlattenStrategy: Equatable {
/// The producers should be merged, so that any value received on any of the
/// input producers will be forwarded immediately to the output producer.
///
/// The resulting producer will complete only when all inputs have completed.
case Merge
/// The producers should be concatenated, so that their values are sent in the
/// order of the producers themselves.
///
/// The resulting producer will complete only when all inputs have completed.
case Concat
/// Only the events from the latest input producer should be considered for
/// the output. Any producers received before that point will be disposed of.
///
/// The resulting producer will complete only when the producer-of-producers and
/// the latest producer has completed.
case Latest
}
extension SignalType where Value: SignalType, Error == Value.Error {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` or an active inner signal emits an error, the returned
/// signal will forward that error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.map(SignalProducer.init).flatten(strategy)
}
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` or an active inner producer fails, the returned signal will
/// forward that failure immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
switch strategy {
case .Merge:
return self.merge()
case .Concat:
return self.concat()
case .Latest:
return self.switchToLatest()
}
}
}
extension SignalType {
/// Maps each event from `signal` to a new producer, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created producers fail, the returned signal
/// will forward that failure immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created signals emit an error, the returned
/// signal will forward that error immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalType {
/// Merges the given signals into a single `Signal` that will emit all values
/// from each of them, and complete when all of them have completed.
public static func merge<S: SequenceType where S.Generator.Element == Signal<Value, Error>>(signals: S) -> Signal<Value, Error> {
let producer = SignalProducer<Signal<Value, Error>, Error>(values: signals)
var result: Signal<Value, Error>!
producer.startWithSignal { (signal, _) in
result = signal.flatten(.Merge)
}
return result
}
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Returns a signal which sends all the values from producer signal emitted from
/// `signal`, waiting until each inner producer completes before beginning to
/// send the values from the next inner producer.
///
/// If any of the inner producers fail, the returned signal will forward
/// that failure immediately
///
/// The returned signal completes only when `signal` and all producers
/// emitted from `signal` complete.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
private func concat() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { observer in
let disposable = CompositeDisposable()
let state = ConcatState(observer: observer, disposable: disposable)
disposable += self.observe { event in
switch event {
case let .Next(value):
state.enqueueSignalProducer(value.producer)
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
// Add one last producer to the queue, whose sole job is to
// "turn out the lights" by completing `observer`.
state.enqueueSignalProducer(SignalProducer.empty.on(completed: {
observer.sendCompleted()
}))
case .Interrupted:
observer.sendInterrupted()
}
}
return disposable
}
}
}
private final class ConcatState<Value, Error: ErrorType> {
/// The observer of a started `concat` producer.
let observer: Signal<Value, Error>.Observer
/// The top level disposable of a started `concat` producer.
let disposable: CompositeDisposable
/// The active producer, if any, and the producers waiting to be started.
let queuedSignalProducers: Atomic<[SignalProducer<Value, Error>]> = Atomic([])
init(observer: Signal<Value, Error>.Observer, disposable: CompositeDisposable) {
self.observer = observer
self.disposable = disposable
}
func enqueueSignalProducer(producer: SignalProducer<Value, Error>) {
if disposable.disposed {
return
}
var shouldStart = true
queuedSignalProducers.modify { (var queue) in
// An empty queue means the concat is idle, ready & waiting to start
// the next producer.
shouldStart = queue.isEmpty
queue.append(producer)
return queue
}
if shouldStart {
startNextSignalProducer(producer)
}
}
func dequeueSignalProducer() -> SignalProducer<Value, Error>? {
if disposable.disposed {
return nil
}
var nextSignalProducer: SignalProducer<Value, Error>?
queuedSignalProducers.modify { (var queue) in
// Active producers remain in the queue until completed. Since
// dequeueing happens at completion of the active producer, the
// first producer in the queue can be removed.
if !queue.isEmpty { queue.removeAtIndex(0) }
nextSignalProducer = queue.first
return queue
}
return nextSignalProducer
}
/// Subscribes to the given signal producer.
func startNextSignalProducer(signalProducer: SignalProducer<Value, Error>) {
signalProducer.startWithSignal { signal, disposable in
let handle = self.disposable.addDisposable(disposable)
signal.observe { event in
switch event {
case .Completed, .Interrupted:
handle.remove()
if let nextSignalProducer = self.dequeueSignalProducer() {
self.startNextSignalProducer(nextSignalProducer)
}
default:
self.observer.action(event)
}
}
}
}
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased toward the producer
/// added earlier. Returns a Signal that will forward events from the inner producers as they arrive.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
private func merge() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { relayObserver in
let inFlight = Atomic(1)
let decrementInFlight: () -> () = {
let orig = inFlight.modify { $0 - 1 }
if orig == 1 {
relayObserver.sendCompleted()
}
}
let disposable = CompositeDisposable()
self.observe { event in
switch event {
case let .Next(producer):
producer.startWithSignal { innerSignal, innerDisposable in
inFlight.modify { $0 + 1 }
let handle = disposable.addDisposable(innerDisposable)
innerSignal.observe { event in
switch event {
case .Completed, .Interrupted:
if event.isTerminating {
handle.remove()
}
decrementInFlight()
default:
relayObserver.action(event)
}
}
}
case let .Failed(error):
relayObserver.sendFailed(error)
case .Completed:
decrementInFlight()
case .Interrupted:
relayObserver.sendInterrupted()
}
}
return disposable
}
}
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
private func switchToLatest() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { observer in
let disposable = CompositeDisposable()
let latestInnerDisposable = SerialDisposable()
disposable.addDisposable(latestInnerDisposable)
let state = Atomic(LatestState<Value, Error>())
self.observe { event in
switch event {
case let .Next(innerProducer):
innerProducer.startWithSignal { innerSignal, innerDisposable in
state.modify { (var state) in
// When we replace the disposable below, this prevents the
// generated Interrupted event from doing any work.
state.replacingInnerSignal = true
return state
}
latestInnerDisposable.innerDisposable = innerDisposable
state.modify { (var state) in
state.replacingInnerSignal = false
state.innerSignalComplete = false
return state
}
innerSignal.observe { event in
switch event {
case .Interrupted:
// If interruption occurred as a result of a new producer
// arriving, we don't want to notify our observer.
let original = state.modify { (var state) in
if !state.replacingInnerSignal {
state.innerSignalComplete = true
}
return state
}
if !original.replacingInnerSignal && original.outerSignalComplete {
observer.sendCompleted()
}
case .Completed:
let original = state.modify { (var state) in
state.innerSignalComplete = true
return state
}
if original.outerSignalComplete {
observer.sendCompleted()
}
default:
observer.action(event)
}
}
}
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
let original = state.modify { (var state) in
state.outerSignalComplete = true
return state
}
if original.innerSignalComplete {
observer.sendCompleted()
}
case .Interrupted:
observer.sendInterrupted()
}
}
return disposable
}
}
}
private struct LatestState<Value, Error: ErrorType> {
var outerSignalComplete: Bool = false
var innerSignalComplete: Bool = true
var replacingInnerSignal: Bool = false
}
extension SignalType where Value: OptionalType {
/// Unwraps non-`nil` values and forwards them on the returned signal, `nil`
/// values are dropped.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func ignoreNil() -> Signal<Value.Wrapped, Error> {
return filter { $0.optional != nil }.map { $0.optional! }
}
}
extension SignalType {
/// Returns a signal that will yield the first `count` values from `self`
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func take(count: Int) -> Signal<Value, Error> {
precondition(count >= 0)
return Signal { observer in
if count == 0 {
observer.sendCompleted()
return nil
}
var taken = 0
return self.observe { event in
if case let .Next(value) = event {
if taken < count {
taken++
observer.sendNext(value)
}
if taken == count {
observer.sendCompleted()
}
} else {
observer.action(event)
}
}
}
}
}
/// A reference type which wraps an array to avoid copying it for performance and
/// memory usage optimization.
private final class CollectState<Value> {
var values: [Value] = []
func append(value: Value) -> Self {
values.append(value)
return self
}
}
extension SignalType {
/// Returns a signal that will yield an array of values when `self` completes.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func collect() -> Signal<[Value], Error> {
return self
.reduce(CollectState()) { $0.append($1) }
.map { $0.values }
}
/// Forwards all events onto the given scheduler, instead of whichever
/// scheduler they originally arrived upon.
public func observeOn(scheduler: SchedulerType) -> Signal<Value, Error> {
return Signal { observer in
return self.observe { event in
scheduler.schedule {
observer.action(event)
}
}
}
}
}
private final class CombineLatestState<Value> {
var latestValue: Value?
var completed = false
}
extension SignalType {
private func observeWithStates<U>(signalState: CombineLatestState<Value>, _ otherState: CombineLatestState<U>, _ lock: NSLock, _ onBothNext: () -> (), _ onFailed: Error -> (), _ onBothCompleted: () -> (), _ onInterrupted: () -> ()) -> Disposable? {
return self.observe { event in
switch event {
case let .Next(value):
lock.lock()
signalState.latestValue = value
if otherState.latestValue != nil {
onBothNext()
}
lock.unlock()
case let .Failed(error):
onFailed(error)
case .Completed:
lock.lock()
signalState.completed = true
if otherState.completed {
onBothCompleted()
}
lock.unlock()
case .Interrupted:
onInterrupted()
}
}
}
/// Combines the latest value of the receiver with the latest value from
/// the given signal.
///
/// The returned signal will not send a value until both inputs have sent
/// at least one value each. If either signal is interrupted, the returned signal
/// will also be interrupted.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatestWith<U>(otherSignal: Signal<U, Error>) -> Signal<(Value, U), Error> {
return Signal { observer in
let lock = NSLock()
lock.name = "org.reactivecocoa.ReactiveCocoa.combineLatestWith"
let signalState = CombineLatestState<Value>()
let otherState = CombineLatestState<U>()
let onBothNext = { () -> () in
observer.sendNext((signalState.latestValue!, otherState.latestValue!))
}
let onFailed = observer.sendFailed
let onBothCompleted = observer.sendCompleted
let onInterrupted = observer.sendInterrupted
let disposable = CompositeDisposable()
disposable += self.observeWithStates(signalState, otherState, lock, onBothNext, onFailed, onBothCompleted, onInterrupted)
disposable += otherSignal.observeWithStates(otherState, signalState, lock, onBothNext, onFailed, onBothCompleted, onInterrupted)
return disposable
}
}
/// Delays `Next` and `Completed` events by the given interval, forwarding
/// them on the given scheduler.
///
/// `Failed` and `Interrupted` events are always scheduled immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func delay(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer in
return self.observe { event in
switch event {
case .Failed, .Interrupted:
scheduler.schedule {
observer.action(event)
}
default:
let date = scheduler.currentDate.dateByAddingTimeInterval(interval)
scheduler.scheduleAfter(date) {
observer.action(event)
}
}
}
}
}
/// Returns a signal that will skip the first `count` values, then forward
/// everything afterward.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skip(count: Int) -> Signal<Value, Error> {
precondition(count >= 0)
if count == 0 {
return signal
}
return Signal { observer in
var skipped = 0
return self.observe { event in
if case .Next = event where skipped < count {
skipped++
} else {
observer.action(event)
}
}
}
}
/// Treats all Events from `self` as plain values, allowing them to be manipulated
/// just like any other value.
///
/// In other words, this brings Events “into the monad.”
///
/// When a Completed or Failed event is received, the resulting signal will send
/// the Event itself and then complete. When an Interrupted event is received,
/// the resulting signal will send the Event itself and then interrupt.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func materialize() -> Signal<Event<Value, Error>, NoError> {
return Signal { observer in
return self.observe { event in
observer.sendNext(event)
switch event {
case .Interrupted:
observer.sendInterrupted()
case .Completed, .Failed:
observer.sendCompleted()
case .Next:
break
}
}
}
}
}
extension SignalType where Value: EventType, Error == NoError {
/// The inverse of materialize(), this will translate a signal of `Event`
/// _values_ into a signal of those events themselves.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func dematerialize() -> Signal<Value.Value, Value.Error> {
return Signal<Value.Value, Value.Error> { observer in
return self.observe { event in
switch event {
case let .Next(innerEvent):
observer.action(innerEvent.event)
case .Failed:
fatalError("NoError is impossible to construct")
case .Completed:
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
}
extension SignalType {
/// Injects side effects to be performed upon the specified signal events.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func on(event event: (Event<Value, Error> -> ())? = nil, failed: (Error -> ())? = nil, completed: (() -> ())? = nil, interrupted: (() -> ())? = nil, terminated: (() -> ())? = nil, disposed: (() -> ())? = nil, next: (Value -> ())? = nil) -> Signal<Value, Error> {
return Signal { observer in
let disposable = CompositeDisposable()
_ = disposed.map(disposable.addDisposable)
disposable += signal.observe { receivedEvent in
event?(receivedEvent)
switch receivedEvent {
case let .Next(value):
next?(value)
case let .Failed(error):
failed?(error)
case .Completed:
completed?()
case .Interrupted:
interrupted?()
}
if receivedEvent.isTerminating {
terminated?()
}
observer.action(receivedEvent)
}
return disposable
}
}
}
private struct SampleState<Value> {
var latestValue: Value? = nil
var signalCompleted: Bool = false
var samplerCompleted: Bool = false
}
extension SignalType {
/// Forwards the latest value from `signal` whenever `sampler` sends a Next
/// event.
///
/// If `sampler` fires before a value has been observed on `signal`, nothing
/// happens.
///
/// Returns a signal that will send values from `signal`, sampled (possibly
/// multiple times) by `sampler`, then complete once both input signals have
/// completed, or interrupt if either input signal is interrupted.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func sampleOn(sampler: Signal<(), NoError>) -> Signal<Value, Error> {
return Signal { observer in
let state = Atomic(SampleState<Value>())
let disposable = CompositeDisposable()
disposable += self.observe { event in
switch event {
case let .Next(value):
state.modify { (var st) in
st.latestValue = value
return st
}
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
let oldState = state.modify { (var st) in
st.signalCompleted = true
return st
}
if oldState.samplerCompleted {
observer.sendCompleted()
}
case .Interrupted:
observer.sendInterrupted()
}
}
disposable += sampler.observe { event in
switch event {
case .Next:
if let value = state.value.latestValue {
observer.sendNext(value)
}
case .Completed:
let oldState = state.modify { (var st) in
st.samplerCompleted = true
return st
}
if oldState.signalCompleted {
observer.sendCompleted()
}
case .Interrupted:
observer.sendInterrupted()
default:
break
}
}
return disposable
}
}
/// Forwards events from `self` until `trigger` sends a Next or Completed
/// event, at which point the returned signal will complete.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func takeUntil(trigger: Signal<(), NoError>) -> Signal<Value, Error> {
return Signal { observer in
let disposable = CompositeDisposable()
disposable += self.observe(observer)
disposable += trigger.observe { event in
switch event {
case .Next, .Completed:
observer.sendCompleted()
case .Failed, .Interrupted:
break
}
}
return disposable
}
}
/// Does not forward any values from `self` until `trigger` sends a Next or
/// Completed event, at which point the returned signal behaves exactly like
/// `signal`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skipUntil(trigger: Signal<(), NoError>) -> Signal<Value, Error> {
return Signal { observer in
let disposable = SerialDisposable()
disposable.innerDisposable = trigger.observe { event in
switch event {
case .Next, .Completed:
disposable.innerDisposable = self.observe(observer)
case .Failed, .Interrupted:
break
}
}
return disposable
}
}
/// Forwards events from `self` with history: values of the returned signal
/// are a tuple whose first member is the previous value and whose second member
/// is the current value. `initial` is supplied as the first member when `self`
/// sends its first value.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combinePrevious(initial: Value) -> Signal<(Value, Value), Error> {
return scan((initial, initial)) { previousCombinedValues, newValue in
return (previousCombinedValues.1, newValue)
}
}
/// Like `scan`, but sends only the final value and then immediately completes.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func reduce<U>(initial: U, _ combine: (U, Value) -> U) -> Signal<U, Error> {
// We need to handle the special case in which `signal` sends no values.
// We'll do that by sending `initial` on the output signal (before taking
// the last value).
let (scannedSignalWithInitialValue, outputSignalObserver) = Signal<U, Error>.pipe()
let outputSignal = scannedSignalWithInitialValue.takeLast(1)
// Now that we've got takeLast() listening to the piped signal, send that initial value.
outputSignalObserver.sendNext(initial)
// Pipe the scanned input signal into the output signal.
scan(initial, combine).observe(outputSignalObserver)
return outputSignal
}
/// Aggregates `selfs`'s values into a single combined value. When `self` emits
/// its first value, `combine` is invoked with `initial` as the first argument and
/// that emitted value as the second argument. The result is emitted from the
/// signal returned from `scan`. That result is then passed to `combine` as the
/// first argument when the next value is emitted, and so on.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func scan<U>(initial: U, _ combine: (U, Value) -> U) -> Signal<U, Error> {
return Signal { observer in
var accumulator = initial
return self.observe { event in
observer.action(event.map { value in
accumulator = combine(accumulator, value)
return accumulator
})
}
}
}
}
extension SignalType where Value: Equatable {
/// Forwards only those values from `self` which are not duplicates of the
/// immedately preceding value. The first value is always forwarded.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skipRepeats() -> Signal<Value, Error> {
return skipRepeats(==)
}
}
extension SignalType {
/// Forwards only those values from `self` which do not pass `isRepeat` with
/// respect to the previous value. The first value is always forwarded.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skipRepeats(isRepeat: (Value, Value) -> Bool) -> Signal<Value, Error> {
return self
.map(Optional.init)
.combinePrevious(nil)
.filter { a, b in
if let a = a, b = b where isRepeat(a, b) {
return false
} else {
return true
}
}
.map { $0.1! }
}
/// Does not forward any values from `self` until `predicate` returns false,
/// at which point the returned signal behaves exactly like `signal`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skipWhile(predicate: Value -> Bool) -> Signal<Value, Error> {
return Signal { observer in
var shouldSkip = true
return self.observe { event in
switch event {
case let .Next(value):
shouldSkip = shouldSkip && predicate(value)
if !shouldSkip {
fallthrough
}
default:
observer.action(event)
}
}
}
}
/// Forwards events from `self` until `replacement` begins sending events.
///
/// Returns a signal which passes through `Next`, `Failed`, and `Interrupted`
/// events from `signal` until `replacement` sends an event, at which point the
/// returned signal will send that event and switch to passing through events
/// from `replacement` instead, regardless of whether `self` has sent events
/// already.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func takeUntilReplacement(replacement: Signal<Value, Error>) -> Signal<Value, Error> {
return Signal { observer in
let disposable = CompositeDisposable()
let signalDisposable = self.observe { event in
switch event {
case .Completed:
break
case .Next, .Failed, .Interrupted:
observer.action(event)
}
}
disposable += signalDisposable
disposable += replacement.observe { event in
signalDisposable?.dispose()
observer.action(event)
}
return disposable
}
}
/// Waits until `self` completes and then forwards the final `count` values
/// on the returned signal.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func takeLast(count: Int) -> Signal<Value, Error> {
return Signal { observer in
var buffer: [Value] = []
buffer.reserveCapacity(count)
return self.observe { event in
switch event {
case let .Next(value):
// To avoid exceeding the reserved capacity of the buffer, we remove then add.
// Remove elements until we have room to add one more.
while (buffer.count + 1) > count {
buffer.removeAtIndex(0)
}
buffer.append(value)
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
for bufferedValue in buffer {
observer.sendNext(bufferedValue)
}
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
/// Forwards any values from `self` until `predicate` returns false,
/// at which point the returned signal will complete.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func takeWhile(predicate: Value -> Bool) -> Signal<Value, Error> {
return Signal { observer in
return self.observe { event in
if case let .Next(value) = event where !predicate(value) {
observer.sendCompleted()
} else {
observer.action(event)
}
}
}
}
}
private struct ZipState<Value> {
var values: [Value] = []
var completed = false
var isFinished: Bool {
return values.isEmpty && completed
}
}
extension SignalType {
/// Zips elements of two signals into pairs. The elements of any Nth pair
/// are the Nth elements of the two input signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zipWith<U>(otherSignal: Signal<U, Error>) -> Signal<(Value, U), Error> {
return Signal { observer in
let states = Atomic(ZipState<Value>(), ZipState<U>())
let disposable = CompositeDisposable()
let flush = { () -> () in
var originalStates: (ZipState<Value>, ZipState<U>)!
states.modify { states in
originalStates = states
var updatedStates = states
let extractCount = min(states.0.values.count, states.1.values.count)
updatedStates.0.values.removeRange(0 ..< extractCount)
updatedStates.1.values.removeRange(0 ..< extractCount)
return updatedStates
}
while !originalStates.0.values.isEmpty && !originalStates.1.values.isEmpty {
let left = originalStates.0.values.removeAtIndex(0)
let right = originalStates.1.values.removeAtIndex(0)
observer.sendNext((left, right))
}
if originalStates.0.isFinished || originalStates.1.isFinished {
observer.sendCompleted()
}
}
let onFailed = { observer.sendFailed($0) }
let onInterrupted = { observer.sendInterrupted() }
disposable += self.observe { event in
switch event {
case let .Next(value):
states.modify { (var states) in
states.0.values.append(value)
return states
}
flush()
case let .Failed(error):
onFailed(error)
case .Completed:
states.modify { (var states) in
states.0.completed = true
return states
}
flush()
case .Interrupted:
onInterrupted()
}
}
disposable += otherSignal.observe { event in
switch event {
case let .Next(value):
states.modify { (var states) in
states.1.values.append(value)
return states
}
flush()
case let .Failed(error):
onFailed(error)
case .Completed:
states.modify { (var states) in
states.1.completed = true
return states
}
flush()
case .Interrupted:
onInterrupted()
}
}
return disposable
}
}
/// Applies `operation` to values from `self` with `Success`ful results
/// forwarded on the returned signal and `Failure`s sent as `Failed` events.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func attempt(operation: Value -> Result<(), Error>) -> Signal<Value, Error> {
return attemptMap { value in
return operation(value).map {
return value
}
}
}
/// Applies `operation` to values from `self` with `Success`ful results mapped
/// on the returned signal and `Failure`s sent as `Failed` events.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func attemptMap<U>(operation: Value -> Result<U, Error>) -> Signal<U, Error> {
return Signal { observer in
self.observe { event in
switch event {
case let .Next(value):
operation(value).analysis(ifSuccess: { value in
observer.sendNext(value)
}, ifFailure: { error in
observer.sendFailed(error)
})
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
/// Throttle values sent by the receiver, so that at least `interval`
/// seconds pass between each, then forwards them on the given scheduler.
///
/// If multiple values are received before the interval has elapsed, the
/// latest value is the one that will be passed on.
///
/// If the input signal terminates while a value is being throttled, that value
/// will be discarded and the returned signal will terminate immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func throttle(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer in
let state: Atomic<ThrottleState<Value>> = Atomic(ThrottleState())
let schedulerDisposable = SerialDisposable()
let disposable = CompositeDisposable()
disposable.addDisposable(schedulerDisposable)
disposable += self.observe { event in
if case let .Next(value) = event {
var scheduleDate: NSDate!
state.modify { (var state) in
state.pendingValue = value
let proposedScheduleDate = state.previousDate?.dateByAddingTimeInterval(interval) ?? scheduler.currentDate
scheduleDate = proposedScheduleDate.laterDate(scheduler.currentDate)
return state
}
schedulerDisposable.innerDisposable = scheduler.scheduleAfter(scheduleDate) {
let previousState = state.modify { (var state) in
if state.pendingValue != nil {
state.pendingValue = nil
state.previousDate = scheduleDate
}
return state
}
if let pendingValue = previousState.pendingValue {
observer.sendNext(pendingValue)
}
}
} else {
schedulerDisposable.innerDisposable = scheduler.schedule {
observer.action(event)
}
}
}
return disposable
}
}
}
private struct ThrottleState<Value> {
var previousDate: NSDate? = nil
var pendingValue: Value? = nil
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>) -> Signal<(A, B), Error> {
return a.combineLatestWith(b)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) -> Signal<(A, B, C), Error> {
return combineLatest(a, b)
.combineLatestWith(c)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) -> Signal<(A, B, C, D), Error> {
return combineLatest(a, b, c)
.combineLatestWith(d)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) -> Signal<(A, B, C, D, E), Error> {
return combineLatest(a, b, c, d)
.combineLatestWith(e)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) -> Signal<(A, B, C, D, E, F), Error> {
return combineLatest(a, b, c, d, e)
.combineLatestWith(f)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, G, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) -> Signal<(A, B, C, D, E, F, G), Error> {
return combineLatest(a, b, c, d, e, f)
.combineLatestWith(g)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, G, H, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) -> Signal<(A, B, C, D, E, F, G, H), Error> {
return combineLatest(a, b, c, d, e, f, g)
.combineLatestWith(h)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, G, H, I, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) -> Signal<(A, B, C, D, E, F, G, H, I), Error> {
return combineLatest(a, b, c, d, e, f, g, h)
.combineLatestWith(i)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, G, H, I, J, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) -> Signal<(A, B, C, D, E, F, G, H, I, J), Error> {
return combineLatest(a, b, c, d, e, f, g, h, i)
.combineLatestWith(j)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`. No events will be sent if the sequence is empty.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<S: SequenceType, Value, Error where S.Generator.Element == Signal<Value, Error>>(signals: S) -> Signal<[Value], Error> {
var generator = signals.generate()
if let first = generator.next() {
let initial = first.map { [$0] }
return GeneratorSequence(generator).reduce(initial) { signal, next in
signal.combineLatestWith(next).map { $0.0 + [$0.1] }
}
}
return .never
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>) -> Signal<(A, B), Error> {
return a.zipWith(b)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) -> Signal<(A, B, C), Error> {
return zip(a, b)
.zipWith(c)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) -> Signal<(A, B, C, D), Error> {
return zip(a, b, c)
.zipWith(d)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) -> Signal<(A, B, C, D, E), Error> {
return zip(a, b, c, d)
.zipWith(e)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) -> Signal<(A, B, C, D, E, F), Error> {
return zip(a, b, c, d, e)
.zipWith(f)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, G, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) -> Signal<(A, B, C, D, E, F, G), Error> {
return zip(a, b, c, d, e, f)
.zipWith(g)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, G, H, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) -> Signal<(A, B, C, D, E, F, G, H), Error> {
return zip(a, b, c, d, e, f, g)
.zipWith(h)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, G, H, I, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) -> Signal<(A, B, C, D, E, F, G, H, I), Error> {
return zip(a, b, c, d, e, f, g, h)
.zipWith(i)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, G, H, I, J, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) -> Signal<(A, B, C, D, E, F, G, H, I, J), Error> {
return zip(a, b, c, d, e, f, g, h, i)
.zipWith(j)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`. No events will be sent if the sequence is empty.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<S: SequenceType, Value, Error where S.Generator.Element == Signal<Value, Error>>(signals: S) -> Signal<[Value], Error> {
var generator = signals.generate()
if let first = generator.next() {
let initial = first.map { [$0] }
return GeneratorSequence(generator).reduce(initial) { signal, next in
signal.zipWith(next).map { $0.0 + [$0.1] }
}
}
return .never
}
extension SignalType {
/// Forwards events from `self` until `interval`. Then if signal isn't completed yet,
/// fails with `error` on `scheduler`.
///
/// If the interval is 0, the timeout will be scheduled immediately. The signal
/// must complete synchronously (or on a faster scheduler) to avoid the timeout.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func timeoutWithError(error: Error, afterInterval interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer in
let disposable = CompositeDisposable()
let date = scheduler.currentDate.dateByAddingTimeInterval(interval)
disposable += scheduler.scheduleAfter(date) {
observer.sendFailed(error)
}
disposable += self.observe(observer)
return disposable
}
}
}
extension SignalType where Error == NoError {
/// Promotes a signal that does not generate failures into one that can.
///
/// This does not actually cause failures to be generated for the given signal,
/// but makes it easier to combine with other signals that may fail; for
/// example, with operators like `combineLatestWith`, `zipWith`, `flatten`, etc.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func promoteErrors<F: ErrorType>(_: F.Type) -> Signal<Value, F> {
return Signal { observer in
return self.observe { event in
switch event {
case let .Next(value):
observer.sendNext(value)
case .Failed:
fatalError("NoError is impossible to construct")
case .Completed:
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
}
|
2f8666efc91bbf00922e331a1e1ddaf4
| 31.951486 | 341 | 0.680199 | false | false | false | false |
rambler-digital-solutions/rambler-it-ios
|
refs/heads/develop
|
Carthage/Checkouts/rides-ios-sdk/source/UberRides/OAuth/OAuthViewController.swift
|
mit
|
1
|
//
// OAuthViewController.swift
// UberRides
//
// Copyright © 2015 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
// MARK: View Controller Lifecycle
// View controller to users to enter credentials for OAuth.
@objc(UBSDKOAuthViewController)
class OAuthViewController: UIViewController {
var hasLoaded = false
var loginView: LoginView
/**
Initializes the web view controller with the necessary information.
- parameter loginAuthenticator: the login authentication process to use
- returns: An initialized OAuthWebViewController
*/
@objc init(loginAuthenticator: LoginViewAuthenticator) {
loginView = LoginView(loginAuthenticator: loginAuthenticator)
super.init(nibName: nil, bundle: nil)
}
@objc required init?(coder aDecoder: NSCoder) {
fatalError("initWithCoder: is not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = UIRectEdge()
self.view.addSubview(loginView)
self.setupLoginView()
// Set up navigation item
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel))
navigationItem.leftBarButtonItem = cancelButton
navigationItem.title = LocalizationUtil.localizedString(forKey: "Sign in with Uber", comment: "Title of navigation bar during OAuth")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if !hasLoaded {
self.loginView.load()
}
}
@objc func cancel() {
self.loginView.loginAuthenticator.loginCompletion?(nil, RidesAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .userCancelled))
dismiss(animated: true, completion: nil)
}
//MARK: View Setup
func setupLoginView() {
self.loginView.translatesAutoresizingMaskIntoConstraints = false
let views = ["loginView": self.loginView]
let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[loginView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[loginView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
self.view.addConstraints(horizontalConstraints)
self.view.addConstraints(verticalConstraints)
}
}
|
83743d0f4d0f898e12795affda00b051
| 40.147727 | 176 | 0.713615 | false | false | false | false |
TonyJin99/SinaWeibo
|
refs/heads/master
|
SinaWeibo/SinaWeibo/TJStatus.swift
|
apache-2.0
|
1
|
//
// TJStatus.swift
// SinaWeibo
//
// Created by Tony.Jin on 8/1/16.
// Copyright © 2016 Innovatis Tech. All rights reserved.
//
import UIKit
class TJStatus: NSObject{
var created_at: String? //微博创建时间
var idstr: String? //字符串型的微博ID
var text: String? //微博信息内容
var source: String? //微博来源
var user: TJUser? //微博作者的用户信息
var pic_urls: [[String: AnyObject]]? //配图数组
var retweeted_status : TJStatus? //转发微博
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
//KVC的setValuesForKeysWithDictionary方法内部会调用setValue方法
override func setValue(value: AnyObject?, forKey key: String) {
if key == "user"{
user = TJUser(dict: value as! [String : AnyObject])
return
}
if key == "retweeted_status"{
retweeted_status = TJStatus(dict: value as! [String : AnyObject])
return
}
super.setValue(value, forKey: key)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
override var description: String {
let property = ["created_at", "idstr", "text", "source"]
let dict = dictionaryWithValuesForKeys(property)
return "\(dict)"
}
}
|
74933361e2e19e0dcd21a093206a2dd9
| 24.627451 | 77 | 0.594491 | false | false | false | false |
mastahyeti/SoftU2F
|
refs/heads/master
|
SoftU2FTool/Keychain.swift
|
mit
|
2
|
//
// Keychain.swift
// SoftU2F
//
// Created by Benjamin P Toews on 2/2/17.
//
import Foundation
class Keychain {
// Get the number of keychain items with a given kSecAttrLabel.
static func count(attrLabel: CFString) -> Int? {
let query = makeCFDictionary(
(kSecClass, kSecClassKey),
(kSecAttrKeyType, kSecAttrKeyTypeEC),
(kSecAttrLabel, attrLabel),
(kSecReturnRef, kCFBooleanTrue),
(kSecMatchLimit, 100 as CFNumber)
)
var optionalOpaqueResult: CFTypeRef? = nil
let err = SecItemCopyMatching(query, &optionalOpaqueResult)
if err == errSecItemNotFound {
return 0
}
if err != errSecSuccess {
print("Error from keychain: \(err)")
return nil
}
guard let opaqueResult = optionalOpaqueResult else {
print("Unexpected nil returned from keychain")
return nil
}
let result = opaqueResult as! CFArray as [AnyObject]
return result.count
}
// Delete all keychain items matching the given query.
static func delete(_ query: CFDictionaryMember...) -> Bool {
let queryDict = makeCFDictionary(query)
let err = SecItemDelete(queryDict)
switch err {
case errSecSuccess:
return true
case errSecItemNotFound:
return false
default:
print("Error from keychain: \(err)")
return false
}
}
// Get the given attribute for the given SecKey.
static func getSecKeyAttr<T:AnyObject>(key: SecKey, attr name: CFString) -> T? {
guard let attrs = SecKeyCopyAttributes(key) as? [String: AnyObject] else {
return nil
}
guard let ret = attrs[name as String] as? T else {
return nil
}
return ret
}
// Get the given attribute for the SecItem with the given kSecAttrApplicationLabel.
static func getSecItemAttr<T>(attrAppLabel: CFData, name: CFString) -> T? {
let query = makeCFDictionary(
(kSecClass, kSecClassKey),
(kSecAttrKeyType, kSecAttrKeyTypeEC),
(kSecAttrKeyClass, kSecAttrKeyClassPrivate),
(kSecAttrApplicationLabel, attrAppLabel),
(kSecReturnAttributes, kCFBooleanTrue)
)
var optionalOpaqueDict: CFTypeRef? = nil
let err = SecItemCopyMatching(query, &optionalOpaqueDict)
if err != errSecSuccess {
print("Error from keychain: \(err)")
return nil
}
guard let opaqueDict = optionalOpaqueDict else {
print("Unexpected nil returned from keychain")
return nil
}
guard let dict = opaqueDict as! CFDictionary as? [String: AnyObject] else {
print("Error downcasting CFDictionary")
return nil
}
guard let opaqueResult = dict[name as String] else {
return nil
}
return opaqueResult as? T
}
// Get the given attribute for the SecItem with the given kSecAttrApplicationLabel.
static func setSecItemAttr<T:CFTypeRef>(attrAppLabel: CFData, name: CFString, value: T) -> Bool {
let query = makeCFDictionary(
(kSecClass, kSecClassKey),
(kSecAttrKeyType, kSecAttrKeyTypeEC),
(kSecAttrKeyClass, kSecAttrKeyClassPrivate),
(kSecAttrApplicationLabel, attrAppLabel)
)
let newAttrs = makeCFDictionary(
(name, value)
)
let err = SecItemUpdate(query, newAttrs)
if err != errSecSuccess {
print("Error from keychain: \(err)")
return false
}
return true
}
// Get the raw data from the key.
static func exportSecKey(_ key: SecKey) -> Data? {
var err: Unmanaged<CFError>? = nil
let data = SecKeyCopyExternalRepresentation(key, &err)
if err != nil {
print("Error exporting key")
return nil
}
return data as Data?
}
// Lookup all private keys with the given label.
static func getPrivateSecKeys(attrLabel: CFString) -> [SecKey] {
let query = makeCFDictionary(
(kSecClass, kSecClassKey),
(kSecAttrKeyType, kSecAttrKeyTypeEC),
(kSecAttrKeyClass, kSecAttrKeyClassPrivate),
(kSecAttrLabel, attrLabel),
(kSecReturnRef, kCFBooleanTrue),
(kSecMatchLimit, 1000 as CFNumber)
)
var optionalOpaqueResult: CFTypeRef? = nil
let err = SecItemCopyMatching(query, &optionalOpaqueResult)
if err == errSecItemNotFound {
return []
}
if err != errSecSuccess {
print("Error from keychain: \(err)")
return []
}
guard let opaqueResult = optionalOpaqueResult else {
print("Unexpected nil returned from keychain")
return []
}
let result = opaqueResult as! [SecKey]
return result
}
static func getPrivateSecKey(attrAppLabel: CFData, signPrompt: CFString) -> SecKey? {
let query = makeCFDictionary(
(kSecClass, kSecClassKey),
(kSecAttrKeyType, kSecAttrKeyTypeEC),
(kSecAttrKeyClass, kSecAttrKeyClassPrivate),
(kSecAttrApplicationLabel, attrAppLabel),
(kSecReturnRef, kCFBooleanTrue),
(kSecUseOperationPrompt, signPrompt as CFString)
)
var optionalOpaqueResult: CFTypeRef? = nil
let err = SecItemCopyMatching(query, &optionalOpaqueResult)
if err != errSecSuccess {
print("Error from keychain: \(err)")
return nil
}
guard let opaqueResult = optionalOpaqueResult else {
print("Unexpected nil returned from keychain")
return nil
}
let result = opaqueResult as! SecKey
return result
}
static func generateKeyPair(attrLabel: CFString, inSEP: Bool) -> (SecKey, SecKey)? {
// Make ACL controlling access to generated keys.
let acl: SecAccessControl?
var err: Unmanaged<CFError>? = nil
defer { err?.release() }
if inSEP {
if #available(OSX 10.12.1, *) {
acl = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlocked, [.privateKeyUsage, .touchIDAny], &err)
} else {
print("Cannot generate keys in SEP on macOS<10.12.1")
return nil
}
} else {
acl = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlocked, [], &err)
}
if acl == nil || err != nil {
print("Error generating ACL for key generation")
return nil
}
// Make parameters for generating keys.
let params: CFDictionary
if inSEP {
params = makeCFDictionary(
(kSecAttrKeyType, kSecAttrKeyTypeEC),
(kSecAttrKeySizeInBits, 256 as CFNumber),
(kSecAttrTokenID, kSecAttrTokenIDSecureEnclave),
(kSecPrivateKeyAttrs, makeCFDictionary(
(kSecAttrAccessControl, acl!),
(kSecAttrLabel, attrLabel),
(kSecAttrIsPermanent, kCFBooleanTrue),
(kSecAttrSynchronizable, kCFBooleanFalse)
))
)
} else {
params = makeCFDictionary(
(kSecAttrKeyType, kSecAttrKeyTypeEC),
(kSecAttrKeySizeInBits, 256 as CFNumber),
(kSecPrivateKeyAttrs, makeCFDictionary(
(kSecAttrAccessControl, acl!),
(kSecAttrLabel, attrLabel),
(kSecAttrIsPermanent, kCFBooleanTrue)
))
)
}
// Generate key pair.
var pub: SecKey? = nil
var priv: SecKey? = nil
let status = SecKeyGeneratePair(params, &pub, &priv)
if status != errSecSuccess {
print("Error calling SecKeyGeneratePair: \(status)")
return nil
}
if pub == nil || priv == nil {
print("Keys not returned from SecKeyGeneratePair")
return nil
}
return (pub!, priv!)
}
// Sign some data with the private key.
static func sign(key: SecKey, data: Data) -> Data? {
var err: Unmanaged<CFError>? = nil
defer { err?.release() }
let sig = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, &err) as Data?
if err != nil {
print("Error creating signature: \(err!.takeUnretainedValue().localizedDescription)")
return nil
}
return sig
}
// Verify some signature over some data with the public key.
static func verify(key: SecKey, data: Data, signature: Data) -> Bool {
var err: Unmanaged<CFError>? = nil
defer { err?.release() }
let ret = SecKeyVerifySignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, signature as CFData, &err)
if err != nil {
print("Error verifying signature: \(err!.takeUnretainedValue().localizedDescription)")
return false
}
return ret
}
// Previously, we had been storing both the public and private key in the keychain and
// using the application tag attribute on the public key for smuggling the U2F
// registration's counter. When generating a private key in the SEP, the public key
// isn't persisted in the keychain. From now on, we're using the application tag
// attribute on the private key for storing the counter and just deriving the public
// key from the private key whenever we need it. This function makes legacy keys
// consistent by deleting the public key from the keychain and copying its application
// tag into the private key.
static func repair(attrLabel: CFString) {
let query = makeCFDictionary(
(kSecClass, kSecClassKey),
(kSecAttrKeyType, kSecAttrKeyTypeEC),
(kSecAttrKeyClass, kSecAttrKeyClassPublic),
(kSecAttrLabel, attrLabel),
(kSecReturnAttributes, kCFBooleanTrue),
(kSecMatchLimit, 100 as CFNumber)
)
var optionalOpaqueResult: CFTypeRef? = nil
let err = SecItemCopyMatching(query, &optionalOpaqueResult)
if err == errSecItemNotFound {
return
}
if err != errSecSuccess {
print("Error from keychain: \(err)")
return
}
guard let opaqueResult = optionalOpaqueResult else {
print("Unexpected nil returned from keychain")
return
}
let publicKeys = opaqueResult as! [[String:AnyObject]]
publicKeys.forEach { publicKey in
print("Repairing one keypair")
guard let attrAppTag = publicKey[kSecAttrApplicationTag as String] as? Data else {
print("error getting kSecAttrApplicationTag for public key")
return
}
guard let attrAppLabel = publicKey[kSecAttrApplicationLabel as String] as? Data else {
print("error getting kSecAttrApplicationLabel for public key")
return
}
guard let _ = getPrivateSecKey(attrAppLabel: attrAppLabel as CFData, signPrompt: "" as CFString) else {
print("error getting private key for public key")
return
}
if !setSecItemAttr(attrAppLabel: attrAppLabel as CFData, name: kSecAttrApplicationTag, value: attrAppTag as CFData) {
print("Error copying kSecAttrApplicationTag to private key")
return
}
let ok = delete(
(kSecClass, kSecClassKey),
(kSecAttrKeyClass, kSecAttrKeyClassPublic),
(kSecAttrApplicationLabel, attrAppLabel as CFData)
)
if !ok {
print("Error deleting public keys")
return
}
print("Success")
}
}
}
|
175a28f3a6367b27d9ba60d34b8e3a58
| 32.56117 | 129 | 0.567715 | false | false | false | false |
jopamer/swift
|
refs/heads/master
|
test/DebugInfo/global_resilience.swift
|
apache-2.0
|
2
|
// RUN: %empty-directory(%t)
//
// Compile the external swift module.
// RUN: %target-swift-frontend -g -emit-module -enable-resilience \
// RUN: -emit-module-path=%t/resilient_struct.swiftmodule \
// RUN: -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
//
// RUN: %target-swift-frontend -g -I %t -emit-ir -enable-resilience %s -o - \
// RUN: | %FileCheck %s
import resilient_struct
// Fits in buffer
let small = Size(w: 1, h: 2)
// Needs out-of-line allocation
let large = Rectangle(p: Point(x: 1, y: 2), s: Size(w: 3, h: 4), color: 5)
// CHECK: @"$S17global_resilience5small16resilient_struct4SizeVvp" =
// CHECK-SAME: !dbg ![[SMALL:[0-9]+]]
// CHECK: @"$S17global_resilience5large16resilient_struct9RectangleVvp" =
// CHECK-SAME: !dbg ![[LARGE:[0-9]+]]
// CHECK: ![[SMALL]] = !DIGlobalVariableExpression(
// CHECK-SAME: expr: !DIExpression())
// CHECK: ![[LARGE]] = !DIGlobalVariableExpression(
// CHECK-SAME: expr: !DIExpression(DW_OP_deref))
|
c60777898b3334e70da9634ab2721236
| 35.962963 | 78 | 0.657315 | false | false | false | false |
AboutObjects/Modelmatic
|
refs/heads/master
|
Example/Modelmatic/DateTransformer.swift
|
mit
|
1
|
//
// Copyright (C) 2015 About Objects, Inc. All Rights Reserved.
// See LICENSE.txt for this example's licensing information.
//
import Foundation
@objc (MDLDateTransformer)
class DateTransformer: ValueTransformer
{
static let transformerName = NSValueTransformerName("Date")
override class func transformedValueClass() -> AnyClass { return NSString.self }
override class func allowsReverseTransformation() -> Bool { return true }
override func transformedValue(_ value: Any?) -> Any? {
guard let date = value as? Date else { return nil }
return serializedDateFormatter.string(from: date)
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
guard let stringVal = value as? String else { return nil }
return serializedDateFormatter.date(from: stringVal)
}
}
private let serializedDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
|
f889bd4425c1b54c66d38f1f56c768fa
| 31.419355 | 84 | 0.702488 | false | false | false | false |
liamnickell/inflation-calc
|
refs/heads/master
|
inflation-calc/InfCalcViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// inflation-calc
//
// Created by Liam Nickell on 7/2/16.
// Copyright © 2016 Liam Nickell. All rights reserved.
//
import UIKit
class InfCalcViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
@IBOutlet weak var calculationView: UIView!
@IBOutlet weak var calcBtn: UIButton!
@IBOutlet weak var inputTextField: UITextField!
@IBOutlet weak var currencySymbolLbl:UILabel!
@IBOutlet weak var textLbl: UILabel!
@IBOutlet weak var topPickerView: UIPickerView!
@IBOutlet weak var bottomPickerView: UIPickerView!
var years = [Int]()
var topYear = 2016
var bottomYear = 2016
var maxYear = 1774
var currencySymbol = ""
var reverseFileOrder = false
var isYen = false
var path = Bundle.main.path(forResource: "CPI-Data", ofType: "txt")
var percentChange = 0.0
var storedTextFieldContent = ""
var keyboardIsDark = false
var keyboardToolbarIsTranslucent = true
var doneBtnCalculates = false
let unknownError = UIAlertController(title: "Unknown Error", message: "An unknown error has occured. Please retry or restart the app.", preferredStyle: UIAlertControllerStyle.alert)
let invalidInput = UIAlertController(title: "Invalid Input", message: "Please input a valid number before attempting to calculate inflation.", preferredStyle: UIAlertControllerStyle.alert)
@IBAction func calculateInflation() {
findCpiData()
if let textFieldText = inputTextField.text, let textFieldAsDouble = Double(textFieldText) {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.currency
numberFormatter.currencySymbol = currencySymbol + " "
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 2
if percentChange > 0.0 {
if !isYen {
let value = textFieldAsDouble + (textFieldAsDouble * percentChange)
textLbl.text = numberFormatter.string(from: NSNumber(value: value))
} else {
let value = round(textFieldAsDouble + (textFieldAsDouble * percentChange))
numberFormatter.maximumFractionDigits = 0
textLbl.text = numberFormatter.string(from: NSNumber(value: value))
}
} else {
percentChange *= -1.0
if round((textFieldAsDouble - (textFieldAsDouble * percentChange)) * 100) / 100 > 0.0 {
if !isYen {
let value = textFieldAsDouble - (textFieldAsDouble * percentChange)
textLbl.text = numberFormatter.string(from: NSNumber(value: value))
} else {
let value = round(textFieldAsDouble - (textFieldAsDouble * percentChange))
numberFormatter.maximumFractionDigits = 0
textLbl.text = numberFormatter.string(from: NSNumber(value: value))
}
} else if !isYen {
textLbl.text = "0.00"
} else {
textLbl.text = "0"
}
}
UIView.animate(withDuration: 0.4, animations: {
self.calculationView.backgroundColor = UIColor(red: 0.0/255.0, green: 235.0/255.0, blue: 160.0/255.0, alpha: 1.0)
})
UIView.animate(withDuration: 0.6, animations: {
self.calculationView.backgroundColor = UIColor.white
})
} else {
self.present(invalidInput, animated: true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
calculationView.layer.cornerRadius = 6
calcBtn.layer.cornerRadius = 6
calculationView.layer.borderWidth = 1
calculationView.layer.borderColor = UIColor.lightGray.cgColor
for i in (maxYear...2016).reversed() {
years.append(i)
}
topPickerView.delegate = self
topPickerView.dataSource = self
bottomPickerView.delegate = self
bottomPickerView.dataSource = self
inputTextField.delegate = self
unknownError.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))
invalidInput.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))
textLbl.adjustsFontSizeToFitWidth = true
}
override func viewWillAppear(_ animated: Bool) {
currencySymbolLbl.text = currencySymbol
if keyboardIsDark {
inputTextField.keyboardAppearance = UIKeyboardAppearance.dark
} else {
inputTextField.keyboardAppearance = UIKeyboardAppearance.default
}
addKeyboardToolbar()
}
override func viewWillDisappear(_ animated: Bool) {
isYen = false
}
func findCpiData() {
do {
if let pathToFile = path {
let fileData = try String(contentsOfFile: pathToFile, encoding: String.Encoding.utf8)
var fileDataByLine: [String]
if reverseFileOrder {
fileDataByLine = fileData.components(separatedBy: CharacterSet.newlines).reversed()
} else {
fileDataByLine = fileData.components(separatedBy: CharacterSet.newlines)
}
if let initialCpi = Double(fileDataByLine[topYear-maxYear]), let finalCpi = Double(fileDataByLine[bottomYear-maxYear]) {
percentChange = (finalCpi - initialCpi) / initialCpi
}
} else {
self.present(unknownError, animated: true, completion: nil)
}
} catch let error as NSError {
print("\(error)")
self.present(unknownError, animated: true, completion: nil)
}
}
func addKeyboardToolbar() {
let toolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
if keyboardIsDark {
toolbar.barStyle = UIBarStyle.black
} else {
toolbar.barStyle = UIBarStyle.default
}
if keyboardToolbarIsTranslucent {
toolbar.isTranslucent = true
} else {
toolbar.isTranslucent = false
}
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let done = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(InfCalcViewController.doneBtnPressed))
let cancel = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(InfCalcViewController.cancelBtnPressed))
var items = [UIBarButtonItem]()
items.append(cancel)
items.append(flexSpace)
items.append(done)
toolbar.items = items
toolbar.isUserInteractionEnabled = true
toolbar.sizeToFit()
inputTextField.inputAccessoryView = toolbar
}
func doneBtnPressed() {
if let text = inputTextField.text {
storedTextFieldContent = text
}
if doneBtnCalculates {
calculateInflation()
}
self.view.endEditing(true)
}
func cancelBtnPressed() {
inputTextField.text = storedTextFieldContent
self.view.endEditing(true)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return years.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return String(years[row])
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == topPickerView {
topYear = years[row]
} else if pickerView == bottomPickerView {
bottomYear = years[row]
}
}
}
|
c62064763ae78b374089831602ada54c
| 36.561947 | 192 | 0.601555 | false | false | false | false |
darina/omim
|
refs/heads/master
|
iphone/Maps/Classes/Components/Modal/PromoBookingPresentationController.swift
|
apache-2.0
|
6
|
final class PromoBookingPresentationController: DimmedModalPresentationController {
let sideMargin: CGFloat = 32.0
let maxWidth: CGFloat = 310.0
override var frameOfPresentedViewInContainerView: CGRect {
let f = super.frameOfPresentedViewInContainerView
let estimatedWidth = min(maxWidth, f.width - (sideMargin * 2.0))
let s = presentedViewController.view.systemLayoutSizeFitting(CGSize(width: estimatedWidth, height: f.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultLow)
let r = CGRect(x: (f.width - s.width) / 2, y: (f.height - s.height) / 2, width: s.width, height: s.height)
return r
}
override func containerViewWillLayoutSubviews() {
presentedView?.frame = frameOfPresentedViewInContainerView
}
override func presentationTransitionWillBegin() {
super.presentationTransitionWillBegin()
presentedViewController.view.layer.cornerRadius = 8
presentedViewController.view.clipsToBounds = true
guard let containerView = containerView, let presentedView = presentedView else { return }
containerView.addSubview(presentedView)
presentedView.frame = frameOfPresentedViewInContainerView
}
override func dismissalTransitionDidEnd(_ completed: Bool) {
super.presentationTransitionDidEnd(completed)
guard let presentedView = presentedView else { return }
if completed {
presentedView.removeFromSuperview()
}
}
}
|
9380664a62c1a2be0dccbc3256e1d6c7
| 42.757576 | 193 | 0.763158 | false | false | false | false |
LeeMZC/MZCWB
|
refs/heads/master
|
MZCWB/MZCWB/Classes/login- 登录相关/Controller/MZCLoginTabBarViewController.swift
|
artistic-2.0
|
1
|
//
// MZCLoginTabBarViewController.swift
// MZCWB
//
// Created by 马纵驰 on 16/7/26.
// Copyright © 2016年 马纵驰. All rights reserved.
//
import UIKit
import QorumLogs
class MZCLoginTabBarViewController: MZCBaseTabBarViewController {
override func viewDidLoad() {
QL1("")
super.viewDidLoad()
setupLoginUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK:login登录界面
private func setupLoginUI(){
let homeViewController = MZCLoginViewController(type: MZCViewControllerType.MZCHome)
let messageViewController = MZCLoginViewController(type: MZCViewControllerType.MZCMessage)
let plazaViewController = MZCLoginViewController(type: MZCViewControllerType.MZCPlaza)
let meViewController = MZCLoginViewController(type: MZCViewControllerType.MZCMe)
let vcArr = [homeViewController,messageViewController,plazaViewController,meViewController]
add4ChildViewController(vcArr)
}
}
|
56e188afd4e7ead1d0c684375a72888c
| 28.513514 | 99 | 0.717033 | false | false | false | false |
jopamer/swift
|
refs/heads/master
|
stdlib/public/core/StringStorage.swift
|
apache-2.0
|
2
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
@_fixed_layout
@usableFromInline
class _SwiftRawStringStorage : _SwiftNativeNSString {
@nonobjc
@usableFromInline
final var capacity: Int
@nonobjc
@usableFromInline
final var count: Int
@nonobjc
internal init(_doNotCallMe: ()) {
_sanityCheckFailure("Use the create method")
}
@inlinable
@nonobjc
internal var rawStart: UnsafeMutableRawPointer {
_abstract()
}
@inlinable
@nonobjc
final var unusedCapacity: Int {
_sanityCheck(capacity >= count)
return capacity - count
}
}
internal typealias _ASCIIStringStorage = _SwiftStringStorage<UInt8>
@usableFromInline // FIXME(sil-serialize-all)
internal typealias _UTF16StringStorage = _SwiftStringStorage<UTF16.CodeUnit>
@_fixed_layout
@usableFromInline
final class _SwiftStringStorage<CodeUnit>
: _SwiftRawStringStorage, _NSStringCore
where CodeUnit : UnsignedInteger & FixedWidthInteger {
/// Create uninitialized storage of at least the specified capacity.
@usableFromInline
@nonobjc
@_specialize(where CodeUnit == UInt8)
@_specialize(where CodeUnit == UInt16)
internal static func create(
capacity: Int,
count: Int = 0
) -> _SwiftStringStorage<CodeUnit> {
_sanityCheck(count >= 0 && count <= capacity)
#if arch(i386) || arch(arm)
#else
// TODO(SR-7594): Restore below invariant
// _sanityCheck(
// CodeUnit.self != UInt8.self || capacity > _SmallUTF8String.capacity,
// "Should prefer a small representation")
#endif // 64-bit
let storage = Builtin.allocWithTailElems_1(
_SwiftStringStorage<CodeUnit>.self,
capacity._builtinWordValue, CodeUnit.self)
let storageAddr = UnsafeMutableRawPointer(
Builtin.bridgeToRawPointer(storage))
let endAddr = (
storageAddr + _stdlib_malloc_size(storageAddr)
).assumingMemoryBound(to: CodeUnit.self)
storage.capacity = endAddr - storage.start
storage.count = count
_sanityCheck(storage.capacity >= capacity)
return storage
}
@inlinable
@nonobjc
internal override final var rawStart: UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(start)
}
#if _runtime(_ObjC)
// NSString API
@objc(initWithCoder:)
@usableFromInline
convenience init(coder aDecoder: AnyObject) {
_sanityCheckFailure("init(coder:) not implemented for _SwiftStringStorage")
}
@objc(length)
@usableFromInline
var length: Int {
return count
}
@objc(characterAtIndex:)
@usableFromInline
func character(at index: Int) -> UInt16 {
defer { _fixLifetime(self) }
precondition(index >= 0 && index < count, "Index out of bounds")
return UInt16(start[index])
}
@objc(getCharacters:range:)
@usableFromInline
func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>,
range aRange: _SwiftNSRange
) {
_precondition(aRange.location >= 0 && aRange.length >= 0,
"Range out of bounds")
_precondition(aRange.location + aRange.length <= Int(count),
"Range out of bounds")
let slice = unmanagedView[
aRange.location ..< aRange.location + aRange.length]
slice._copy(
into: UnsafeMutableBufferPointer<UTF16.CodeUnit>(
start: buffer,
count: aRange.length))
_fixLifetime(self)
}
@objc(_fastCharacterContents)
@usableFromInline
func _fastCharacterContents() -> UnsafePointer<UInt16>? {
guard CodeUnit.self == UInt16.self else { return nil }
return UnsafePointer(rawStart.assumingMemoryBound(to: UInt16.self))
}
@objc(copyWithZone:)
@usableFromInline
func copy(with zone: _SwiftNSZone?) -> AnyObject {
// While _SwiftStringStorage instances aren't immutable in general,
// mutations may only occur when instances are uniquely referenced.
// Therefore, it is safe to return self here; any outstanding Objective-C
// reference will make the instance non-unique.
return self
}
#endif // _runtime(_ObjC)
}
extension _SwiftStringStorage {
// Basic properties
@inlinable
@nonobjc
internal final var start: UnsafeMutablePointer<CodeUnit> {
return UnsafeMutablePointer(Builtin.projectTailElems(self, CodeUnit.self))
}
@inlinable
@nonobjc
internal final var end: UnsafeMutablePointer<CodeUnit> {
return start + count
}
@inlinable
@nonobjc
internal final var capacityEnd: UnsafeMutablePointer<CodeUnit> {
return start + capacity
}
@inlinable
@nonobjc
var usedBuffer: UnsafeMutableBufferPointer<CodeUnit> {
return UnsafeMutableBufferPointer(start: start, count: count)
}
@inlinable
@nonobjc
var unusedBuffer: UnsafeMutableBufferPointer<CodeUnit> {
@inline(__always)
get {
return UnsafeMutableBufferPointer(start: end, count: capacity - count)
}
}
@inlinable
@nonobjc
var unmanagedView: _UnmanagedString<CodeUnit> {
return _UnmanagedString(start: self.start, count: self.count)
}
}
extension _SwiftStringStorage {
// Append operations
@nonobjc
internal final func _appendInPlace<OtherCodeUnit>(
_ other: _UnmanagedString<OtherCodeUnit>
)
where OtherCodeUnit : FixedWidthInteger & UnsignedInteger {
let otherCount = Int(other.count)
_sanityCheck(self.count + otherCount <= self.capacity)
other._copy(into: self.unusedBuffer)
self.count += otherCount
}
@nonobjc
internal final func _appendInPlace(_ other: _UnmanagedOpaqueString) {
let otherCount = Int(other.count)
_sanityCheck(self.count + otherCount <= self.capacity)
other._copy(into: self.unusedBuffer)
self.count += otherCount
}
@nonobjc
internal final func _appendInPlace<C: Collection>(contentsOf other: C)
where C.Element == CodeUnit {
let otherCount = Int(other.count)
_sanityCheck(self.count + otherCount <= self.capacity)
var (remainder, writtenUpTo) =
other._copyContents(initializing: self.unusedBuffer)
_precondition(remainder.next() == nil, "Collection underreported its count")
_precondition(writtenUpTo == otherCount, "Collection misreported its count")
count += otherCount
}
@_specialize(where C == Character._SmallUTF16, CodeUnit == UInt8)
@nonobjc
internal final func _appendInPlaceUTF16<C: Collection>(contentsOf other: C)
where C.Element == UInt16 {
let otherCount = Int(other.count)
_sanityCheck(self.count + otherCount <= self.capacity)
// TODO: Use _copyContents(initializing:) for UTF16->UTF16 case
var it = other.makeIterator()
for p in end ..< end + otherCount {
p.pointee = CodeUnit(it.next()!)
}
_precondition(it.next() == nil, "Collection underreported its count")
count += otherCount
}
}
extension _SwiftStringStorage {
@nonobjc
internal final func _appendInPlace(_ other: _StringGuts, range: Range<Int>) {
if _slowPath(other._isOpaque) {
_opaqueAppendInPlace(opaqueOther: other, range: range)
return
}
defer { _fixLifetime(other) }
if other.isASCII {
_appendInPlace(other._unmanagedASCIIView[range])
} else {
_appendInPlace(other._unmanagedUTF16View[range])
}
}
@usableFromInline // @opaque
internal final func _opaqueAppendInPlace(
opaqueOther other: _StringGuts, range: Range<Int>
) {
_sanityCheck(other._isOpaque)
if other._isSmall {
other._smallUTF8String[range].withUnmanagedUTF16 {
self._appendInPlace($0)
}
return
}
defer { _fixLifetime(other) }
_appendInPlace(other._asOpaque()[range])
}
@nonobjc
internal final func _appendInPlace(_ other: _StringGuts) {
if _slowPath(other._isOpaque) {
_opaqueAppendInPlace(opaqueOther: other)
return
}
defer { _fixLifetime(other) }
if other.isASCII {
_appendInPlace(other._unmanagedASCIIView)
} else {
_appendInPlace(other._unmanagedUTF16View)
}
}
@usableFromInline // @opaque
internal final func _opaqueAppendInPlace(opaqueOther other: _StringGuts) {
_sanityCheck(other._isOpaque)
if other._isSmall {
other._smallUTF8String.withUnmanagedUTF16 {
self._appendInPlace($0)
}
return
}
defer { _fixLifetime(other) }
_appendInPlace(other._asOpaque())
}
@nonobjc
internal final func _appendInPlace(_ other: String) {
self._appendInPlace(other._guts)
}
@nonobjc
internal final func _appendInPlace<S : StringProtocol>(_ other: S) {
self._appendInPlace(
other._wholeString._guts,
range: other._encodedOffsetRange)
}
}
|
e3f7cb0d3cb8c5cd109727fe30dc7ce9
| 27.021944 | 80 | 0.685423 | false | false | false | false |
KieranHarper/Yakka
|
refs/heads/master
|
Sources/TaskRetryHelper.swift
|
mit
|
1
|
//
// TaskRetryHelper.swift
// Yakka
//
// Created by Kieran Harper on 29/1/17.
//
//
import Foundation
import Dispatch
/// Helper class that provides a means to retry something up to a limit, and according to a wait schedule
public final class TaskRetryHelper {
// MARK: - Properties
/// The timeline of inter-attempt wait durations that was provided on construction
public let waitTimeline: [TimeInterval]
/// The maximum number of retries this will allow
public var maxNumRetries: Int {
return waitTimeline.count
}
/// Number of remaining retry attempts before this will elect to fail instead
public private(set) var remainingNumRetries: Int
// MARK: - Instance methods
/// Construct with a wait timeline to use, which defines which delay to use for each retry attempt and how many are allowed
public init(waitTimeline: [TimeInterval]) {
self.waitTimeline = waitTimeline
self.remainingNumRetries = waitTimeline.count
}
/// Perform a time delayed retry if it hasn't maxxed them out already, otherwise perform some give-up code
public func retryOrNah(onQueue queue: DispatchQueue = DispatchQueue.main, retry: @escaping ()->(), nah: @escaping ()->()) {
if remainingNumRetries > 0 {
let wait = waitTimeline[maxNumRetries - remainingNumRetries]
remainingNumRetries = remainingNumRetries - 1
queue.asyncAfter(deadline: .now() + wait) {
retry()
}
} else {
queue.async {
nah()
}
}
}
// MARK: - Static helpers
public class func exponentialBackoffTimeline(forMaxRetries maxRetries: Int, startingAt initialWait: TimeInterval) -> [TimeInterval] {
var toReturn = Array<TimeInterval>()
toReturn.append(max(initialWait, 0.0))
for ii in 1..<maxRetries {
var next = toReturn[ii - 1] * 2.0
if next == 0.0 {
next = 1.0
}
toReturn.append(next)
}
return toReturn
}
}
|
414f1af66c5953f432610342668c4496
| 28.405405 | 137 | 0.607077 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/CryptoAssets/Sources/EthereumKit/Models/Transactions/EthereumTransactionCandidate.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BigInt
import Foundation
public struct EthereumTransactionCandidate: Equatable {
public enum TransferType: Equatable {
case transfer(data: Data? = nil)
case erc20Transfer(contract: EthereumAddress, addressReference: EthereumAddress? = nil)
}
let to: EthereumAddress
let gasPrice: BigUInt
let gasLimit: BigUInt
let value: BigUInt
let nonce: BigUInt
let chainID: BigUInt
let transferType: TransferType
init(
to: EthereumAddress,
gasPrice: BigUInt,
gasLimit: BigUInt,
value: BigUInt,
nonce: BigUInt,
chainID: BigUInt,
transferType: TransferType
) {
self.to = to
self.gasPrice = gasPrice
self.gasLimit = gasLimit
self.value = value
self.nonce = nonce
self.chainID = chainID
self.transferType = transferType
}
}
|
4ac6c3bd3f3f0eac7bd3f7232c435b53
| 24.864865 | 95 | 0.645768 | false | false | false | false |
Tomikes/eidolon
|
refs/heads/master
|
Kiosk/Bid Fulfillment/LoadingViewModel.swift
|
mit
|
4
|
import Foundation
import ARAnalytics
import ReactiveCocoa
import Swift_RAC_Macros
/// Encapsulates activities of the LoadingViewController.
class LoadingViewModel: NSObject {
let placingBid: Bool
let bidderNetworkModel: BidderNetworkModel
lazy var placeBidNetworkModel: PlaceBidNetworkModel = {
return PlaceBidNetworkModel(fulfillmentController: self.bidderNetworkModel.fulfillmentController)
}()
lazy var bidCheckingModel: BidCheckingNetworkModel = { () -> BidCheckingNetworkModel in
return BidCheckingNetworkModel(fulfillmentController: self.bidderNetworkModel.fulfillmentController)
}()
dynamic var createdNewBidder = false
dynamic var bidIsResolved = false
dynamic var isHighestBidder = false
dynamic var reserveNotMet = false
var bidDetails: BidDetails {
return bidderNetworkModel.fulfillmentController.bidDetails
}
init(bidNetworkModel: BidderNetworkModel, placingBid: Bool) {
self.bidderNetworkModel = bidNetworkModel
self.placingBid = placingBid
super.init()
RAC(self, "createdNewBidder") <~ RACObserve(bidderNetworkModel, "createdNewBidder")
RAC(self, "bidIsResolved") <~ RACObserve(bidCheckingModel, "bidIsResolved")
RAC(self, "isHighestBidder") <~ RACObserve(bidCheckingModel, "isHighestBidder")
RAC(self, "reserveNotMet") <~ RACObserve(bidCheckingModel, "reserveNotMet")
}
/// Encapsulates essential activities of the LoadingViewController, including:
/// - Registering new users
/// - Placing bids for users
/// - Polling for bid results
func performActions() -> RACSignal {
return bidderNetworkModel.createOrGetBidder().then { [weak self] () -> RACSignal in
if self?.placingBid == false {
ARAnalytics.event("Registered New User Only")
return RACSignal.empty()
}
if let strongSelf = self {
ARAnalytics.event("Started Placing Bid")
return strongSelf.placeBidNetworkModel.bidSignal(strongSelf.bidderNetworkModel.fulfillmentController.bidDetails)
} else {
return RACSignal.empty()
}
}.then { [weak self] (_) in
if self == nil || self?.placingBid == false {
return RACSignal.empty()
}
return self!.bidCheckingModel.waitForBidResolution()
}
}
}
|
ff0bb9f4554a48e1dd298ce2aa28e171
| 36.723077 | 128 | 0.673328 | false | false | false | false |
wowiwj/WDayDayCook
|
refs/heads/master
|
WDayDayCook/WDayDayCook/Controllers/Discover/DiscoverViewController.swift
|
mit
|
1
|
//
// DiscoverViewController.swift
// WDayDayCook
//
// Created by wangju on 16/8/20.
// Copyright © 2016年 wangju. All rights reserved.
//
import UIKit
import SDCycleScrollView
import Alamofire
import SwiftyJSON
import ObjectMapper
import AlamofireObjectMapper
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
private let RecipeDiscussCellId = "RecipeDiscussCell"
private let reusableHeaderViewID = "DiscoverHeaderView"
class DiscoverViewController: UICollectionViewController {
fileprivate lazy var cycleView:SDCycleScrollView = {
let placeholderImage = UIImage(named: "default_1~iphone")!
let screenSize = UIScreen.main.bounds.size
let headerW = screenSize.width
let headerH = headerW / placeholderImage.size.width * placeholderImage.size.height
let size = CGSize(width: headerW, height: headerH)
let cycleView = SDCycleScrollView(frame: CGRect(origin: CGPoint.zero, size: size), delegate: self, placeholderImage: placeholderImage)
return cycleView!
}()
var recipeList:ThemeRecipeList?{
didSet{
guard let recipeList = recipeList else{
return
}
self.themeRecipes = recipeList.themeRecipes.sorted { (theme1, theme2) -> Bool in
return theme1.locationId < theme2.locationId
}
self.headerRecipes = recipeList.headerRecipes
}
}
var themeRecipes:[ThemeRecipe]?{
didSet{
collectionView?.reloadData()
}
}
var headerRecipes:[ThemeRecipe]?{
didSet{
guard let headerRecipes = headerRecipes else{
return
}
cycleView.imageURLStringsGroup = headerRecipes.map{$0.image_url!}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// MARK: - 代理测试
// self.collectionView?.emptyDataSetDataSource = self
MakeUI()
collectionView?.addHeaderWithCallback({
self.loadDatda()
})
collectionView?.headerBeginRefreshing()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
}
func MakeUI()
{
func setLayout()
{
let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
let screenSize = UIScreen.main.bounds.size
let width = (screenSize.width - WDConfig.discoverDefaultMargin) * 0.5
let height = width
layout.itemSize = CGSize(width: width, height: height)
layout.minimumLineSpacing = WDConfig.discoverDefaultMargin
layout.minimumInteritemSpacing = WDConfig.discoverDefaultMargin
layout.sectionInset = UIEdgeInsets(top: WDConfig.discoverDefaultMargin, left: 0, bottom: 0, right: 0)
layout.headerReferenceSize = cycleView.frame.size
}
setLayout()
collectionView?.register(UINib(nibName: RecipeDiscussCellId, bundle: nil), forCellWithReuseIdentifier: RecipeDiscussCellId)
self.collectionView?.backgroundColor = UIColor.white
}
func loadDatda()
{
Alamofire.request(Router.moreThemeRecipe(parameters: nil)).responseObject { (response:DataResponse<ThemeRecipeList>) in
self.collectionView!.headerEndRefreshing()
if response.result.isFailure
{
print(response.result.error)
return
}else
{
let recipeList = response.result.value
self.recipeList = recipeList
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - 控制器跳转
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier else{
return
}
if identifier == "showDetail" {
let vc = segue.destination as! ShowDetailViewController
let item = sender as! Int
vc.id = item
}
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return themeRecipes?.count ?? 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RecipeDiscussCellId, for: indexPath)
return cell
}
override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let cell = cell as? RecipeDiscussCell else {
return
}
if let themeRecipes = themeRecipes {
cell.themeRecipe = themeRecipes[(indexPath as NSIndexPath).item]
}
}
override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
var reusableHeaderView:UICollectionReusableView? = nil
if kind == "UICollectionElementKindSectionHeader" {
reusableHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: reusableHeaderViewID, for: indexPath)
reusableHeaderView?.addSubview(cycleView)
}
return reusableHeaderView ?? UICollectionReusableView()
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let themeRecipes = themeRecipes else{
return
}
let headerRecipe = themeRecipes[(indexPath as NSIndexPath).item]
if let id = headerRecipe.recipe_id {
performSegue(withIdentifier: "showDetail", sender: id)
}
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
}
extension DiscoverViewController: SDCycleScrollViewDelegate
{
func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {
guard let headerRecipes = headerRecipes else{
return
}
let headerRecipe = headerRecipes[index]
if let id = headerRecipe.recipe_id {
performSegue(withIdentifier: "showDetail", sender: id)
}
}
}
|
d48d24c790e22f658178a79b87c7065b
| 30.383764 | 185 | 0.640094 | false | false | false | false |
thatseeyou/SpriteKitExamples.playground
|
refs/heads/master
|
Pages/Rolling Circle.xcplaygroundpage/Contents.swift
|
isc
|
1
|
/*:
### UIBezierPath를 이용해서 SKShapeNode를 만들 수 있다.
*/
import UIKit
import SpriteKit
class GameScene: SKScene {
var contentCreated = false
let pi:CGFloat = CGFloat(M_PI)
override func didMove(to view: SKView) {
if self.contentCreated != true {
do {
let shape = SKShapeNode(path: makeHalfCircle().cgPath)
shape.strokeColor = SKColor.green
shape.fillColor = SKColor.red
shape.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
shape.physicsBody = SKPhysicsBody(polygonFrom: makeHalfCircle().cgPath)
shape.physicsBody?.isDynamic = true
shape.physicsBody?.pinned = true
shape.physicsBody?.affectedByGravity = false
shape.physicsBody?.friction = 1.0
addChild(shape)
shape.run(angularImpulse())
}
addBall(CGPoint(x: self.frame.midX, y: self.frame.midY))
addBall(CGPoint(x: self.frame.midX - 40, y: self.frame.midY))
addBall(CGPoint(x: self.frame.midX + 50, y: self.frame.midY))
self.physicsWorld.speed = 0.2
//self.physicsWorld.gravity = CGVectorMake(0, -9)
self.contentCreated = true
}
}
func addBall(_ position:CGPoint) {
let ball = SKShapeNode(circleOfRadius: 10.0)
ball.position = position
ball.physicsBody = SKPhysicsBody(circleOfRadius: 10.0)
ball.physicsBody?.friction = 1.0
ball.physicsBody?.density = 0.1
addChild(ball)
let label = SKLabelNode(text: "45")
ball.addChild(label)
}
func makeHalfCircle() -> UIBezierPath {
// CGPath가 되면 X축을 중심으로 flipping
// physicsBody에 사용하기 위해서는 clockwise가 되도록 하는 것이 좋다. Flipping이 되면서 counter clockwise가 된다.
// bezierPathByReversingPath를 사용해서 변경하는 것도 가능하다.
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 110.0, y: 0.0))
bezierPath.addArc(withCenter: CGPoint(x: 0.0, y: 0.0), radius: 100.0, startAngle: 2.0 * pi, endAngle: pi, clockwise: false)
//bezierPath.addLineToPoint(CGPointMake(110, 0.0))
bezierPath.addArc(withCenter: CGPoint(x: 0.0, y: 0.0), radius: 110.0, startAngle: pi, endAngle: 2.0 * pi, clockwise: true)
bezierPath.close()
return bezierPath
}
func angularImpulse() -> SKAction {
let waitAction = SKAction.wait(forDuration: 2.0)
let impulse = SKAction.applyAngularImpulse(0.3, duration: 1.0)
let all = SKAction.sequence([waitAction, impulse])
return all
}
func rotation() -> SKAction {
let waitAction = SKAction.wait(forDuration: 2.0)
let rotate = SKAction.rotate(byAngle: pi * 0.25, duration: 1.0)
let revereRotate = rotate.reversed()
let rocking = SKAction.sequence([rotate, revereRotate])
let repeatAction = SKAction.repeatForever(rocking)
let all = SKAction.sequence([waitAction, repeatAction])
return all
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// add SKView
do {
let skView = SKView(frame:CGRect(x: 0, y: 0, width: 320, height: 480))
skView.showsFPS = true
//skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
let scene = GameScene(size: CGSize(width: 320, height: 480))
scene.scaleMode = .aspectFit
skView.presentScene(scene)
self.view.addSubview(skView)
}
}
}
PlaygroundHelper.showViewController(ViewController())
|
00c70b5dcdcf8fb0283ddb692cc052e7
| 30.836207 | 131 | 0.607095 | false | false | false | false |
alvaromb/EventBlankApp
|
refs/heads/master
|
EventBlank/EventBlank/ViewControllers/Feed/PhotoPopupView.swift
|
mit
|
1
|
//
// PhotoPopupView.swift
// EventBlank
//
// Created by Marin Todorov on 8/23/15.
// Copyright (c) 2015 Underplot ltd. All rights reserved.
//
import UIKit
import Haneke
class PhotoPopupView: UIView {
static func showImage(image: UIImage, inView: UIView) {
let popup = PhotoPopupView()
inView.addSubview(popup)
popup.photo = image
}
static func showImageWithUrl(url: NSURL, inView: UIView) {
let popup = PhotoPopupView()
inView.addSubview(popup)
popup.photoUrl = url
}
func hideImage() {
didTapPhoto(UITapGestureRecognizer()) //hack
}
//UIViewController.alert("Couldn't fetch image. \(error.localizedDescription)", buttons: ["Close"], completion: {
//self.hideImage()
//});
var photoUrl: NSURL! {
didSet {
imgView.hnk_setImageFromURL(photoUrl, placeholder: nil, format: nil, failure: {error in
UIViewController.alert("Couldn't fetch image. \(error)", buttons: ["Close"], completion: {_ in
self.hideImage()
})
}, success: {[weak self]image in
self?.imgView.image = image
if self?.spinner != nil {
self?.spinner.removeFromSuperview()
}
})
}
}
var photo: UIImage! {
didSet {
imgView.image = photo
}
}
var imgView: UIImageView!
var spinner: UIActivityIndicatorView!
override func didMoveToSuperview() {
super.didMoveToSuperview()
if superview == nil {
return
}
frame = superview!.bounds
//add background
let backdrop = UIView(frame: bounds)
backdrop.backgroundColor = UIColor(white: 0.0, alpha: 0.8)
addSubview(backdrop)
//spinner
spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
spinner.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
spinner.center = center
spinner.startAnimating()
spinner.backgroundColor = UIColor.whiteColor()
spinner.layer.masksToBounds = true
spinner.layer.cornerRadius = 5
backdrop.addSubview(spinner)
//add image view
imgView = UIImageView()
imgView.frame = CGRectInset(bounds, 20, 40)
imgView.layer.cornerRadius = 10
imgView.clipsToBounds = true
imgView.contentMode = .ScaleAspectFit
imgView.alpha = 0
backdrop.addSubview(imgView)
imgView.userInteractionEnabled = true
imgView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "didTapPhoto:"))
let swipeDown = UISwipeGestureRecognizer(target: self, action: "didSwipePhoto:")
swipeDown.direction = .Down
imgView.addGestureRecognizer(swipeDown)
let swipeUp = UISwipeGestureRecognizer(target: self, action: "didSwipePhoto:")
swipeUp.direction = .Up
imgView.addGestureRecognizer(swipeUp)
UIView.animateWithDuration(0.67, delay: 0.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.imgView.alpha = 1.0
}, completion: nil)
UIView.animateWithDuration(0.67, delay: 0.0, usingSpringWithDamping: 0.33, initialSpringVelocity: 0, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
let yDelta = ((UIApplication.sharedApplication().windows.first! as! UIWindow).rootViewController as! UITabBarController).tabBar.frame.size.height/2
self.imgView.center.y -= yDelta
self.spinner.center.y -= yDelta
}, completion: nil)
}
func didTapPhoto(tap: UIGestureRecognizer) {
imgView.userInteractionEnabled = false
UIView.animateWithDuration(0.4, delay: 0.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.alpha = 0
}, completion: {_ in
self.removeFromSuperview()
})
}
func didSwipePhoto(swipe: UISwipeGestureRecognizer) {
imgView.userInteractionEnabled = false
UIView.animateWithDuration(0.4, delay: 0.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.imgView.center.y += (swipe.direction == .Down ? 1 : -1) * ((UIApplication.sharedApplication().windows.first! as! UIWindow).rootViewController as! UITabBarController).tabBar.frame.size.height/2
self.alpha = 0
}, completion: {_ in
self.removeFromSuperview()
})
}
}
|
e34b5c12f8dcd53ba2c2c1bb52a91b34
| 33.766423 | 209 | 0.609828 | false | false | false | false |
rivetlogic/liferay-mobile-directory-ios
|
refs/heads/master
|
Liferay-Screens/Source/DDL/Model/DDLField+DataType.swift
|
gpl-3.0
|
1
|
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library 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 Lesser General Public License for more
* details.
*/
import Foundation
extension DDLField {
public enum DataType: String {
case DDLBoolean = "boolean"
case DDLString = "string"
case DDLDate = "date"
case DDLInteger = "integer"
case DDLNumber = "number"
case DDLDouble = "double"
case DDLDocument = "document-library"
case Unsupported = ""
public static func from(#xmlElement:SMXMLElement) -> DataType {
return DataType(rawValue: xmlElement.attributeNamed("dataType") ?? "") ?? .Unsupported
}
public func createField(
#attributes:[String:AnyObject],
locale: NSLocale)
-> DDLField? {
switch self {
case .DDLBoolean:
return DDLFieldBoolean(
attributes:attributes,
locale: locale)
case .DDLString:
switch DDLField.Editor.from(attributes: attributes) {
case .Select, .Radio:
return DDLFieldStringWithOptions(
attributes: attributes,
locale: locale)
default:
return DDLFieldString(
attributes:attributes,
locale: locale)
}
case .DDLDate:
return DDLFieldDate(
attributes:attributes,
locale: locale)
case .DDLInteger, .DDLNumber, .DDLDouble:
return DDLFieldNumber(
attributes:attributes,
locale: locale)
case .DDLDocument:
return DDLFieldDocument(
attributes:attributes,
locale: locale)
default: ()
}
return nil
}
}
}
|
e10d6a3ecbc7fe30e1e50e417ad0382c
| 23.675 | 89 | 0.680851 | false | false | false | false |
auth0/Lock.iOS-OSX
|
refs/heads/master
|
LockTests/Models/RuleSpec.swift
|
mit
|
2
|
// RuleSpec.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Quick
import Nimble
@testable import Lock
class RuleSpec: QuickSpec {
override func spec() {
describe("length") {
let message = "length"
it("should pass message in result") {
let rule = withPassword(lengthInRange: 1...10, message: message)
expect(rule.evaluate(on: "password").message) == message
}
it("should validate length with range") {
let rule = withPassword(lengthInRange: 1...10, message: message)
expect(rule.evaluate(on: "password").valid) == true
}
it("should fail when length is smaller than desired") {
let rule = withPassword(lengthInRange: 8...10, message: message)
expect(rule.evaluate(on: "short").valid) == false
}
it("should fail when length is greater than desired") {
let rule = withPassword(lengthInRange: 1...4, message: message)
expect(rule.evaluate(on: "longpassword").valid) == false
}
it("should fail with nil") {
let rule = withPassword(lengthInRange: 1...4, message: message)
expect(rule.evaluate(on: nil).valid) == false
}
}
describe("character set") {
let rule = withPassword(havingCharactersIn: .alphanumerics, message: "character set")
it("should pass message in result") {
expect(rule.evaluate(on: "password").message) == "character set"
}
it("should allow valid characters") {
expect(rule.evaluate(on: "should match this 1 password").valid) == true
}
it("should fail whe no valid character is found") {
expect(rule.evaluate(on: "#@&$)*@#()*$)(#*)$@#*").valid) == false
}
it("should fail with nil") {
expect(rule.evaluate(on: nil).valid) == false
}
}
describe("consecutive repeats") {
let rule = withPassword(havingMaxConsecutiveRepeats: 2, message: "no repeats")
it("should pass message in result") {
expect(rule.evaluate(on: "password").message) == "no repeats"
}
it("should allow string with no repeating count") {
expect(rule.evaluate(on: "1234567890").valid) == true
}
it("should allow string with max repeating count") {
expect(rule.evaluate(on: "12234567890").valid) == true
}
it("should fail with nil") {
expect(rule.evaluate(on: nil).valid) == false
}
it("should detect repeating characters") {
expect(rule.evaluate(on: "123455567890").valid) == false
}
it("should detect at least one repeating characters") {
expect(rule.evaluate(on: "1222222345567890").valid) == false
}
}
describe("at least rule") {
let valid = MockRule(valid: true)
let invalid = MockRule(valid: false)
let password = "a password"
it("should pass message in result") {
let rule = AtLeastRule(minimum: 1, rules: [valid], message: "only one")
expect(rule.evaluate(on: "password").message) == "only one"
}
it("should have conditions") {
let rule = AtLeastRule(minimum: 1, rules: [valid, invalid], message: "only one")
let result = rule.evaluate(on: "password")
expect(result.conditions).to(haveCount(2))
expect(result.conditions[0].valid) == true
expect(result.conditions[1].valid) == false
}
it("should be valid for only one") {
let rule = AtLeastRule(minimum: 1, rules: [valid], message: "only one")
expect(rule.evaluate(on: password).valid) == true
}
it("should be valid when the minimum valid quote is reached") {
let rule = AtLeastRule(minimum: 1, rules: [valid, invalid, invalid], message: "only one")
expect(rule.evaluate(on: password).valid) == true
}
it("should be invalid when minimum of valid rules is not reached") {
let rule = AtLeastRule(minimum: Int.max, rules: [valid, invalid, invalid], message: "impossible")
expect(rule.evaluate(on: password).valid) == false
}
}
}
}
struct MockRule: Rule {
let valid: Bool
let message = "MOCK"
func evaluate(on password: String?) -> RuleResult {
return SimpleRule.Result(message: message, valid: valid)
}
}
|
a54ed7565dc32ef093b75f7b1d53a617
| 35.648148 | 113 | 0.579586 | false | false | false | false |
inacioferrarini/York
|
refs/heads/master
|
Classes/DataSyncRules/Entities/EntityDailySyncRule.swift
|
mit
|
1
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Inácio Ferrarini
//
// 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
open class EntityDailySyncRule: EntityBaseSyncRules {
open class func fetchEntityDailySyncRuleByName(_ name: String, inManagedObjectContext context: NSManagedObjectContext) -> EntityDailySyncRule? {
guard name.characters.count > 0 else {
return nil
}
let request: NSFetchRequest = NSFetchRequest<EntityDailySyncRule>(entityName: self.simpleClassName())
request.predicate = NSPredicate(format: "name = %@", name)
return self.lastObjectFromRequest(request, inManagedObjectContext: context)
}
open class func entityDailySyncRuleByName(_ name: String, days: NSNumber?, inManagedObjectContext context: NSManagedObjectContext) -> EntityDailySyncRule? {
guard name.characters.count > 0 else {
return nil
}
var entityDailySyncRule: EntityDailySyncRule? = fetchEntityDailySyncRuleByName(name, inManagedObjectContext: context)
if entityDailySyncRule == nil {
let newEntityDailySyncRule = NSEntityDescription.insertNewObject(forEntityName: self.simpleClassName(), into: context) as? EntityDailySyncRule
if let entity = newEntityDailySyncRule {
entity.name = name
}
entityDailySyncRule = newEntityDailySyncRule
}
if let entityDailySyncRule = entityDailySyncRule {
entityDailySyncRule.days = days
}
return entityDailySyncRule
}
override open func shouldRunSyncRuleWithName(_ name: String, date: Date, inManagedObjectContext context: NSManagedObjectContext) -> Bool {
let lastExecution = EntitySyncHistory.fetchEntityAutoSyncHistoryByName(name, inManagedObjectContext: context)
if let lastExecution = lastExecution,
let lastExecutionDate = lastExecution.lastExecutionDate,
let days = self.days {
let elapsedTime = Date().timeIntervalSince(lastExecutionDate)
let targetTime = TimeInterval(days.int32Value * 24 * 60 * 60)
return elapsedTime >= targetTime
}
return true
}
}
|
39a393f553d9a96b25ee32f2d73e7397
| 43.426667 | 160 | 0.704382 | false | false | false | false |
thehung111/ViSearchSwiftSDK
|
refs/heads/develop
|
Carthage/Checkouts/visearch-sdk-swift/Example/Example/Lib/KRProgressHUD/KRProgressHUD.swift
|
mit
|
3
|
//
// KRProgressHUD.swift
// KRProgressHUD
//
// Copyright © 2016年 Krimpedance. All rights reserved.
//
import UIKit
/**
Type of KRProgressHUD's background view.
- **Clear:** `UIColor.clearColor`.
- **White:** `UIColor(white: 1, alpho: 0.2)`.
- **Black:** `UIColor(white: 0, alpho: 0.2)`. Default type.
*/
public enum KRProgressHUDMaskType {
case clear, white, black
}
/**
Style of KRProgressHUD.
- **Black:** HUD's backgroundColor is `.blackColor()`. HUD's text color is `.whiteColor()`.
- **White:** HUD's backgroundColor is `.whiteColor()`. HUD's text color is `.blackColor()`. Default style.
- **BlackColor:** same `.Black` and confirmation glyphs become original color.
- **WhiteColor:** same `.Black` and confirmation glyphs become original color.
*/
public enum KRProgressHUDStyle {
case black, white, blackColor, whiteColor
}
/**
KRActivityIndicatorView style. (KRProgressHUD uses only large style.)
- **Black:** the color is `.blackColor()`. Default style.
- **White:** the color is `.blackColor()`.
- **Color(startColor, endColor):** the color is a gradation to `endColor` from `startColor`.
*/
public enum KRProgressHUDActivityIndicatorStyle {
case black, white, color(UIColor, UIColor)
}
/**
* KRProgressHUD is a beautiful and easy-to-use progress HUD.
*/
public final class KRProgressHUD {
fileprivate static let view = KRProgressHUD()
class func sharedView() -> KRProgressHUD { return view }
fileprivate let window = UIWindow(frame: UIScreen.main.bounds)
fileprivate let progressHUDView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
fileprivate let iconView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
fileprivate let activityIndicatorView = KRActivityIndicatorView(position: CGPoint.zero, activityIndicatorStyle: .largeBlack)
fileprivate let drawView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
fileprivate let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 20))
fileprivate var tmpWindow: UIWindow?
fileprivate var maskType: KRProgressHUDMaskType {
willSet {
switch newValue {
case .clear: window.rootViewController?.view.backgroundColor = UIColor.clear
case .white: window.rootViewController?.view.backgroundColor = UIColor(white: 1, alpha: 0.2)
case .black: window.rootViewController?.view.backgroundColor = UIColor(white: 0, alpha: 0.2)
}
}
}
fileprivate var progressHUDStyle: KRProgressHUDStyle {
willSet {
switch newValue {
case .black, .blackColor:
progressHUDView.backgroundColor = UIColor.black
messageLabel.textColor = UIColor.white
case .white, .whiteColor:
progressHUDView.backgroundColor = UIColor.white
messageLabel.textColor = UIColor.black
}
}
}
fileprivate var activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle {
willSet {
switch newValue {
case .black: activityIndicatorView.activityIndicatorViewStyle = .largeBlack
case .white: activityIndicatorView.activityIndicatorViewStyle = .largeWhite
case let .color(sc, ec): activityIndicatorView.activityIndicatorViewStyle = .largeColor(sc, ec)
}
}
}
fileprivate var defaultStyle: KRProgressHUDStyle = .white { willSet { progressHUDStyle = newValue } }
fileprivate var defaultMaskType: KRProgressHUDMaskType = .black { willSet { maskType = newValue } }
fileprivate var defaultActivityIndicatorStyle: KRProgressHUDActivityIndicatorStyle = .black { willSet { activityIndicatorStyle = newValue } }
fileprivate var defaultMessageFont = UIFont(name: "HiraginoSans-W3", size: 13) ?? UIFont.systemFont(ofSize: 13) { willSet { messageLabel.font = newValue } }
fileprivate var defaultPosition: CGPoint = {
let screenFrame = UIScreen.main.bounds
return CGPoint(x: screenFrame.width/2, y: screenFrame.height/2)
}() {
willSet { progressHUDView.center = newValue }
}
public static var isVisible: Bool {
return sharedView().window.alpha == 0 ? false : true
}
fileprivate init() {
maskType = .black
progressHUDStyle = .white
activityIndicatorStyle = .black
configureProgressHUDView()
}
fileprivate func configureProgressHUDView() {
let rootViewController = KRProgressHUDViewController()
window.rootViewController = rootViewController
window.windowLevel = UIWindowLevelNormal
window.alpha = 0
progressHUDView.center = defaultPosition
progressHUDView.backgroundColor = UIColor.white
progressHUDView.layer.cornerRadius = 10
progressHUDView.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin]
window.rootViewController?.view.addSubview(progressHUDView)
iconView.backgroundColor = UIColor.clear
iconView.center = CGPoint(x: 50, y: 50)
progressHUDView.addSubview(iconView)
activityIndicatorView.isHidden = false
iconView.addSubview(activityIndicatorView)
drawView.backgroundColor = UIColor.clear
drawView.isHidden = true
iconView.addSubview(drawView)
messageLabel.center = CGPoint(x: 150/2, y: 90)
messageLabel.backgroundColor = UIColor.clear
messageLabel.font = defaultMessageFont
messageLabel.textAlignment = .center
messageLabel.adjustsFontSizeToFitWidth = true
messageLabel.minimumScaleFactor = 0.5
messageLabel.text = nil
messageLabel.isHidden = true
progressHUDView.addSubview(messageLabel)
}
}
/**
* KRProgressHUD Setter --------------------------
*/
extension KRProgressHUD {
/// Set default mask type.
/// - parameter type: `KRProgressHUDMaskType`
public class func set(maskType type: KRProgressHUDMaskType) {
KRProgressHUD.sharedView().defaultMaskType = type
}
/// Set default HUD style
/// - parameter style: `KRProgressHUDStyle`
public class func set(style: KRProgressHUDStyle) {
KRProgressHUD.sharedView().defaultStyle = style
}
/// Set default KRActivityIndicatorView style.
/// - parameter style: `KRProgresHUDActivityIndicatorStyle`
public class func set(activityIndicatorStyle style: KRProgressHUDActivityIndicatorStyle) {
KRProgressHUD.sharedView().defaultActivityIndicatorStyle = style
}
/// Set default HUD text font.
/// - parameter font: text font
public class func set(font: UIFont) {
KRProgressHUD.sharedView().defaultMessageFont = font
}
/// Set default HUD center's position.
/// - parameter position: center position
public class func set(centerPosition position: CGPoint) {
KRProgressHUD.sharedView().defaultPosition = position
}
}
/**
* KRProgressHUD Show & Dismiss --------------------------
*/
extension KRProgressHUD {
/**
Showing HUD with some args. You can appoint only the args which You want to appoint.
(Args is reflected only this time.)
- parameter progressHUDStyle: KRProgressHUDStyle
- parameter maskType: KRProgressHUDMaskType
- parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle
- parameter font: HUD's message font
- parameter message: HUD's message
- parameter image: image that Alternative to confirmation glyph.
- parameter completion: completion handler.
- returns: No return value.
*/
public class func show(
progressHUDStyle progressStyle: KRProgressHUDStyle? = nil,
maskType type: KRProgressHUDMaskType? = nil,
activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil,
font: UIFont? = nil, message: String? = nil, image: UIImage? = nil,
completion: (()->())? = nil
) {
KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle)
KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message)
KRProgressHUD.sharedView().updateProgressHUDViewIcon(image: image)
KRProgressHUD.sharedView().show() { completion?() }
}
/**
Showing HUD with success glyph. the HUD dismiss after 1 secound.
You can appoint only the args which You want to appoint.
(Args is reflected only this time.)
- parameter progressHUDStyle: KRProgressHUDStyle
- parameter maskType: KRProgressHUDMaskType
- parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle
- parameter font: HUD's message font
- parameter message: HUD's message
*/
public class func showSuccess(
progressHUDStyle progressStyle: KRProgressHUDStyle? = nil,
maskType type: KRProgressHUDMaskType? = nil,
activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil,
font: UIFont? = nil, message: String? = nil) {
KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle)
KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message)
KRProgressHUD.sharedView().updateProgressHUDViewIcon(iconType: .success)
KRProgressHUD.sharedView().show()
Thread.afterDelay(1.0) {
KRProgressHUD.dismiss()
}
}
/**
Showing HUD with information glyph. the HUD dismiss after 1 secound.
You can appoint only the args which You want to appoint.
(Args is reflected only this time.)
- parameter progressHUDStyle: KRProgressHUDStyle
- parameter maskType: KRProgressHUDMaskType
- parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle
- parameter font: HUD's message font
- parameter message: HUD's message
*/
public class func showInfo(
progressHUDStyle progressStyle: KRProgressHUDStyle? = nil,
maskType type: KRProgressHUDMaskType? = nil,
activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil,
font: UIFont? = nil, message: String? = nil) {
KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle)
KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message)
KRProgressHUD.sharedView().updateProgressHUDViewIcon(iconType: .info)
KRProgressHUD.sharedView().show()
Thread.afterDelay(1.0) {
KRProgressHUD.dismiss()
}
}
/**
Showing HUD with warning glyph. the HUD dismiss after 1 secound.
You can appoint only the args which You want to appoint.
(Args is reflected only this time.)
- parameter progressHUDStyle: KRProgressHUDStyle
- parameter maskType: KRProgressHUDMaskType
- parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle
- parameter font: HUD's message font
- parameter message: HUD's message
*/
public class func showWarning(
progressHUDStyle progressStyle: KRProgressHUDStyle? = nil,
maskType type: KRProgressHUDMaskType? = nil,
activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil,
font: UIFont? = nil, message: String? = nil) {
KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle)
KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message)
KRProgressHUD.sharedView().updateProgressHUDViewIcon(iconType: .warning)
KRProgressHUD.sharedView().show()
Thread.afterDelay(1.0) {
KRProgressHUD.dismiss()
}
}
/**
Showing HUD with error glyph. the HUD dismiss after 1 secound.
You can appoint only the args which You want to appoint.
(Args is reflected only this time.)
- parameter progressHUDStyle: KRProgressHUDStyle
- parameter maskType: KRProgressHUDMaskType
- parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle
- parameter font: HUD's message font
- parameter message: HUD's message
*/
public class func showError(
progressHUDStyle progressStyle: KRProgressHUDStyle? = nil,
maskType type: KRProgressHUDMaskType? = nil,
activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil,
font: UIFont? = nil, message: String? = nil) {
KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle)
KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message)
KRProgressHUD.sharedView().updateProgressHUDViewIcon(iconType: .error)
KRProgressHUD.sharedView().show()
Thread.afterDelay(1.0) {
KRProgressHUD.dismiss()
}
}
/**
Dismissing HUD.
- parameter completion: handler when dismissed.
- returns: No return value
*/
public class func dismiss(_ completion: (()->())? = nil) {
DispatchQueue.main.async { () -> Void in
UIView.animate(withDuration: 0.5, animations: {
KRProgressHUD.sharedView().window.alpha = 0
}, completion: { _ in
KRProgressHUD.sharedView().window.isHidden = true
KRProgressHUD.sharedView().tmpWindow?.makeKey()
KRProgressHUD.sharedView().activityIndicatorView.stopAnimating()
KRProgressHUD.sharedView().progressHUDStyle = KRProgressHUD.sharedView().defaultStyle
KRProgressHUD.sharedView().maskType = KRProgressHUD.sharedView().defaultMaskType
KRProgressHUD.sharedView().activityIndicatorStyle = KRProgressHUD.sharedView().defaultActivityIndicatorStyle
KRProgressHUD.sharedView().messageLabel.font = KRProgressHUD.sharedView().defaultMessageFont
completion?()
})
}
}
}
/**
* KRProgressHUD update during show --------------------------
*/
extension KRProgressHUD {
public class func update(text: String) {
sharedView().messageLabel.text = text
}
}
/**
* KRProgressHUD update style method --------------------------
*/
private extension KRProgressHUD {
func show(_ completion: (()->())? = nil) {
DispatchQueue.main.async { () -> Void in
self.tmpWindow = UIApplication.shared.keyWindow
self.window.alpha = 0
self.window.makeKeyAndVisible()
UIView.animate(withDuration: 0.5, animations: {
KRProgressHUD.sharedView().window.alpha = 1
}, completion: { _ in
completion?()
})
}
}
func updateStyles(progressHUDStyle progressStyle: KRProgressHUDStyle?, maskType type: KRProgressHUDMaskType?, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle?) {
if let style = progressStyle {
KRProgressHUD.sharedView().progressHUDStyle = style
}
if let type = type {
KRProgressHUD.sharedView().maskType = type
}
if let style = indicatorStyle {
KRProgressHUD.sharedView().activityIndicatorStyle = style
}
}
func updateProgressHUDViewText(font: UIFont?, message: String?) {
if let text = message {
let center = progressHUDView.center
var frame = progressHUDView.frame
frame.size = CGSize(width: 150, height: 110)
progressHUDView.frame = frame
progressHUDView.center = center
iconView.center = CGPoint(x: 150/2, y: 40)
messageLabel.isHidden = false
messageLabel.text = text
messageLabel.font = font ?? defaultMessageFont
} else {
let center = progressHUDView.center
var frame = progressHUDView.frame
frame.size = CGSize(width: 100, height: 100)
progressHUDView.frame = frame
progressHUDView.center = center
iconView.center = CGPoint(x: 50, y: 50)
messageLabel.isHidden = true
}
}
func updateProgressHUDViewIcon(iconType: KRProgressHUDIconType? = nil, image: UIImage? = nil) {
drawView.subviews.forEach { $0.removeFromSuperview() }
drawView.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
switch (iconType, image) {
case (nil, nil):
drawView.isHidden = true
activityIndicatorView.isHidden = false
activityIndicatorView.startAnimating()
case let (nil, image):
activityIndicatorView.isHidden = true
activityIndicatorView.stopAnimating()
drawView.isHidden = false
let imageView = UIImageView(image: image)
imageView.frame = KRProgressHUD.sharedView().drawView.bounds
imageView.contentMode = .scaleAspectFit
drawView.addSubview(imageView)
case let (type, _):
drawView.isHidden = false
activityIndicatorView.isHidden = true
activityIndicatorView.stopAnimating()
let pathLayer = CAShapeLayer()
pathLayer.frame = drawView.layer.bounds
pathLayer.lineWidth = 0
pathLayer.path = type!.getPath()
switch progressHUDStyle {
case .black: pathLayer.fillColor = UIColor.white.cgColor
case .white: pathLayer.fillColor = UIColor.black.cgColor
default: pathLayer.fillColor = type!.getColor()
}
drawView.layer.addSublayer(pathLayer)
}
}
}
|
9e0dfa8e22f07908d06fe48367870fd0
| 38.967033 | 192 | 0.660929 | false | false | false | false |
motoom/ios-apps
|
refs/heads/master
|
Persistence/Sqlite/Sqlite/ViewController.swift
|
mit
|
2
|
// ViewController.swift
/* Hoe kun je het Sqlite3 framework toevoegen aan je project:
1. Ga naar je project setting, 'General' tab.
2. Bij Linked Frameworks op de + drukken en 'libsqlite3.tbd' toevoegen.
3. Voeg een header file toe aan het project, noem deze 'BridgingHeader.h', en zet hierin één regel: #include <sqlite3.h>
4. Ga naar je project setting, 'Build Settings', en vind 'Objective-C Bridging Header' (via zoek mogelijkheid).
5. Dubbelklik op de lege ruimte erachter en vul daar 'BridgingHeader.h' in.
6. Sleep 'SqliteDb.swift' in je project.
*/
// Uitzoeken: Hoe ga je om met INTEGER, DOUBLE, DECIMALS en DATE velden in je tabel?
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var naamText: UITextField!
@IBOutlet weak var nummerText: UITextField!
@IBOutlet weak var overzichtView: UITextView!
@IBAction func add() {
let db = TelefoonDb.sharedInstance
let naam = naamText.text!
let nummer = nummerText.text!
db.execute("insert into Nummers(naam, nummer) values('\(naam)', '\(nummer)')")
naamText.text = ""
nummerText.text = ""
updateUI()
}
override func viewDidLoad() {
let db = TelefoonDb.sharedInstance
if !db.tableExists("Nummers") {
print("Tabel 'Nummers' bestaat nog niet, aanmaken dus.")
db.execute("create table Nummers(naam text, nummer text)")
db.execute("insert into Nummers values('Koen', '061273281')")
db.execute("insert into Nummers values('Piet', '020128723')")
}
updateUI()
}
func updateUI() {
overzichtView.text = "Dit is de inhoud van de database:\n\n"
let db = TelefoonDb.sharedInstance
if let rs = db.query("select * from Nummers") {
for r in rs {
let naam = r["naam"] ?? ""
let nummer = r["nummer"] ?? ""
let regel = "Bel \(naam) op \(nummer)\n"
overzichtView.text = overzichtView.text + regel
}
}
}
}
|
31413bfca7a8e8120676349aa2064a25
| 35.017241 | 120 | 0.614648 | false | false | false | false |
functionaldude/XLPagerTabStrip
|
refs/heads/master
|
Example/Example/NavButtonBarExampleViewController.swift
|
mit
|
2
|
// NavButtonBarExampleViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import XLPagerTabStrip
class NavButtonBarExampleViewController: ButtonBarPagerTabStripViewController {
var isReload = false
override func viewDidLoad() {
// set up style before super view did load is executed
settings.style.buttonBarBackgroundColor = .clear
settings.style.selectedBarBackgroundColor = .orange
//-
super.viewDidLoad()
buttonBarView.removeFromSuperview()
navigationController?.navigationBar.addSubview(buttonBarView)
changeCurrentIndexProgressive = { (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in
guard changeCurrentIndex == true else { return }
oldCell?.label.textColor = UIColor(white: 1, alpha: 0.6)
newCell?.label.textColor = .white
if animated {
UIView.animate(withDuration: 0.1, animations: { () -> Void in
newCell?.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
oldCell?.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
})
} else {
newCell?.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
oldCell?.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
}
}
}
// MARK: - PagerTabStripDataSource
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
let child_1 = TableChildExampleViewController(style: .plain, itemInfo: "Table View")
let child_2 = ChildExampleViewController(itemInfo: "View")
let child_3 = TableChildExampleViewController(style: .grouped, itemInfo: "Table View 2")
let child_4 = ChildExampleViewController(itemInfo: "View 1")
let child_5 = TableChildExampleViewController(style: .plain, itemInfo: "Table View 3")
let child_6 = ChildExampleViewController(itemInfo: "View 2")
let child_7 = TableChildExampleViewController(style: .grouped, itemInfo: "Table View 4")
let child_8 = ChildExampleViewController(itemInfo: "View 3")
guard isReload else {
return [child_1, child_2, child_3, child_4, child_5, child_6, child_7, child_8]
}
var childViewControllers = [child_1, child_2, child_3, child_4, child_5, child_6, child_7, child_8]
for index in childViewControllers.indices {
let nElements = childViewControllers.count - index
let n = (Int(arc4random()) % nElements) + index
if n != index {
childViewControllers.swapAt(index, n)
}
}
let nItems = 1 + (arc4random() % 8)
return Array(childViewControllers.prefix(Int(nItems)))
}
override func reloadPagerTabStripView() {
isReload = true
if arc4random() % 2 == 0 {
pagerBehaviour = .progressive(skipIntermediateViewControllers: arc4random() % 2 == 0, elasticIndicatorLimit: arc4random() % 2 == 0 )
} else {
pagerBehaviour = .common(skipIntermediateViewControllers: arc4random() % 2 == 0)
}
super.reloadPagerTabStripView()
}
override func configureCell(_ cell: ButtonBarViewCell, indicatorInfo: IndicatorInfo) {
super.configureCell(cell, indicatorInfo: indicatorInfo)
cell.backgroundColor = .clear
}
}
|
110464797772d3bbf2d1c96ded17ec54
| 44.95098 | 182 | 0.675699 | false | false | false | false |
KinveyClientServices/training-app-ios
|
refs/heads/master
|
TrainingApp/CollateralsViewController.swift
|
apache-2.0
|
1
|
//
// CollateralsViewController.swift
// TrainingApp
//
// Created by Igor Sapyanik on 3/29/16.
// Copyright © 2016 Kinvey. All rights reserved.
//
import UIKit
import Kinvey
import SVProgressHUD
class CollateralsViewController: UITableViewController {
var files = [File]()
var fileStore: FileStore!
override func viewDidLoad() {
super.viewDidLoad()
self.clearsSelectionOnViewWillAppear = true
self.refreshControl?.addTarget(self, action: #selector(loadDataFromServer), forControlEvents: .ValueChanged)
fileStore = FileStore.getInstance()
loadDataFromServer()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
func loadDataFromServer() {
self.refreshControl?.beginRefreshing()
//TODO: LAB: Get files from Kinvey
//crash when quering pdf files (mimeType is nil )
//let query = Query(format: "mimeType == %@", "application/pdf")
let query = Query()
fileStore.find(query, ttl: nil, completionHandler: { (files, error) -> Void in
self.refreshControl?.endRefreshing()
if let files = files {
self.files = files
if self.refreshControl?.refreshing ?? false {
self.refreshControl?.endRefreshing()
}
self.tableView.reloadData()
}
})
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return files.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier")!
// Configure the cell...
if indexPath.row < files.count {
let file = files[indexPath.row]
cell.textLabel?.text = file.fileName
}
return cell
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
if let filePreviewViewController = segue.destinationViewController as? FilePreviewViewController {
guard let indexPath = self.tableView.indexPathForSelectedRow where indexPath.row < files.count else {
return
}
let file = files[indexPath.row]
filePreviewViewController.file = file
}
}
}
|
a28ff45c89aef3e46101d6dcf0d2b54c
| 29.052632 | 118 | 0.62662 | false | false | false | false |
frootloops/swift
|
refs/heads/master
|
stdlib/public/core/StringUTF8.swift
|
apache-2.0
|
1
|
//===--- StringUTF8.swift - A UTF8 view of _StringCore --------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// _StringCore currently has three representations: Native ASCII,
// Native UTF-16, and Opaque Cocoa. Expose each of these as UTF-8 in a
// way that will hopefully be efficient to traverse
//
//===----------------------------------------------------------------------===//
extension String {
/// A view of a string's contents as a collection of UTF-8 code units.
///
/// You can access a string's view of UTF-8 code units by using its `utf8`
/// property. A string's UTF-8 view encodes the string's Unicode scalar
/// values as 8-bit integers.
///
/// let flowers = "Flowers 💐"
/// for v in flowers.utf8 {
/// print(v)
/// }
/// // 70
/// // 108
/// // 111
/// // 119
/// // 101
/// // 114
/// // 115
/// // 32
/// // 240
/// // 159
/// // 146
/// // 144
///
/// A string's Unicode scalar values can be up to 21 bits in length. To
/// represent those scalar values using 8-bit integers, more than one UTF-8
/// code unit is often required.
///
/// let flowermoji = "💐"
/// for v in flowermoji.unicodeScalars {
/// print(v, v.value)
/// }
/// // 💐 128144
///
/// for v in flowermoji.utf8 {
/// print(v)
/// }
/// // 240
/// // 159
/// // 146
/// // 144
///
/// In the encoded representation of a Unicode scalar value, each UTF-8 code
/// unit after the first is called a *continuation byte*.
///
/// UTF8View Elements Match Encoded C Strings
/// =========================================
///
/// Swift streamlines interoperation with C string APIs by letting you pass a
/// `String` instance to a function as an `Int8` or `UInt8` pointer. When you
/// call a C function using a `String`, Swift automatically creates a buffer
/// of UTF-8 code units and passes a pointer to that buffer. The code units
/// of that buffer match the code units in the string's `utf8` view.
///
/// The following example uses the C `strncmp` function to compare the
/// beginning of two Swift strings. The `strncmp` function takes two
/// `const char*` pointers and an integer specifying the number of characters
/// to compare. Because the strings are identical up to the 14th character,
/// comparing only those characters results in a return value of `0`.
///
/// let s1 = "They call me 'Bell'"
/// let s2 = "They call me 'Stacey'"
///
/// print(strncmp(s1, s2, 14))
/// // Prints "0"
/// print(String(s1.utf8.prefix(14)))
/// // Prints "They call me '"
///
/// Extending the compared character count to 15 includes the differing
/// characters, so a nonzero result is returned.
///
/// print(strncmp(s1, s2, 15))
/// // Prints "-17"
/// print(String(s1.utf8.prefix(15)))
/// // Prints "They call me 'B"
@_fixed_layout // FIXME(sil-serialize-all)
public struct UTF8View
: BidirectionalCollection,
CustomStringConvertible,
CustomDebugStringConvertible {
/// Underlying UTF-16-compatible representation
@_versioned
internal let _core: _StringCore
/// Distances to `(startIndex, endIndex)` from the endpoints of _core,
/// measured in UTF-8 code units.
///
/// Note: this is *only* here to support legacy Swift3-style slicing where
/// `s.utf8[i..<j]` produces a `String.UTF8View`, and should be removed when
/// those semantics are no longer supported.
@_versioned
internal let _legacyOffsets: (start: Int8, end: Int8)
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(_ _core: _StringCore,
legacyOffsets: (Int, Int) = (0, 0)
) {
self._core = _core
self._legacyOffsets = (Int8(legacyOffsets.0), Int8(legacyOffsets.1))
}
public typealias Index = String.Index
/// The position of the first code unit if the UTF-8 view is
/// nonempty.
///
/// If the UTF-8 view is empty, `startIndex` is equal to `endIndex`.
@_inlineable // FIXME(sil-serialize-all)
public var startIndex: Index {
let r = _index(atEncodedOffset: _core.startIndex)
if _legacyOffsets.start == 0 { return r }
return index(r, offsetBy: numericCast(_legacyOffsets.start))
}
/// The "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// In an empty UTF-8 view, `endIndex` is equal to `startIndex`.
@_inlineable // FIXME(sil-serialize-all)
public var endIndex: Index {
_sanityCheck(_legacyOffsets.end >= -3 && _legacyOffsets.end <= 0,
"out of bounds legacy end")
var r = Index(encodedOffset: _core.endIndex)
if _fastPath(_legacyOffsets.end == 0) {
return r
}
switch _legacyOffsets.end {
case -3: r = index(before: r); fallthrough
case -2: r = index(before: r); fallthrough
case -1: return index(before: r)
default: Builtin.unreachable()
}
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal func _index(atEncodedOffset n: Int) -> Index {
if _fastPath(_core.isASCII) { return Index(encodedOffset: n) }
if n == _core.endIndex { return endIndex }
var p = UTF16.ForwardParser()
var i = _core[n...].makeIterator()
var buffer = Index._UTF8Buffer()
Loop:
while true {
switch p.parseScalar(from: &i) {
case .valid(let u16):
let u8 = Unicode.UTF8.transcode(u16, from: Unicode.UTF16.self)
._unsafelyUnwrappedUnchecked
if buffer.count + u8.count > buffer.capacity { break Loop }
buffer.append(contentsOf: u8)
case .error:
let u8 = Unicode.UTF8.encodedReplacementCharacter
if buffer.count + u8.count > buffer.capacity { break Loop }
buffer.append(contentsOf: u8)
case .emptyInput:
break Loop
}
}
return Index(encodedOffset: n, .utf8(buffer: buffer))
}
/// Returns the next consecutive position after `i`.
///
/// - Precondition: The next position is representable.
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public func index(after i: Index) -> Index {
if _fastPath(_core.isASCII) {
precondition(i.encodedOffset < _core.count)
return Index(encodedOffset: i.encodedOffset + 1)
}
var j = i
// Ensure j's cache is utf8
if _slowPath(j._cache.utf8 == nil) {
j = _index(atEncodedOffset: j.encodedOffset)
precondition(j != endIndex, "Index out of bounds")
}
let buffer = j._cache.utf8._unsafelyUnwrappedUnchecked
var scalarLength16 = 1
let b0 = buffer.first._unsafelyUnwrappedUnchecked
var nextBuffer = buffer
let leading1s = (~b0).leadingZeroBitCount
if _fastPath(leading1s == 0) { // ASCII in buffer; just consume it
nextBuffer.removeFirst()
}
else {
// Number of bytes consumed in this scalar
let n8 = j._transcodedOffset + 1
// If we haven't reached a scalar boundary...
if _fastPath(n8 < leading1s) {
// Advance to the next position in this scalar
return Index(
encodedOffset: j.encodedOffset,
transcodedOffset: n8, .utf8(buffer: buffer))
}
// We reached a scalar boundary; compute the underlying utf16's width
// based on the number of utf8 code units
scalarLength16 = n8 >> 2 + 1
nextBuffer.removeFirst(n8)
}
if _fastPath(!nextBuffer.isEmpty) {
return Index(
encodedOffset: j.encodedOffset + scalarLength16,
.utf8(buffer: nextBuffer))
}
// If nothing left in the buffer, refill it.
return _index(atEncodedOffset: j.encodedOffset + scalarLength16)
}
@_inlineable // FIXME(sil-serialize-all)
public func index(before i: Index) -> Index {
if _fastPath(_core.isASCII) {
precondition(i.encodedOffset > 0)
return Index(encodedOffset: i.encodedOffset - 1)
}
if i._transcodedOffset != 0 {
_sanityCheck(i._cache.utf8 != nil)
var r = i
r._compoundOffset = r._compoundOffset &- 1
return r
}
// Handle the scalar boundary the same way as the not-a-utf8-index case.
// Parse a single scalar
var p = Unicode.UTF16.ReverseParser()
var s = _core[..<i.encodedOffset].reversed().makeIterator()
let u8: Unicode.UTF8.EncodedScalar
switch p.parseScalar(from: &s) {
case .valid(let u16):
u8 = Unicode.UTF8.transcode(
u16, from: Unicode.UTF16.self)._unsafelyUnwrappedUnchecked
case .error:
u8 = Unicode.UTF8.encodedReplacementCharacter
case .emptyInput:
_preconditionFailure("Index out of bounds")
}
return Index(
encodedOffset: i.encodedOffset &- (u8.count < 4 ? 1 : 2),
transcodedOffset: u8.count &- 1,
.utf8(buffer: String.Index._UTF8Buffer(u8))
)
}
@_inlineable // FIXME(sil-serialize-all)
public func distance(from i: Index, to j: Index) -> Int {
if _fastPath(_core.isASCII) {
return j.encodedOffset - i.encodedOffset
}
return j >= i
? _forwardDistance(from: i, to: j) : -_forwardDistance(from: j, to: i)
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned
@inline(__always)
internal func _forwardDistance(from i: Index, to j: Index) -> Int {
var r = j._transcodedOffset - i._transcodedOffset
UTF8._transcode(
_core[i.encodedOffset..<j.encodedOffset], from: UTF16.self) {
r += $0.count
}
return r
}
/// Accesses the code unit at the given position.
///
/// The following example uses the subscript to print the value of a
/// string's first UTF-8 code unit.
///
/// let greeting = "Hello, friend!"
/// let i = greeting.utf8.startIndex
/// print("First character's UTF-8 code unit: \(greeting.utf8[i])")
/// // Prints "First character's UTF-8 code unit: 72"
///
/// - Parameter position: A valid index of the view. `position`
/// must be less than the view's end index.
@_inlineable // FIXME(sil-serialize-all)
public subscript(position: Index) -> UTF8.CodeUnit {
@inline(__always)
get {
if _fastPath(_core.asciiBuffer != nil), let ascii = _core.asciiBuffer {
_precondition(position < endIndex, "Index out of bounds")
return ascii[position.encodedOffset]
}
var j = position
while true {
if case .utf8(let buffer) = j._cache {
_onFastPath()
return buffer[
buffer.index(buffer.startIndex, offsetBy: j._transcodedOffset)]
}
j = _index(atEncodedOffset: j.encodedOffset)
precondition(j < endIndex, "Index out of bounds")
}
}
}
@_inlineable // FIXME(sil-serialize-all)
public var description: String {
return String(_core)
}
@_inlineable // FIXME(sil-serialize-all)
public var debugDescription: String {
return "UTF8View(\(self.description.debugDescription))"
}
}
/// A UTF-8 encoding of `self`.
@_inlineable // FIXME(sil-serialize-all)
public var utf8: UTF8View {
get {
return UTF8View(self._core)
}
set {
self = String(describing: newValue)
}
}
/// A contiguously stored null-terminated UTF-8 representation of the string.
///
/// To access the underlying memory, invoke `withUnsafeBufferPointer` on the
/// array.
///
/// let s = "Hello!"
/// let bytes = s.utf8CString
/// print(bytes)
/// // Prints "[72, 101, 108, 108, 111, 33, 0]"
///
/// bytes.withUnsafeBufferPointer { ptr in
/// print(strlen(ptr.baseAddress!))
/// }
/// // Prints "6"
@_inlineable // FIXME(sil-serialize-all)
public var utf8CString: ContiguousArray<CChar> {
var result = ContiguousArray<CChar>()
result.reserveCapacity(utf8.count + 1)
for c in utf8 {
result.append(CChar(bitPattern: c))
}
result.append(0)
return result
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal func _withUnsafeBufferPointerToUTF8<R>(
_ body: (UnsafeBufferPointer<UTF8.CodeUnit>) throws -> R
) rethrows -> R {
if let asciiBuffer = self._core.asciiBuffer {
return try body(UnsafeBufferPointer(
start: asciiBuffer.baseAddress,
count: asciiBuffer.count))
}
var nullTerminatedUTF8 = ContiguousArray<UTF8.CodeUnit>()
nullTerminatedUTF8.reserveCapacity(utf8.count + 1)
nullTerminatedUTF8 += utf8
nullTerminatedUTF8.append(0)
return try nullTerminatedUTF8.withUnsafeBufferPointer(body)
}
/// Creates a string corresponding to the given sequence of UTF-8 code units.
///
/// If `utf8` is an ill-formed UTF-8 code sequence, the result is `nil`.
///
/// You can use this initializer to create a new string from a slice of
/// another string's `utf8` view.
///
/// let picnicGuest = "Deserving porcupine"
/// if let i = picnicGuest.utf8.index(of: 32) {
/// let adjective = String(picnicGuest.utf8[..<i])
/// print(adjective)
/// }
/// // Prints "Optional(Deserving)"
///
/// The `adjective` constant is created by calling this initializer with a
/// slice of the `picnicGuest.utf8` view.
///
/// - Parameter utf8: A UTF-8 code sequence.
@_inlineable // FIXME(sil-serialize-all)
@available(swift, deprecated: 3.2,
message: "Failable initializer was removed in Swift 4. When upgrading to Swift 4, please use non-failable String.init(_:UTF8View)")
@available(swift, obsoleted: 4.0,
message: "Please use non-failable String.init(_:UTF8View) instead")
public init?(_ utf8: UTF8View) {
if utf8.startIndex._transcodedOffset != 0
|| utf8.endIndex._transcodedOffset != 0 {
return nil
}
// Attempt to recover the whole string, the better to implement the actual
// Swift 3.1 semantics, which are not as documented above! Full Swift 3.1
// semantics may be impossible to preserve in the case of string literals,
// since we no longer have access to the length of the original string when
// there is no owner and elements have been dropped from the end.
if let nativeBuffer = utf8._core.nativeBuffer {
let wholeString = String(_StringCore(nativeBuffer))
let offset = (utf8._core._baseAddress! - nativeBuffer.start)
&>> utf8._core.elementShift
if Index(
encodedOffset: utf8.startIndex.encodedOffset + offset
).samePosition(in: wholeString) == nil
|| Index(
encodedOffset: utf8.endIndex.encodedOffset + offset
).samePosition(in: wholeString) == nil {
return nil
}
}
self = String(utf8._core)
}
/// Creates a string corresponding to the given sequence of UTF-8 code units.
@_inlineable // FIXME(sil-serialize-all)
@available(swift, introduced: 4.0, message:
"Please use failable String.init?(_:UTF8View) when in Swift 3.2 mode")
public init(_ utf8: UTF8View) {
self = String(utf8._core)
}
/// The index type for subscripting a string.
public typealias UTF8Index = UTF8View.Index
}
extension String.UTF8View : _SwiftStringView {
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal var _persistentContent : String { return String(self._core) }
}
extension String.UTF8View {
@_fixed_layout // FIXME(sil-serialize-all)
public struct Iterator {
internal typealias _OutputBuffer = UInt64
@_versioned // FIXME(sil-serialize-all)
internal let _source: _StringCore
@_versioned // FIXME(sil-serialize-all)
internal var _sourceIndex: Int
@_versioned // FIXME(sil-serialize-all)
internal var _buffer: _OutputBuffer
}
public func makeIterator() -> Iterator {
return Iterator(_core)
}
}
extension String.UTF8View.Iterator : IteratorProtocol {
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(_ source: _StringCore) {
_source = source
_sourceIndex = 0
_buffer = 0
}
@_inlineable // FIXME(sil-serialize-all)
public mutating func next() -> Unicode.UTF8.CodeUnit? {
if _fastPath(_buffer != 0) {
let r = UInt8(truncatingIfNeeded: _buffer) &- 1
_buffer >>= 8
return r
}
if _slowPath(_sourceIndex == _source.count) { return nil }
defer { _fixLifetime(_source) }
if _fastPath(_source._unmanagedASCII != nil),
let ascii = _source._unmanagedASCII {
let result = ascii[_sourceIndex]
_sourceIndex += 1
for i in 0 ..< _OutputBuffer.bitWidth>>3 {
if _sourceIndex == _source.count { break }
_buffer |= _OutputBuffer(ascii[_sourceIndex] &+ 1) &<< (i << 3)
_sourceIndex += 1
}
return result
}
if _fastPath(_source._unmanagedUTF16 != nil),
let utf16 = _source._unmanagedUTF16 {
return _next(refillingFrom: utf16)
}
return _next(refillingFrom: _source)
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal mutating func _next<Source: Collection>(
refillingFrom source: Source
) -> Unicode.UTF8.CodeUnit?
where Source.Element == Unicode.UTF16.CodeUnit,
Source.Index == Int
{
_sanityCheck(_buffer == 0)
var shift = 0
// ASCII fastpath
while _sourceIndex != _source.endIndex && shift < _OutputBuffer.bitWidth {
let u = _source[_sourceIndex]
if u >= 0x80 { break }
_buffer |= _OutputBuffer(UInt8(truncatingIfNeeded: u &+ 1)) &<< shift
_sourceIndex += 1
shift = shift &+ 8
}
var i = IndexingIterator(_elements: source, _position: _sourceIndex)
var parser = Unicode.UTF16.ForwardParser()
Loop:
while true {
let u8: UTF8.EncodedScalar
switch parser.parseScalar(from: &i) {
case .valid(let s):
u8 = UTF8.transcode(s, from: UTF16.self)._unsafelyUnwrappedUnchecked
case .error(_):
u8 = UTF8.encodedReplacementCharacter
case .emptyInput:
break Loop
}
var newBuffer = _buffer
for x in u8 {
newBuffer |= _OutputBuffer(x &+ 1) &<< shift
shift = shift &+ 8
}
guard _fastPath(shift <= _OutputBuffer.bitWidth) else { break Loop }
_buffer = newBuffer
_sourceIndex = i._position &- parser._buffer.count
}
guard _fastPath(_buffer != 0) else { return nil }
let result = UInt8(truncatingIfNeeded: _buffer) &- 1
_buffer >>= 8
return result
}
}
extension String.UTF8View {
@_inlineable // FIXME(sil-serialize-all)
public var count: Int {
if _fastPath(_core.isASCII) { return _core.count }
let b = _core._unmanagedUTF16
if _fastPath(b != nil) {
defer { _fixLifetime(_core) }
return _count(fromUTF16: b!)
}
return _count(fromUTF16: self._core)
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal func _count<Source: Sequence>(fromUTF16 source: Source) -> Int
where Source.Element == Unicode.UTF16.CodeUnit
{
var result = 0
var prev: Unicode.UTF16.CodeUnit = 0
for u in source {
switch u {
case 0..<0x80: result += 1
case 0x80..<0x800: result += 2
case 0x800..<0xDC00: result += 3
case 0xDC00..<0xE000: result += UTF16.isLeadSurrogate(prev) ? 1 : 3
default: result += 3
}
prev = u
}
return result
}
}
// Index conversions
extension String.UTF8View.Index {
/// Creates an index in the given UTF-8 view that corresponds exactly to the
/// specified `UTF16View` position.
///
/// The following example finds the position of a space in a string's `utf16`
/// view and then converts that position to an index in the string's
/// `utf8` view.
///
/// let cafe = "Café 🍵"
///
/// let utf16Index = cafe.utf16.index(of: 32)!
/// let utf8Index = String.UTF8View.Index(utf16Index, within: cafe.utf8)!
///
/// print(Array(cafe.utf8[..<utf8Index]))
/// // Prints "[67, 97, 102, 195, 169]"
///
/// If the position passed in `utf16Index` doesn't have an exact
/// corresponding position in `utf8`, the result of the initializer is
/// `nil`. For example, because UTF-8 and UTF-16 represent high Unicode code
/// points differently, an attempt to convert the position of the trailing
/// surrogate of a UTF-16 surrogate pair fails.
///
/// The next example attempts to convert the indices of the two UTF-16 code
/// points that represent the teacup emoji (`"🍵"`). The index of the lead
/// surrogate is successfully converted to a position in `utf8`, but the
/// index of the trailing surrogate is not.
///
/// let emojiHigh = cafe.utf16.index(after: utf16Index)
/// print(String.UTF8View.Index(emojiHigh, within: cafe.utf8))
/// // Prints "Optional(String.Index(...))"
///
/// let emojiLow = cafe.utf16.index(after: emojiHigh)
/// print(String.UTF8View.Index(emojiLow, within: cafe.utf8))
/// // Prints "nil"
///
/// - Parameters:
/// - sourcePosition: A position in a `String` or one of its views.
/// - target: The `UTF8View` in which to find the new position.
@_inlineable // FIXME(sil-serialize-all)
public init?(_ sourcePosition: String.Index, within target: String.UTF8View) {
switch sourcePosition._cache {
case .utf8:
self.init(encodedOffset: sourcePosition.encodedOffset,
transcodedOffset:sourcePosition._transcodedOffset, sourcePosition._cache)
default:
guard String.UnicodeScalarView(target._core)._isOnUnicodeScalarBoundary(
sourcePosition) else { return nil }
self.init(encodedOffset: sourcePosition.encodedOffset)
}
}
}
// Reflection
extension String.UTF8View : CustomReflectable {
/// Returns a mirror that reflects the UTF-8 view of a string.
@_inlineable // FIXME(sil-serialize-all)
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self)
}
}
extension String.UTF8View : CustomPlaygroundQuickLookable {
@_inlineable // FIXME(sil-serialize-all)
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(description)
}
}
// backward compatibility for index interchange.
extension String.UTF8View {
@_inlineable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index")
public func index(after i: Index?) -> Index {
return index(after: i!)
}
@_inlineable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index")
public func index(_ i: Index?, offsetBy n: Int) -> Index {
return index(i!, offsetBy: n)
}
@_inlineable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional indices")
public func distance(
from i: Index?, to j: Index?) -> Int {
return distance(from: i!, to: j!)
}
@_inlineable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index")
public subscript(i: Index?) -> Unicode.UTF8.CodeUnit {
return self[i!]
}
}
//===--- Slicing Support --------------------------------------------------===//
/// In Swift 3.2, in the absence of type context,
///
/// someString.utf8[someString.utf8.startIndex..<someString.utf8.endIndex]
///
/// was deduced to be of type `String.UTF8View`. Provide a more-specific
/// Swift-3-only `subscript` overload that continues to produce
/// `String.UTF8View`.
extension String.UTF8View {
public typealias SubSequence = Substring.UTF8View
@_inlineable // FIXME(sil-serialize-all)
@available(swift, introduced: 4)
public subscript(r: Range<Index>) -> String.UTF8View.SubSequence {
return String.UTF8View.SubSequence(self, _bounds: r)
}
@_inlineable // FIXME(sil-serialize-all)
@available(swift, obsoleted: 4)
public subscript(r: Range<Index>) -> String.UTF8View {
if r.upperBound._transcodedOffset == 0 {
return String.UTF8View(
_core[r.lowerBound.encodedOffset..<r.upperBound.encodedOffset],
legacyOffsets: (r.lowerBound._transcodedOffset, 0))
}
let b0 = r.upperBound._cache.utf8!.first!
let scalarLength8 = (~b0).leadingZeroBitCount
let scalarLength16 = scalarLength8 == 4 ? 2 : 1
let coreEnd = r.upperBound.encodedOffset + scalarLength16
return String.UTF8View(
_core[r.lowerBound.encodedOffset..<coreEnd],
legacyOffsets: (
r.lowerBound._transcodedOffset,
r.upperBound._transcodedOffset - scalarLength8))
}
@_inlineable // FIXME(sil-serialize-all)
@available(swift, obsoleted: 4)
public subscript(bounds: ClosedRange<Index>) -> String.UTF8View {
return self[bounds.relative(to: self)]
}
}
|
0338cb1a91cb30fe38757ed7fe18d176
| 33.833109 | 135 | 0.62401 | false | false | false | false |
jianghongbing/APIReferenceDemo
|
refs/heads/master
|
UIKit/NSLayoutConstraint/NSLayoutConstraint/VFLViewController.swift
|
mit
|
1
|
//
// VFLViewController.swift
// NSLayoutConstraint
//
// Created by pantosoft on 2018/7/16.
// Copyright © 2018年 jianghongbing. All rights reserved.
//
import UIKit
class VFLViewController: UIViewController, CreateView{
private var myLayoutConstraints: [NSLayoutConstraint] = []
private var redView: UIView!
private var greenView: UIView!
private var blueView: UIView!
private var orangeView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
redView = createView(with: .red, superView: view)
greenView = createView(with: .green, superView: view)
blueView = createView(with: .blue, superView: view)
orangeView = createView(with: .orange, superView: view)
}
override func updateViewConstraints() {
super.updateViewConstraints()
if myLayoutConstraints.count > 0 {
NSLayoutConstraint.deactivate(myLayoutConstraints)
}
let views = ["redView": redView!, "greenView": greenView!, "blueView": blueView!, "orangeView": orangeView!]
let topMargin = self.view.layoutMargins.top + 20
let bottomMargin = self.view.layoutMargins.bottom + 20
let leftMargin = self.view.layoutMargins.left
let rightMargin = self.view.layoutMargins.right
let metrics = ["horizonalMargin": 10, "verticalMargin": 20, "topMargin": topMargin, "bottomMargin": bottomMargin, "leftMargin": leftMargin, "rightMargin": rightMargin]
var horizonalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(leftMargin)-[redView(==greenView)]-(horizonalMargin)-[greenView]-(rightMargin)-|", options: [.alignAllTop, .alignAllBottom, .directionLeadingToTrailing], metrics: metrics, views: views)
horizonalConstraints += NSLayoutConstraint.constraints(withVisualFormat: "|-(leftMargin)-[blueView(==orangeView)]-(horizonalMargin)-[orangeView]-(rightMargin)-|", options: [.alignAllTop, .alignAllBottom, .directionLeadingToTrailing], metrics: metrics, views: views)
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(topMargin)-[redView(==blueView)]-(verticalMargin)-[blueView]-(bottomMargin)-|", options: [.alignAllLeading, .alignAllCenterX], metrics: metrics, views: views)
myLayoutConstraints = horizonalConstraints + verticalConstraints
NSLayoutConstraint.activate(myLayoutConstraints)
}
override func viewLayoutMarginsDidChange() {
super.viewLayoutMarginsDidChange()
view.setNeedsUpdateConstraints()
}
}
|
ed8f83a669f261b0a5ae458ee4ef2a08
| 49.54902 | 275 | 0.706362 | false | false | false | false |
Poligun/NihonngoSwift
|
refs/heads/master
|
Nihonngo/Type.swift
|
mit
|
1
|
//
// Type.swift
// Nihonngo
//
// Created by ZhaoYuhan on 14/12/26.
// Copyright (c) 2014年 ZhaoYuhan. All rights reserved.
//
import Foundation
import CoreData
class Type: NSManagedObject {
@NSManaged var word: Word
@NSManaged var type: String
override var description: String {
return wordType.rawValue
}
var wordType: WordType {
get {
return WordType(rawValue: self.type)!
}
set {
self.type = newValue.rawValue
}
}
}
enum WordType: String {
case Noun = "名词"
case Pronoun = "代词"
case Adverb = "副词"
case Intransitive = "自动词"
case Transitive = "他动词"
case Godan = "五段动词"
case Ichidan = "一段动词"
case Sahen = "サ变动词"
case FirstTypeAdj = "一类形容词"
case SecondTypeAdj = "二类形容词"
case Auxiliary = "助词"
case Conjunction = "接续词"
case CommonlyUsed = "常用语"
case RenTaiShi = "连体词"
case RenGo = "连语"
case JyoSuuShi = "量词"
static let allValues = [Noun, Pronoun, Adverb, Intransitive, Transitive, Godan, Ichidan, Sahen, FirstTypeAdj, SecondTypeAdj]
}
|
955c63b5e9346df19e9b072a1c1ee133
| 20.882353 | 128 | 0.605381 | false | false | false | false |
Ivacker/swift
|
refs/heads/master
|
test/SILGen/generic_property_base_lifetime.swift
|
apache-2.0
|
10
|
// RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | FileCheck %s
protocol ProtocolA: class {
var intProp: Int { get set }
}
protocol ProtocolB {
var intProp: Int { get }
}
@objc protocol ProtocolO: class {
var intProp: Int { get set }
}
// CHECK-LABEL: sil hidden @_TF30generic_property_base_lifetime21getIntPropExistentialFPS_9ProtocolA_Si
// CHECK: [[PROJECTION:%.*]] = open_existential_ref %0
// CHECK: strong_retain [[PROJECTION]]
// CHECK: apply {{%.*}}<@opened{{.*}}>([[PROJECTION]])
// CHECK: strong_release %0
// CHECK-NOT: strong_release
func getIntPropExistential(a: ProtocolA) -> Int {
return a.intProp
}
// CHECK-LABEL: sil hidden @_TF30generic_property_base_lifetime21setIntPropExistentialFPS_9ProtocolA_T_
// CHECK: [[PROJECTION:%.*]] = open_existential_ref %0
// CHECK: strong_retain [[PROJECTION]]
// CHECK: apply {{%.*}}<@opened{{.*}}>({{%.*}}, [[PROJECTION]])
// CHECK: strong_release %0
// CHECK_NOT: strong_release
func setIntPropExistential(a: ProtocolA) {
a.intProp = 0
}
// CHECK-LABEL: sil hidden @_TF30generic_property_base_lifetime17getIntPropGeneric
// CHECK-NOT: strong_retain %0
// CHECK: apply {{%.*}}<T>(%0)
// CHECK: strong_release %0
func getIntPropGeneric<T: ProtocolA>(a: T) -> Int {
return a.intProp
}
// CHECK-LABEL: sil hidden @_TF30generic_property_base_lifetime17setIntPropGeneric
// CHECK-NOT: strong_retain %0
// CHECK: apply {{%.*}}<T>({{%.*}}, %0)
// CHECK: strong_release %0
func setIntPropGeneric<T: ProtocolA>(a: T) {
a.intProp = 0
}
// CHECK-LABEL: sil hidden @_TF30generic_property_base_lifetime21getIntPropExistentialFPS_9ProtocolB_Si
// CHECK: [[PROJECTION:%.*]] = open_existential_addr %0
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $@opened({{".*"}}) ProtocolB
// CHECK: copy_addr [[PROJECTION]] to [initialization] [[STACK]]#1
// CHECK: apply {{%.*}}([[STACK]]#1)
// CHECK: destroy_addr [[STACK]]#1
// CHECK: dealloc_stack [[STACK]]#0
// CHECK: destroy_addr %0
func getIntPropExistential(a: ProtocolB) -> Int {
return a.intProp
}
// CHECK-LABEL: sil hidden @_TF30generic_property_base_lifetime17getIntPropGeneric
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]]#1
// CHECK: apply {{%.*}}<T>([[STACK]]#1)
// CHECK: destroy_addr [[STACK]]#1
// CHECK: dealloc_stack [[STACK]]#0
// CHECK: destroy_addr %0
func getIntPropGeneric<T: ProtocolB>(a: T) -> Int {
return a.intProp
}
// CHECK-LABEL: sil hidden @_TF30generic_property_base_lifetime21getIntPropExistentialFPS_9ProtocolO_Si
// CHECK: debug_value
// CHECK-NEXT: [[PROJECTION:%.*]] = open_existential_ref %0
// CHECK-NEXT: strong_retain [[PROJECTION]]
// CHECK-NEXT: [[METHOD:%.*]] = witness_method
// CHECK-NEXT: apply [[METHOD]]<@opened{{.*}}>([[PROJECTION]])
// CHECK-NEXT: strong_release [[PROJECTION]]
// CHECK-NEXT: strong_release %0
// CHECK-NEXT: return
func getIntPropExistential(a: ProtocolO) -> Int {
return a.intProp
}
// CHECK-LABEL: sil hidden @_TF30generic_property_base_lifetime21setIntPropExistentialFPS_9ProtocolO_T_
// CHECK: [[PROJECTION:%.*]] = open_existential_ref %0
// CHECK-NEXT: strong_retain [[PROJECTION]]
// CHECK: [[METHOD:%.*]] = witness_method
// CHECK-NEXT: apply [[METHOD]]<@opened{{.*}}>({{.*}}, [[PROJECTION]])
// CHECK-NEXT: strong_release [[PROJECTION]]
// CHECK-NEXT: strong_release %0
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
func setIntPropExistential(a: ProtocolO) {
a.intProp = 0
}
// CHECK-LABEL: sil hidden @_TF30generic_property_base_lifetime17getIntPropGeneric
// CHECK-NOT: strong_retain %0
// CHECK: apply {{%.*}}<T>(%0)
// CHECK: strong_release %0
// CHECK-NOT: strong_release %0
func getIntPropGeneric<T: ProtocolO>(a: T) -> Int {
return a.intProp
}
// CHECK-LABEL: sil hidden @_TF30generic_property_base_lifetime17setIntPropGeneric
// CHECK-NOT: strong_retain %0
// CHECK: apply {{%.*}}<T>({{%.*}}, %0)
// CHECK: strong_release %0
// CHECK-NOT: strong_release %0
func setIntPropGeneric<T: ProtocolO>(a: T) {
a.intProp = 0
}
|
6f285e9847d9a3a91a912aad26a8096e
| 36.119658 | 107 | 0.628137 | false | false | false | false |
angelolloqui/SwiftKotlin
|
refs/heads/develop
|
Assets/Tests/KotlinTokenizer/expressions.swift
|
mit
|
1
|
// Ternary and coalescing operators
let value = isTrue ? "yes" : "no"
let label = x > 0 ? "Positive" : "negative"
button.color = item.deleted ? red : green
let text = label ?? "default"
// Wilcard assignments
_ = service.deleteObject()
// Optional chaning
self.service.fetchData()?.user.name?.count
self.data.filter { $0.item?.value == 1 }.map { $0.key }.first?.name.count
// Type casting
self.object = data as! ObjectType
self.object = data as? ObjectType
|
9dcb3afc06fbeeea5fc7a670629bba52
| 24.777778 | 73 | 0.68319 | false | false | false | false |
tqtifnypmb/Framenderer
|
refs/heads/master
|
Framenderer/Sources/Filters/ImageProcessing/FeiChen/FeiChenFilter.swift
|
mit
|
2
|
//
// FeiChenFilter.swift
// Framenderer
//
// Created by tqtifnypmb on 09/04/2017.
// Copyright © 2017 tqtifnypmb. All rights reserved.
//
import Foundation
public class FeiChenFilter: BaseFilter {
override public init() {}
override public var name: String {
return "FeiChenFilter"
}
override func buildProgram() throws {
_program = try Program.create(fragmentSourcePath: "3x3ConvolutionFragmentShader")
}
override func setUniformAttributs(context ctx: Context) {
super.setUniformAttributs(context: ctx)
let texelWidth = 1 / GLfloat(ctx.inputWidth)
let texelHeight = 1 / GLfloat(ctx.inputHeight)
_program.setUniform(name: kXOffset, value: texelWidth)
_program.setUniform(name: kYOffset, value: texelHeight)
let tmp = sqrtf(2.0)
let xKernel: [Float] = [1.0, tmp, 1.0,
0.0, 0.0, 0.0,
-1.0, -tmp, -1.0]
let yKernel: [Float] = [1.0, 0.0, -1.0,
tmp, 0.0, -tmp,
1.0, 0.0, -1.0]
_program.setUniform(name: "xKernel", mat3x3: xKernel)
_program.setUniform(name: "yKernel", mat3x3: yKernel)
_program.setUniform(name: "scale", value: 2.0 / (2.0 + tmp))
}
}
|
0dbc1fadc3c9ecfd2beb289e9f30f779
| 30.697674 | 89 | 0.553925 | false | false | false | false |
allbto/WayThere
|
refs/heads/master
|
ios/WayThere/WayThere/Classes/Controllers/Cities/CitiesViewController.swift
|
mit
|
2
|
//
// CitiesViewController.swift
// WayThere
//
// Created by Allan BARBATO on 5/17/15.
// Copyright (c) 2015 Allan BARBATO. All rights reserved.
//
import UIKit
protocol CitiesViewControllerDelegate
{
func didFinishEditingCities()
}
@IBDesignable class CitiesViewController: UITableViewController
{
let DefaultCellIdentifier = "DefaultCellIdentifier"
@IBInspectable weak var isForecast: NSNumber!
weak var forecastCity: City? {
didSet {
if let city = forecastCity {
dataStore.delegate = self
dataStore.retrieveWeatherForecastForCity(city)
self.title = city.name
}
}
}
var activityIndicator: UIActivityIndicatorView?
@IBOutlet weak var addCityButton: UIButton!
var delegate: CitiesViewControllerDelegate?
var dataStore = CitiesDataStore()
// Cities manager
var cities = [City]()
var searchingCities = [SimpleCity]()
// Forecast
var weathers = [Weather]()
// MARK: - UIViewController
private func _showActivityIndicator()
{
if activityIndicator == nil {
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
activityIndicator!.frame = CGRectMake(0, 0, 24, 24)
activityIndicator!.center = self.tableView.center
activityIndicator!.frame.origin.y = 53
self.view.addSubview(activityIndicator!)
}
self.view.bringSubviewToFront(activityIndicator!)
activityIndicator!.hidden = false
activityIndicator!.startAnimating()
}
private func _hideActivityIndicator()
{
activityIndicator?.stopAnimating()
activityIndicator?.hidden = true
}
private func _hideSearchBar(active: Bool = false)
{
if active {
self.searchDisplayController?.setActive(false, animated: true)
self.searchDisplayController?.searchBar.resignFirstResponder()
}
self.searchDisplayController?.searchBar.hidden = true
self.tableView.tableFooterView?.hidden = false
self.tableView.tableHeaderView = nil
}
private func _showSearchBar(active: Bool = true)
{
self.searchDisplayController?.searchBar.hidden = false
self.tableView.tableFooterView?.hidden = true
self.tableView.tableHeaderView = self.searchDisplayController?.searchBar
if active {
self.searchDisplayController?.setActive(true, animated: true)
self.searchDisplayController?.searchBar.becomeFirstResponder()
}
}
private func _setUpBottomView()
{
var button = UIButton(frame: CGRect(x: 0, y: 0, width: 65, height: 65))
button.setImage(UIImage(named: "AddButton"), forState: .Normal)
button.addTarget(self, action: "addCityAction:", forControlEvents: .TouchUpInside)
self.tableView.tableFooterView = button
}
override func viewDidLoad()
{
super.viewDidLoad()
// Setup tableView background view color
self.tableView.backgroundView = UIView(frame: self.view.bounds)
self.tableView.backgroundView?.backgroundColor = UIColor.whiteColor()
// Configure DataStore
dataStore.delegate = self
// Hide bar button item if isForecast
if isForecast.boolValue == true {
self.navigationItem.rightBarButtonItem = nil
} else {
// Setup tableView bottom view
_setUpBottomView()
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
_hideSearchBar()
// Reload data to not show wrong information
if cities.count > 0 || weathers.count > 0 {
self.tableView.reloadData()
}
_showActivityIndicator()
if isForecast.boolValue == false {
// Fetch cities data
dataStore.retrieveWeatherConfiguration()
} else {
_hideActivityIndicator()
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func addCityAction(sender: AnyObject)
{
_showSearchBar()
}
@IBAction func cancelAction(sender: AnyObject)
{
delegate?.didFinishEditingCities()
self.dismissViewControllerAnimated(true, completion: nil)
}
}
// MARK: CitiesDataStoreDelegate
extension CitiesViewController : CitiesDataStoreDelegate
{
func foundWeatherConfiguration(cities : [City])
{
_hideActivityIndicator()
self.cities = cities
self.tableView.reloadData()
}
func unableToFindWeatherConfiguration(error : NSError)
{
_hideActivityIndicator()
UIAlertView(title: "Oups !", message: "Seems like the cities just disappeared", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "Retry").show()
}
func foundCitiesForQuery(cities: [SimpleCity])
{
_hideActivityIndicator()
searchingCities = cities
self.searchDisplayController?.searchResultsTableView.reloadData()
}
func unableToFindCitiesForQuery(error: NSError?)
{
_hideActivityIndicator()
// UIAlertView(title: "Cannot find cities", message: "Seems like it's broken, Johnny !", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "Retry").show()
}
func didSaveNewCity(city: City)
{
cities.append(city)
self.tableView.reloadSections(NSIndexSet(index:0), withRowAnimation: .Automatic)
}
func didRemoveCity(city: City)
{
if let index = cities.remove(city) {
self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .Automatic)
}
}
func foundWeatherForecastForCity(weathers: [Weather])
{
_hideActivityIndicator()
self.weathers = weathers
self.tableView.reloadData()
}
func unableToFindForecastForCity(error: NSError?)
{
UIAlertView(title: "Oups !", message: "Seems like the forecasts are unreachable", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "Retry").show()
}
}
// MARK: - UIAlertViewDelegate
extension CitiesViewController: UIAlertViewDelegate
{
/**
Relaunch requests if they were unsuccessful and user decides to retry
:param: alertView
:param: buttonIndex
*/
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int)
{
if buttonIndex != alertView.cancelButtonIndex {
// Show activity indicator while waiting for weather data
_showActivityIndicator()
if isForecast.boolValue == true && forecastCity != nil {
// Fetch weather forecasts
dataStore.retrieveWeatherForecastForCity(forecastCity!)
} else if isForecast.boolValue == false {
// Fetch cities data
dataStore.retrieveWeatherConfiguration()
}
}
}
}
// MARK: UITableViewDataSource
extension CitiesViewController
{
/// Rows
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
var deleteButton = UITableViewRowAction(style: .Default, title: "Delete", handler: { (action, indexPath) in
self.tableView.dataSource?.tableView?(
self.tableView,
commitEditingStyle: .Delete,
forRowAtIndexPath: indexPath
)
return
})
deleteButton.backgroundColor = UIColor(red:1, green:136 / 255, blue:71 / 255, alpha:1.0)
return [deleteButton]
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
if tableView == self.searchDisplayController?.searchResultsTableView ||
isForecast.boolValue == true ||
cities.get(indexPath.row)?.isCurrentLocation?.boolValue == true {
return false
}
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == .Delete {
if let city = cities.get(indexPath.row) {
dataStore.removeCity(city)
}
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
if tableView == self.searchDisplayController?.searchResultsTableView {
return 44
}
return 85
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if tableView == self.searchDisplayController?.searchResultsTableView {
return searchingCities.count
} else if isForecast.boolValue == true {
return weathers.count
}
return cities.count
}
private func _searchCityCellForIndexPath(indexPath: NSIndexPath) -> UITableViewCell
{
if let city = searchingCities.get(indexPath.row) {
var cell = tableView.dequeueReusableCellWithIdentifier(DefaultCellIdentifier) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: DefaultCellIdentifier)
}
cell!.textLabel?.text = "\(city.name), \(city.country)"
return cell!
} else {
return UITableViewCell()
}
}
private func _forecastCellForIndexPath(indexPath: NSIndexPath) -> UITableViewCell
{
if let weather = weathers.get(indexPath.row), weatherCell = tableView.dequeueReusableCellWithIdentifier(CellType.CityWeatherCell.rawValue) as? CityWeatherTableViewCell {
weatherCell.mainLabel.text = weather.day
weatherCell.subtitleLabel.text = weather.title
if SettingsDataStore.settingValueForKey(.UnitOfTemperature) as? String == SettingUnitOfTemperature.Celcius.rawValue {
weatherCell.temperatureLabel.text = "\(String(weather.tempCelcius as? Int))°C"
} else {
weatherCell.temperatureLabel.text = "\(String(weather.tempFahrenheit as? Int))°F"
}
weatherCell.weatherImageView.image = weather.weatherImage()
return weatherCell
} else {
return UITableViewCell()
}
}
private func _cityCellForIndexPath(indexPath: NSIndexPath) -> UITableViewCell
{
if let city = cities.get(indexPath.row), weatherCell = tableView.dequeueReusableCellWithIdentifier(CellType.CityWeatherCell.rawValue) as? CityWeatherTableViewCell {
weatherCell.mainLabel.text = city.name
weatherCell.subtitleLabel.text = city.todayWeather?.title
if SettingsDataStore.settingValueForKey(.UnitOfTemperature) as? String == SettingUnitOfTemperature.Celcius.rawValue {
weatherCell.temperatureLabel.text = "\(String(city.todayWeather?.tempCelcius as? Int))°C"
} else {
weatherCell.temperatureLabel.text = "\(String(city.todayWeather?.tempFahrenheit as? Int))°F"
}
weatherCell.weatherImageView.image = city.todayWeather?.weatherImage()
//UIColor(red:1, green:136 / 255, blue:71 / 255, alpha:1.0), icon:UIImage(named:"DeleteIcon")) // #FF8847
return weatherCell
} else {
return UITableViewCell()
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
if tableView == self.searchDisplayController?.searchResultsTableView {
return _searchCityCellForIndexPath(indexPath)
} else if isForecast.boolValue == true {
return _forecastCellForIndexPath(indexPath)
} else {
return _cityCellForIndexPath(indexPath)
}
}
}
// MARK: UITableViewDelegate
extension CitiesViewController
{
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if tableView == self.searchDisplayController?.searchResultsTableView {
if let city = searchingCities.get(indexPath.row) {
_hideSearchBar(active: true)
dataStore.saveCity(city)
}
}
}
}
// MARK: UISearchDisplayDelegate
extension CitiesViewController : UISearchDisplayDelegate
{
func searchDisplayControllerWillBeginSearch(controller: UISearchDisplayController)
{
self.searchDisplayController?.searchBar.hidden = false
}
func searchDisplayControllerWillEndSearch(controller: UISearchDisplayController)
{
_hideSearchBar()
}
func searchDisplayControllerDidBeginSearch(controller: UISearchDisplayController) {
}
func searchDisplayControllerDidEndSearch(controller: UISearchDisplayController)
{
searchingCities = []
self.searchDisplayController?.searchResultsTableView.reloadData()
}
func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String!) -> Bool
{
if count(searchString) >= 3 {
_showActivityIndicator()
dataStore.retrieveCitiesForQuery(searchString)
}
return false
}
}
|
08444c485ddff82e300e93c2902f5493
| 32.848411 | 177 | 0.643745 | false | false | false | false |
jeremiahyan/ResearchKit
|
refs/heads/main
|
ResearchKit/ActiveTasks/Math.swift
|
bsd-3-clause
|
3
|
/*
Copyright (c) 2019, Novartis.
Copyright (c) 2019, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
internal class Math {
internal class func degreesToRadians(_ angle: Double) -> Double {
return angle / 180 * .pi
}
internal class func pointFromAngle(_ frame: CGRect, angle: Double, radius: Double) -> CGPoint {
let radian = degreesToRadians(angle)
let xPoint = Double(frame.midX) + cos(radian) * radius
let yPoint = Double(frame.midY) + sin(radian) * radius
return CGPoint(x: xPoint, y: yPoint)
}
internal class func pointPairToBearingDegrees(_ startPoint: CGPoint, endPoint: CGPoint) -> Double {
let originPoint = CGPoint(x: endPoint.x - startPoint.x, y: endPoint.y - startPoint.y)
let bearingRadians = atan2(Double(originPoint.y), Double(originPoint.x))
var bearingDegrees = bearingRadians * (180.0 / .pi)
bearingDegrees = (bearingDegrees > 0.0 ? bearingDegrees : (360.0 + bearingDegrees))
return bearingDegrees
}
internal class func adjustValue(_ startAngle: Double, degree: Double, maxValue: Float, minValue: Float) -> Double {
let ratio = Double((maxValue - minValue) / 360)
let ratioStart = ratio * startAngle
let ratioDegree = ratio * degree
let adjustValue: Double
if startAngle < 0 {
adjustValue = (360 + startAngle) > degree ? (ratioDegree - ratioStart) : (ratioDegree - ratioStart) - (360 * ratio)
} else {
adjustValue = (360 - (360 - startAngle)) < degree ? (ratioDegree - ratioStart) : (ratioDegree - ratioStart) + (360 * ratio)
}
return adjustValue + (Double(minValue))
}
internal class func adjustDegree(_ startAngle: Double, degree: Double) -> Double {
return (360 + startAngle) > degree ? degree : -(360 - degree)
}
internal class func degreeFromValue(_ startAngle: Double, value: Float, maxValue: Float, minValue: Float) -> Double {
let ratio = Double((maxValue - minValue) / 360)
let angle = Double(value) / ratio
return angle + startAngle - (Double(minValue) / ratio)
}
}
|
42f72dddae58ed0488bdd451b0be025f
| 48.184211 | 135 | 0.703585 | false | false | false | false |
IngmarStein/swift
|
refs/heads/master
|
test/attr/attr_noescape.swift
|
apache-2.0
|
4
|
// RUN: %target-parse-verify-swift
@noescape var fn : () -> Int = { 4 } // expected-error {{@noescape may only be used on 'parameter' declarations}} {{1-11=}}
func conflictingAttrs(_ fn: @noescape @escaping () -> Int) {} // expected-error {{@escaping conflicts with @noescape}}
// expected-warning@-1{{@noescape is the default and is deprecated}} {{29-39=}}
func doesEscape(_ fn : @escaping () -> Int) {}
func takesGenericClosure<T>(_ a : Int, _ fn : @noescape () -> T) {} // expected-warning{{@noescape is the default and is deprecated}} {{47-57=}}
func takesNoEscapeClosure(_ fn : () -> Int) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
// expected-note@-2{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
// expected-note@-3{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
// expected-note@-4{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
takesNoEscapeClosure { 4 } // ok
_ = fn() // ok
var x = fn // expected-error {{non-escaping parameter 'fn' may only be called}}
// This is ok, because the closure itself is noescape.
takesNoEscapeClosure { fn() }
// This is not ok, because it escapes the 'fn' closure.
doesEscape { fn() } // expected-error {{closure use of non-escaping parameter 'fn' may allow it to escape}}
// This is not ok, because it escapes the 'fn' closure.
func nested_function() {
_ = fn() // expected-error {{declaration closing over non-escaping parameter 'fn' may allow it to escape}}
}
takesNoEscapeClosure(fn) // ok
doesEscape(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
takesGenericClosure(4, fn) // ok
takesGenericClosure(4) { fn() } // ok.
}
class SomeClass {
final var x = 42
func test() {
// This should require "self."
doesEscape { x } // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
// Since 'takesNoEscapeClosure' doesn't escape its closure, it doesn't
// require "self." qualification of member references.
takesNoEscapeClosure { x }
}
@discardableResult
func foo() -> Int {
foo()
func plain() { foo() }
let plain2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
func multi() -> Int { foo(); return 0 }
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{31-31=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
takesNoEscapeClosure { foo() } // okay
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
takesNoEscapeClosure { foo(); return 0 } // okay
func outer() {
func inner() { foo() }
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 }
let _: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{28-28=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() }
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 }
}
let outer2: () -> Void = {
func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}}
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
}
doesEscape {
func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}}
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
return 0
}
takesNoEscapeClosure {
func inner() { foo() }
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 }
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // okay
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // okay
return 0
}
struct Outer {
@discardableResult
func bar() -> Int {
bar()
func plain() { bar() }
let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
func multi() -> Int { bar(); return 0 }
let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
takesNoEscapeClosure { bar() } // okay
doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
takesNoEscapeClosure { bar(); return 0 } // okay
return 0
}
}
func structOuter() {
struct Inner {
@discardableResult
func bar() -> Int {
bar() // no-warning
func plain() { bar() }
let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{26-26=self.}}
func multi() -> Int { bar(); return 0 }
let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{32-32=self.}}
doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
takesNoEscapeClosure { bar() } // okay
doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
takesNoEscapeClosure { bar(); return 0 } // okay
return 0
}
}
}
return 0
}
}
// Implicit conversions (in this case to @convention(block)) are ok.
@_silgen_name("whatever")
func takeNoEscapeAsObjCBlock(_: @noescape @convention(block) () -> Void) // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}}
func takeNoEscapeTest2(_ fn : @noescape () -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{31-41=}}
takeNoEscapeAsObjCBlock(fn)
}
// Autoclosure implies noescape, but produce nice diagnostics so people know
// why noescape problems happen.
func testAutoclosure(_ a : @autoclosure () -> Int) { // expected-note{{parameter 'a' is implicitly non-escaping because it was declared @autoclosure}}
doesEscape { a() } // expected-error {{closure use of non-escaping parameter 'a' may allow it to escape}}
}
// <rdar://problem/19470858> QoI: @autoclosure implies @noescape, so you shouldn't be allowed to specify both
func redundant(_ fn : @noescape // expected-error @+1 {{@noescape is implied by @autoclosure and should not be redundantly specified}}
@autoclosure () -> Int) {
// expected-warning@-2{{@noescape is the default and is deprecated}} {{23-33=}}
}
protocol P1 {
associatedtype Element
}
protocol P2 : P1 {
associatedtype Element
}
func overloadedEach<O: P1, T>(_ source: O, _ transform: @escaping (O.Element) -> (), _: T) {}
func overloadedEach<P: P2, T>(_ source: P, _ transform: @escaping (P.Element) -> (), _: T) {}
struct S : P2 {
typealias Element = Int
func each(_ transform: @noescape (Int) -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{26-36=}}
overloadedEach(self, // expected-error {{cannot invoke 'overloadedEach' with an argument list of type '(S, (Int) -> (), Int)'}}
transform, 1)
// expected-note @-2 {{overloads for 'overloadedEach' exist with these partially matching parameter lists: (O, @escaping (O.Element) -> (), T), (P, @escaping (P.Element) -> (), T)}}
}
}
// rdar://19763676 - False positive in @noescape analysis triggered by parameter label
func r19763676Callee(_ f: @noescape (_ param: Int) -> Int) {} // expected-warning{{@noescape is the default and is deprecated}} {{27-37=}}
func r19763676Caller(_ g: @noescape (Int) -> Int) { // expected-warning{{@noescape is the default and is deprecated}} {{27-37=}}
r19763676Callee({ _ in g(1) })
}
// <rdar://problem/19763732> False positive in @noescape analysis triggered by default arguments
func calleeWithDefaultParameters(_ f: @noescape () -> (), x : Int = 1) {} // expected-warning {{closure parameter prior to parameters with default arguments will not be treated as a trailing closure}}
// expected-warning@-1{{@noescape is the default and is deprecated}} {{39-49=}}
func callerOfDefaultParams(_ g: @noescape () -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}}
calleeWithDefaultParameters(g)
}
// <rdar://problem/19773562> Closures executed immediately { like this }() are not automatically @noescape
class NoEscapeImmediatelyApplied {
func f() {
// Shouldn't require "self.", the closure is obviously @noescape.
_ = { return ivar }()
}
final var ivar = 42
}
// Reduced example from XCTest overlay, involves a TupleShuffleExpr
public func XCTAssertTrue(_ expression: @autoclosure () -> Bool, _ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void {
}
public func XCTAssert(_ expression: @autoclosure () -> Bool, _ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void {
XCTAssertTrue(expression, message, file: file, line: line);
}
/// SR-770 - Currying and `noescape`/`rethrows` don't work together anymore
func curriedFlatMap<A, B>(_ x: [A]) -> (@noescape (A) -> [B]) -> [B] { // expected-warning{{@noescape is the default and is deprecated}} {{41-50=}}
return { f in
x.flatMap(f)
}
}
func curriedFlatMap2<A, B>(_ x: [A]) -> (@noescape (A) -> [B]) -> [B] { // expected-warning{{@noescape is the default and is deprecated}} {{42-51=}}
return { (f : @noescape (A) -> [B]) in // expected-warning{{@noescape is the default and is deprecated}} {{17-27=}}
x.flatMap(f)
}
}
func bad(_ a : @escaping (Int)-> Int) -> Int { return 42 }
func escapeNoEscapeResult(_ x: [Int]) -> (@noescape (Int) -> Int) -> Int { // expected-warning{{@noescape is the default and is deprecated}} {{43-52=}}
return { f in // expected-note{{parameter 'f' is implicitly non-escaping}}
bad(f) // expected-error {{passing non-escaping parameter 'f' to function expecting an @escaping closure}}
}
}
// SR-824 - @noescape for Type Aliased Closures
//
// Old syntax -- @noescape is the default, and is redundant
typealias CompletionHandlerNE = @noescape (_ success: Bool) -> () // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}}
// Explicit @escaping is not allowed here
typealias CompletionHandlerE = @escaping (_ success: Bool) -> () // expected-error{{@escaping attribute may only be used in function parameter position}} {{32-42=}}
// No @escaping -- it's implicit from context
typealias CompletionHandler = (_ success: Bool) -> ()
var escape : CompletionHandlerNE
var escapeOther : CompletionHandler
func doThing1(_ completion: (_ success: Bool) -> ()) {
// expected-note@-1{{parameter 'completion' is implicitly non-escaping}}
// expected-error @+2 {{non-escaping value 'escape' may only be called}}
// expected-error @+1 {{non-escaping parameter 'completion' may only be called}}
escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}}
}
func doThing2(_ completion: CompletionHandlerNE) {
// expected-note@-1{{parameter 'completion' is implicitly non-escaping}}
// expected-error @+2 {{non-escaping value 'escape' may only be called}}
// expected-error @+1 {{non-escaping parameter 'completion' may only be called}}
escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}}
}
func doThing3(_ completion: CompletionHandler) {
// expected-note@-1{{parameter 'completion' is implicitly non-escaping}}
// expected-error @+2 {{non-escaping value 'escape' may only be called}}
// expected-error @+1 {{non-escaping parameter 'completion' may only be called}}
escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}}
}
func doThing4(_ completion: @escaping CompletionHandler) {
escapeOther = completion
}
// <rdar://problem/19997680> @noescape doesn't work on parameters of function type
func apply<T, U>(_ f: @noescape (T) -> U, g: @noescape (@noescape (T) -> U) -> U) -> U {
// expected-warning@-1{{@noescape is the default and is deprecated}} {{23-33=}}
// expected-warning@-2{{@noescape is the default and is deprecated}} {{46-56=}}
// expected-warning@-3{{@noescape is the default and is deprecated}} {{57-66=}}
return g(f)
}
// <rdar://problem/19997577> @noescape cannot be applied to locals, leading to duplication of code
enum r19997577Type {
case Unit
case Function(() -> r19997577Type, () -> r19997577Type)
case Sum(() -> r19997577Type, () -> r19997577Type)
func reduce<Result>(_ initial: Result, _ combine: @noescape (Result, r19997577Type) -> Result) -> Result { // expected-warning{{@noescape is the default and is deprecated}} {{53-63=}}
let binary: @noescape (r19997577Type, r19997577Type) -> Result = { combine(combine(combine(initial, self), $0), $1) } // expected-warning{{@noescape is the default and is deprecated}} {{17-27=}}
switch self {
case .Unit:
return combine(initial, self)
case let .Function(t1, t2):
return binary(t1(), t2())
case let .Sum(t1, t2):
return binary(t1(), t2())
}
}
}
// type attribute and decl attribute
func noescapeD(@noescape f: @escaping () -> Bool) {} // expected-error {{@noescape is now an attribute on a parameter type, instead of on the parameter itself}} {{16-25=}} {{29-29=@noescape }}
func noescapeT(f: @noescape () -> Bool) {} // expected-warning{{@noescape is the default and is deprecated}} {{19-29=}}
func autoclosureD(@autoclosure f: () -> Bool) {} // expected-error {{@autoclosure is now an attribute on a parameter type, instead of on the parameter itself}} {{19-31=}} {{35-35=@autoclosure }}
func autoclosureT(f: @autoclosure () -> Bool) {} // ok
func noescapeD_noescapeT(@noescape f: @noescape () -> Bool) {} // expected-error {{@noescape is now an attribute on a parameter type, instead of on the parameter itself}}
// expected-warning@-1{{@noescape is the default and is deprecated}} {{39-49=}}
func autoclosureD_noescapeT(@autoclosure f: @noescape () -> Bool) {} // expected-error {{@autoclosure is now an attribute on a parameter type, instead of on the parameter itself}} {{29-41=}} {{45-45=@autoclosure }}
// expected-warning@-1{{@noescape is the default and is deprecated}} {{45-55=}}
|
60ae67d1ada48bcc88c3c788e9875675
| 53.703812 | 214 | 0.659376 | false | false | false | false |
Crebs/Discrete-Mathematics
|
refs/heads/master
|
DiscreteMath/SwiftScripts/SwiftScripts/main.swift
|
mit
|
1
|
#!/usr/bin/swift
import Foundation
class KnownPrime {
private var primes = [Int]()
private func addToKnowPrimes(newPrime: Int) {
primes.append(newPrime)
}
public func isPrime(number: Int) -> Bool {
let root = Int(floor(sqrt(Double(number))))
for nextPrime in primes {
if nextPrime <= root {
let remainder = number % nextPrime
if remainder == 0 {
return false
}
} else {
break
}
}
return true
}
public func primesThrough(max: Int) -> [Int] {
var nuq = 2;
while nuq <= max {
if isPrime(number: nuq) {
addToKnowPrimes(newPrime: nuq)
}
nuq += 1
}
return primes
}
}
class PrimeOutput {
public func primes(max: Int) {
let knownPrimes = KnownPrime()
let primes = knownPrimes.primesThrough(max: max)
var previous :Int?
for prime in primes {
print(prime)
if (previous != nil) {
let diff = prime - previous! - 1
if !knownPrimes.isPrime(number: diff) {
print("^\(diff) isn't prime !!!!!")
} else {
print("^\(diff)")
}
}
previous = prime
}
}
}
//// Takes input from commandline
for argument in CommandLine.arguments {
if let numberOfPrimes = Int(argument) {
let output = PrimeOutput()
output.primes(max: numberOfPrimes)
}
}
|
09b847f328ef4c2c785be7d86ebf31f8
| 23.279412 | 56 | 0.471835 | false | false | false | false |
IvanVorobei/RequestPermission
|
refs/heads/master
|
Example/SPPermission/SPPermission/Frameworks/SparrowKit/UI/Controllers/SPProposeController.swift
|
mit
|
1
|
// The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([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
class SPProposeController: SPController {
private let data: Data
internal let areaView = AreaView()
private var isPresent: Bool = false
private var animationDuration: TimeInterval {
return 0.5
}
private var gradeFactor: CGFloat {
return 0.6
}
private var space: CGFloat {
return 6
}
init(title: String, subtitle: String, buttonTitle: String, imageLink: String? = nil, image: UIImage? = nil, complection: @escaping (_ isConfirmed: Bool)->() = {_ in }) {
self.data = Data(
title: title,
subtitle: subtitle,
buttonTitle: buttonTitle,
imageLink: imageLink,
image: image,
complection: complection
)
super.init(nibName: nil, bundle: nil)
self.modalPresentationStyle = .overCurrentContext
self.view.backgroundColor = UIColor.black.withAlphaComponent(0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.areaView.isHidden = true
self.areaView.titleLabel.text = self.data.title
self.areaView.subtitleLabel.text = self.data.subtitle
self.areaView.button.setTitle(self.data.buttonTitle, for: UIControl.State.normal)
self.areaView.button.addTarget(self, action: #selector(self.open), for: UIControl.Event.touchUpInside)
self.areaView.closeButton.addTarget(self, action: #selector(self.close), for: UIControl.Event.touchUpInside)
self.view.addSubview(self.areaView)
let panGesture = UIPanGestureRecognizer.init(target: self, action: #selector(self.handleGesture(sender:)))
panGesture.maximumNumberOfTouches = 1
self.areaView.addGestureRecognizer(panGesture)
self.areaView.imageView.setParalax(amount: 0.1)
if let image = self.data.image {
self.areaView.imageView.setImage(image: image, animatable: false)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !self.isPresent {
self.present()
self.isPresent = true
}
}
private func present() {
SPVibration.impact(.warning)
self.areaView.frame.origin.y = self.view.frame.size.height
self.areaView.isHidden = false
SPAnimationSpring.animate(self.animationDuration, animations: {
self.view.backgroundColor = UIColor.black.withAlphaComponent(self.gradeFactor)
self.areaView.frame.origin.y = self.view.frame.size.height - self.areaView.frame.height - (self.bottomSafeArea / 2) - self.space
}, spring: 1,
velocity: 1,
options: .transitionCurlUp)
}
override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
let hide = {
self.view.backgroundColor = UIColor.black.withAlphaComponent(0)
self.areaView.frame.origin.y = self.view.frame.size.height
}
let dismiss = {
super.dismiss(animated: false) {
completion?()
}
}
if flag {
SPAnimationSpring.animate(self.animationDuration, animations: {
hide()
}, spring: 1,
velocity: 1,
options: .transitionCurlDown,
withComplection: {
dismiss()
})
} else {
hide()
dismiss()
}
}
override func updateLayout(with size: CGSize) {
super.updateLayout(with: size)
self.areaView.layout(origin: CGPoint.init(x: self.space, y: 0), width: size.width - (self.space * 2))
self.areaView.frame.origin.y = self.view.frame.size.height - self.areaView.frame.height - (self.bottomSafeArea / 2) - self.space
}
@objc func handleGesture(sender: UIPanGestureRecognizer) {
let returnAreaViewToPoint = {
SPAnimationSpring.animate(self.animationDuration, animations: {
self.areaView.frame.origin.y = self.view.frame.size.height - self.areaView.frame.height - (self.bottomSafeArea / 2) - self.space
self.view.backgroundColor = UIColor.black.withAlphaComponent(self.gradeFactor)
}, spring: 1,
velocity: 1,
options: .transitionCurlDown,
withComplection: {
})
}
switch sender.state {
case .began:
break
case .cancelled:
returnAreaViewToPoint()
case .changed:
let translation = sender.translation(in: self.view)
self.areaView.center = CGPoint(x: areaView.center.x + 0, y: areaView.center.y + translation.y / 4)
sender.setTranslation(CGPoint.zero, in: self.view)
let baseY = self.view.frame.size.height - self.areaView.frame.height - (self.bottomSafeArea / 2) - self.space
let dem = -(baseY - self.areaView.frame.origin.y) / 6
var newGrade = self.gradeFactor - (dem / 100)
newGrade.setIfFewer(when: 0.2)
newGrade.setIfMore(when: self.gradeFactor + 0.05)
self.view.backgroundColor = UIColor.black.withAlphaComponent(newGrade)
case .ended:
returnAreaViewToPoint()
default:
break
}
}
@objc func open() {
self.data.complection(true)
self.dismiss(animated: true)
}
@objc func close() {
self.data.complection(false)
self.dismiss(animated: true)
}
class AreaView: UIView {
let titleLabel = UILabel()
let subtitleLabel = UILabel()
let imageView = SPDownloadingImageView()
let button = SPNativeLargeButton()
let closeButton = SPSystemIconButton(type: SPSystemIcon.close)
var imageSideSize: CGFloat = 160
private let space: CGFloat = 36
init() {
super.init(frame: CGRect.zero)
self.backgroundColor = UIColor.white
self.layer.masksToBounds = true
self.layer.cornerRadius = 34
self.titleLabel.font = UIFont.system(weight: .regular, size: 28)
self.titleLabel.textColor = UIColor.init(hex: "939393")
self.titleLabel.numberOfLines = 1
self.titleLabel.adjustsFontSizeToFitWidth = true
self.titleLabel.minimumScaleFactor = 0.5
self.titleLabel.setCenterAlignment()
self.addSubview(self.titleLabel)
self.subtitleLabel.font = UIFont.system(weight: .regular, size: 16)
self.subtitleLabel.textColor = SPNativeColors.black
self.subtitleLabel.numberOfLines = 0
self.subtitleLabel.setCenterAlignment()
self.addSubview(self.subtitleLabel)
self.imageView.gradeView.backgroundColor = UIColor.white
self.imageView.contentMode = .scaleAspectFit
self.imageView.layer.masksToBounds = true
self.addSubview(self.imageView)
self.button.titleLabel?.font = UIFont.system(weight: UIFont.FontWeight.medium, size: 15)
self.button.setTitleColor(SPNativeColors.black)
self.button.layer.cornerRadius = 13
self.button.backgroundColor = SPNativeColors.lightGray
self.addSubview(self.button)
self.closeButton.widthIconFactor = 0.4
self.closeButton.heightIconFactor = 0.4
self.closeButton.backgroundColor = SPNativeColors.lightGray.withAlphaComponent(0.6)
self.closeButton.color = UIColor.init(hex: "979797")
self.addSubview(self.closeButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.titleLabel.sizeToFit()
self.titleLabel.frame.origin.y = self.space * 0.9
self.titleLabel.frame.set(width: self.frame.width - self.space * 3)
self.titleLabel.setXCenter()
self.subtitleLabel.sizeToFit()
self.subtitleLabel.frame.origin.y = self.titleLabel.frame.bottomY + 8
self.subtitleLabel.frame.set(width: self.frame.width - self.space * 2)
self.subtitleLabel.setXCenter()
self.imageView.frame = CGRect.init(
x: 0, y: self.subtitleLabel.frame.bottomY + self.space / 2,
width: self.imageSideSize,
height: self.imageSideSize
)
self.imageView.setXCenter()
self.button.sizeToFit()
self.button.frame.set(height: 52)
self.button.frame.set(width: self.frame.width - self.space * 2)
self.button.frame.origin.y = self.imageView.frame.bottomY + self.space / 1.8
self.button.setXCenter()
self.closeButton.frame = CGRect.init(x: 0, y: 0, width: 24, height: 24)
self.closeButton.frame.origin.x = self.frame.width - self.closeButton.frame.width - 20
self.closeButton.frame.origin.y = 20
self.closeButton.round()
self.frame.set(height: self.button.frame.bottomY + self.space)
}
func layout(origin: CGPoint, width: CGFloat) {
self.frame.origin = origin
self.frame.set(width: width)
self.layoutSubviews()
}
}
struct Data {
var title: String
var subtitle: String
var buttonTitle: String
var imageLink: String?
var image: UIImage?
var complection: (_ isConfirmed: Bool)->()
}
var bottomSafeArea: CGFloat {
var bottomSafeArea: CGFloat = 0
if let window = UIApplication.shared.keyWindow {
if #available(iOS 11.0, *) {
bottomSafeArea = window.safeAreaInsets.bottom
}
} else {
bottomSafeArea = 0
}
return bottomSafeArea
}
}
|
bd07f8ccafc0d4ada095a26985817db8
| 37.872483 | 173 | 0.604454 | false | false | false | false |
zisko/swift
|
refs/heads/master
|
test/SILGen/protocol_optional.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
@objc protocol P1 {
@objc optional func method(_ x: Int)
@objc optional var prop: Int { get }
@objc optional subscript (i: Int) -> Int { get }
}
// CHECK-LABEL: sil hidden @$S17protocol_optional0B13MethodGeneric1tyx_tAA2P1RzlF : $@convention(thin) <T where T : P1> (@owned T) -> ()
func optionalMethodGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : @owned $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T>
// CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: [[T_BORROW:%.*]] = begin_borrow [[T]]
// CHECK: [[T_COPY:%.*]] = copy_value [[T_BORROW]]
// CHECK: store [[T_COPY]] to [init] [[PT]] : $*T
// CHECK: end_borrow [[T_BORROW]] from [[T]]
// CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_guaranteed (Int) -> ()> }
// CHECK: project_box [[OPT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T
// CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T
// CHECK: alloc_stack $Optional<@callee_guaranteed (Int) -> ()>
// CHECK: dynamic_method_br [[T]] : $T, #P1.method!1.foreign
var methodRef = t.method
}
// CHECK: } // end sil function '$S17protocol_optional0B13MethodGeneric1tyx_tAA2P1RzlF'
// CHECK-LABEL: sil hidden @$S17protocol_optional0B15PropertyGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P1> (@owned T) -> ()
func optionalPropertyGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : @owned $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T>
// CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: [[T_BORROW:%.*]] = begin_borrow [[T]]
// CHECK: [[T_COPY:%.*]] = copy_value [[T_BORROW]]
// CHECK: store [[T_COPY]] to [init] [[PT]] : $*T
// CHECK: end_borrow [[T_BORROW]] from [[T]]
// CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<Int> }
// CHECK: project_box [[OPT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T
// CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T
// CHECK: alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[T]] : $T, #P1.prop!getter.1.foreign
var propertyRef = t.prop
}
// CHECK: } // end sil function '$S17protocol_optional0B15PropertyGeneric{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @$S17protocol_optional0B16SubscriptGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P1> (@owned T) -> ()
func optionalSubscriptGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : @owned $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T>
// CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: [[T_BORROW:%.*]] = begin_borrow [[T]]
// CHECK: [[T_COPY:%.*]] = copy_value [[T_BORROW]]
// CHECK: store [[T_COPY]] to [init] [[PT]] : $*T
// CHECK: end_borrow [[T_BORROW]] from [[T]]
// CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<Int> }
// CHECK: project_box [[OPT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T
// CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T
// CHECK: [[INT64:%[0-9]+]] = metatype $@thin Int.Type
// CHECK: [[FIVELIT:%[0-9]+]] = integer_literal $Builtin.Int2048, 5
// CHECK: [[INTCONV:%[0-9]+]] = function_ref @$SSi2{{[_0-9a-zA-Z]*}}fC
// CHECK: [[FIVE:%[0-9]+]] = apply [[INTCONV]]([[FIVELIT]], [[INT64]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
// CHECK: alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[T]] : $T, #P1.subscript!getter.1.foreign
var subscriptRef = t[5]
}
// CHECK: } // end sil function '$S17protocol_optional0B16SubscriptGeneric{{[_0-9a-zA-Z]*}}F'
|
2db4fd4929741a7c852c5a4fcbb826f7
| 52.246575 | 148 | 0.555184 | false | false | false | false |
cwwise/CWWeChat
|
refs/heads/master
|
CWWeChat/MainClass/Mine/Expression/View/EmoticonDetailFooterView.swift
|
mit
|
2
|
//
// EmoticonDetailFooterView.swift
// CWWeChat
//
// Created by wei chen on 2017/8/24.
// Copyright © 2017年 cwcoder. All rights reserved.
//
import UIKit
import YYText
import Kingfisher
import SwiftyImage
class EmoticonDetailFooterView: UICollectionReusableView {
var emoticonPackage: EmoticonPackage! {
didSet {
setupInfo()
}
}
var userImageView: UIImageView!
var userLabel: UILabel!
var titleLabel: UILabel!
// 赞赏
var admireButton: UIButton!
var admireLabel: YYLabel!
var copyrightLabel: UILabel!
// 服务声明
var serveButton: UIButton!
// 侵权投诉
var tortButton: UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
addSnap()
}
func setupUI() {
titleLabel = UILabel()
titleLabel.textColor = UIColor(hex: "#666")
titleLabel.font = UIFont.systemFont(ofSize: 14)
self.addSubview(titleLabel)
admireButton = UIButton()
let normalImage = UIImage.size(CGSize(width: 10, height: 10))
.color(UIColor(hex: "#ff6a55")).corner(radius: 3).image.resizableImage()
admireButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15)
admireButton.setBackgroundImage(normalImage.resizableImage(), for: .normal)
admireButton.setTitle("赞赏", for: .normal)
self.addSubview(admireButton)
admireLabel = YYLabel()
self.addSubview(admireLabel)
copyrightLabel = UILabel()
copyrightLabel.textColor = UIColor(hex: "#666")
copyrightLabel.font = UIFont.systemFont(ofSize: 12)
self.addSubview(copyrightLabel)
serveButton = UIButton(type: .custom)
self.addSubview(serveButton)
tortButton = UIButton(type: .custom)
self.addSubview(tortButton)
}
func addSnap() {
titleLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(self)
make.top.equalTo(30)
}
admireButton.snp.makeConstraints { (make) in
make.size.equalTo(CGSize(width: 75, height: 32))
make.centerX.equalTo(self)
make.top.equalTo(titleLabel.snp.bottom).offset(10)
}
admireLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(self)
make.top.equalTo(admireButton.snp.bottom).offset(20)
}
copyrightLabel.snp.makeConstraints { (make) in
make.top.equalTo(admireLabel.snp.bottom).offset(20)
make.centerX.equalTo(self)
}
}
func setupInfo() {
guard let author = emoticonPackage.author else {
return
}
titleLabel.text = "我用小心心换红包了啦"
let highlightBorder = YYTextBorder()
highlightBorder.insets = UIEdgeInsets(top: -2, left: 0, bottom: -2, right: 2)
highlightBorder.fillColor = UIColor.clear
let nameText = NSMutableAttributedString(string: "9175")
nameText.yy_color = UIColor(hex: "#576b95")
nameText.yy_font = UIFont.systemFont(ofSize: 13)
let hightLight = YYTextHighlight()
hightLight.setBackgroundBorder(highlightBorder)
nameText.yy_setTextHighlight(hightLight, range: NSMakeRange(0, nameText.length))
let admireAttri = NSMutableAttributedString()
admireAttri.append(nameText)
let textAttri = NSMutableAttributedString(string: "人已赞赏")
textAttri.yy_color = UIColor(hex: "#666")
textAttri.yy_font = UIFont.systemFont(ofSize: 13)
admireAttri.append(textAttri)
admireLabel.attributedText = admireAttri
copyrightLabel.text = "Copyright © \(author.name)"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
2b52adb673ca51652a607c0044547a41
| 27.664286 | 88 | 0.602791 | false | false | false | false |
HTWDD/htwcampus
|
refs/heads/develop
|
HTWDD/Components/Grades/Main/GradeMainVC.swift
|
mit
|
1
|
//
// GradeMainVC.swift
// HTWDD
//
// Created by Benjamin Herzog on 30/11/2016.
// Copyright © 2016 HTW Dresden. All rights reserved.
//
import UIKit
import RxSwift
class GradeMainVC: CollectionViewController {
enum Const {
static let margin: CGFloat = 10
}
var auth: GradeService.Auth? {
set { self.dataSource.auth = newValue }
get { return nil }
}
private lazy var dataSource = GradeDataSource(context: self.context)
private let refreshControl = UIRefreshControl()
private var selectedIndexPath: IndexPath?
private let layout = CollectionViewFlowLayout()
let context: HasGrade
// MARK: - Init
init(context: HasGrade) {
self.context = context
super.init(layout: self.layout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func initialSetup() {
super.initialSetup()
self.title = Loca.Grades.title
self.tabBarItem.image = #imageLiteral(resourceName: "Grade")
}
// MARK: - ViewController lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.contentInset = UIEdgeInsets(top: Const.margin,
left: Const.margin,
bottom: Const.margin,
right: Const.margin)
self.refreshControl.addTarget(self, action: #selector(reload), for: .valueChanged)
self.refreshControl.tintColor = .white
if #available(iOS 11.0, *) {
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationItem.largeTitleDisplayMode = .automatic
self.collectionView.refreshControl = self.refreshControl
} else {
self.collectionView.add(self.refreshControl)
}
self.dataSource.collectionView = self.collectionView
self.dataSource.register(type: GradeAverageCell.self)
self.dataSource.register(type: GradeCell.self) { [weak self] cell, _, indexPath in
if self?.selectedIndexPath == indexPath {
cell.updatedExpanded(true)
}
}
self.dataSource.registerSupplementary(CollectionHeaderView.self, kind: .header) { [weak self] view, indexPath in
guard let information = self?.dataSource.information(for: indexPath.section) else {
view.attributedTitle = nil
return
}
let semesterTitle = information.semester.localized
let attributedTitle = NSAttributedString(string: (semesterTitle),
attributes: [.foregroundColor: UIColor.htw.textHeadline, .font: UIFont.systemFont(ofSize: 22, weight: .bold)])
let averageTitle = NSAttributedString(string: Loca.Grades.average(information.average),
attributes: [.foregroundColor: UIColor.htw.textBody, .font: UIFont.systemFont(ofSize: 16, weight: .semibold)])
view.attributedTitle = attributedTitle + " " + averageTitle
}
let loading = self.dataSource.loading.filter { $0 == true }
let notLoading = self.dataSource.loading.filter { $0 != true }
loading
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] _ in
self?.setLoading(true)
})
.disposed(by: self.rx_disposeBag)
notLoading
.delay(0.5, scheduler: MainScheduler.instance)
.subscribe(onNext: { [weak self] _ in
self?.refreshControl.endRefreshing()
self?.setLoading(false)
})
.disposed(by: self.rx_disposeBag)
self.reload()
}
override func noResultsViewConfiguration() -> NoResultsView.Configuration? {
return .init(title: Loca.Grades.noResults.title, message: Loca.Grades.noResults.message, image: nil)
}
// MARK: - Private
@objc private func reload() {
self.dataSource.load()
}
// MARK: - Actions
private func showAlert(error: Error) {
let alert = UIAlertController(title: "Fehler", message: "Some failure in loading: \(error.localizedDescription)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
// MARK: - UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let _ = collectionView.cellForItem(at: indexPath) as? GradeCell else { return }
func animate(block: @escaping () -> Void) {
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: [.beginFromCurrentState, .curveEaseInOut], animations: block, completion: nil)
}
if self.selectedIndexPath == indexPath {
self.selectedIndexPath = nil
animate {
collectionView.reloadItems(at: [indexPath])
}
return
}
let currentSelected = self.selectedIndexPath
self.selectedIndexPath = indexPath
let indexPaths = [indexPath] + (currentSelected.map { [$0] } ?? [])
animate {
collectionView.reloadItems(at: indexPaths)
}
let oldCell = currentSelected.flatMap(collectionView.cellForItem) as? GradeCell
oldCell?.updatedExpanded(false)
let newCell = collectionView.cellForItem(at: indexPath) as? GradeCell
newCell?.updatedExpanded(true)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension GradeMainVC {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = self.itemWidth(collectionView: collectionView)
let height: CGFloat
if self.selectedIndexPath == indexPath {
height = GradeCell.Const.expandedHeight
} else {
height = GradeCell.Const.collapsedHeight
}
return CGSize(width: width, height: height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section == 0 {
return CGSize(width: self.itemWidth(collectionView: collectionView), height: 20)
}
return CGSize(width: self.itemWidth(collectionView: collectionView), height: 60)
}
}
extension GradeMainVC: TabbarChildViewController {
func tabbarControllerDidSelectAlreadyActiveChild() {
self.collectionView.setContentOffset(CGPoint(x: self.collectionView.contentOffset.x, y: -self.view.htw.safeAreaInsets.top), animated: true)
}
}
|
db2d30602ffc66ef8849b053bd7e02b3
| 35.431472 | 200 | 0.62352 | false | false | false | false |
brentsimmons/Evergreen
|
refs/heads/ios-candidate
|
iOS/Add/AddFeedViewController.swift
|
mit
|
1
|
//
// AddFeedViewController.swift
// NetNewsWire
//
// Created by Maurice Parker on 4/16/19.
// Copyright © 2019 Ranchero Software, LLC. All rights reserved.
//
import UIKit
import Account
import RSCore
import RSTree
import RSParser
enum AddFeedType {
case web
case reddit
case twitter
}
class AddFeedViewController: UITableViewController {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var addButton: UIBarButtonItem!
@IBOutlet weak var urlTextField: UITextField!
@IBOutlet weak var urlTextFieldToSuperViewConstraint: NSLayoutConstraint!
@IBOutlet weak var nameTextField: UITextField!
static let preferredContentSizeForFormSheetDisplay = CGSize(width: 460.0, height: 400.0)
private var folderLabel = ""
private var userCancelled = false
var addFeedType = AddFeedType.web
var initialFeed: String?
var initialFeedName: String?
var container: Container?
override func viewDidLoad() {
super.viewDidLoad()
switch addFeedType {
case .reddit:
navigationItem.title = NSLocalizedString("Add Reddit Feed", comment: "Add Reddit Feed")
navigationItem.leftBarButtonItem = nil
case .twitter:
navigationItem.title = NSLocalizedString("Add Twitter Feed", comment: "Add Twitter Feed")
navigationItem.leftBarButtonItem = nil
default:
break
}
activityIndicator.isHidden = true
activityIndicator.color = .label
if initialFeed == nil, let urlString = UIPasteboard.general.string {
if urlString.mayBeURL {
initialFeed = urlString.normalizedURL
}
}
urlTextField.autocorrectionType = .no
urlTextField.autocapitalizationType = .none
urlTextField.text = initialFeed
urlTextField.delegate = self
if initialFeed != nil {
addButton.isEnabled = true
}
nameTextField.text = initialFeedName
nameTextField.delegate = self
if let defaultContainer = AddWebFeedDefaultContainer.defaultContainer {
container = defaultContainer
} else {
addButton.isEnabled = false
}
updateFolderLabel()
tableView.register(UINib(nibName: "AddFeedSelectFolderTableViewCell", bundle: nil), forCellReuseIdentifier: "AddFeedSelectFolderTableViewCell")
NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: urlTextField)
if initialFeed == nil {
urlTextField.becomeFirstResponder()
}
}
@IBAction func cancel(_ sender: Any) {
userCancelled = true
dismiss(animated: true)
}
@IBAction func add(_ sender: Any) {
let urlString = urlTextField.text ?? ""
let normalizedURLString = urlString.normalizedURL
guard !normalizedURLString.isEmpty, let url = URL(unicodeString: normalizedURLString) else {
return
}
guard let container = container else { return }
var account: Account?
if let containerAccount = container as? Account {
account = containerAccount
} else if let containerFolder = container as? Folder, let containerAccount = containerFolder.account {
account = containerAccount
}
if account!.hasWebFeed(withURL: url.absoluteString) {
presentError(AccountError.createErrorAlreadySubscribed)
return
}
addButton.isEnabled = false
activityIndicator.isHidden = false
activityIndicator.startAnimating()
let feedName = (nameTextField.text?.isEmpty ?? true) ? nil : nameTextField.text
BatchUpdate.shared.start()
account!.createWebFeed(url: url.absoluteString, name: feedName, container: container, validateFeed: true) { result in
BatchUpdate.shared.end()
switch result {
case .success(let feed):
self.dismiss(animated: true)
NotificationCenter.default.post(name: .UserDidAddFeed, object: self, userInfo: [UserInfoKey.webFeed: feed])
case .failure(let error):
self.addButton.isEnabled = true
self.activityIndicator.isHidden = true
self.activityIndicator.stopAnimating()
self.presentError(error)
}
}
}
@objc func textDidChange(_ note: Notification) {
updateUI()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: "AddFeedSelectFolderTableViewCell", for: indexPath) as? AddFeedSelectFolderTableViewCell
cell!.detailLabel.text = folderLabel
return cell!
} else {
return super.tableView(tableView, cellForRowAt: indexPath)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 2 {
let navController = UIStoryboard.add.instantiateViewController(withIdentifier: "AddWebFeedFolderNavViewController") as! UINavigationController
navController.modalPresentationStyle = .currentContext
let folderViewController = navController.topViewController as! AddFeedFolderViewController
folderViewController.delegate = self
folderViewController.addFeedType = addFeedType
folderViewController.initialContainer = container
present(navController, animated: true)
}
}
}
// MARK: AddWebFeedFolderViewControllerDelegate
extension AddFeedViewController: AddFeedFolderViewControllerDelegate {
func didSelect(container: Container) {
self.container = container
updateFolderLabel()
AddWebFeedDefaultContainer.saveDefaultContainer(container)
}
}
// MARK: UITextFieldDelegate
extension AddFeedViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
// MARK: Private
private extension AddFeedViewController {
func updateUI() {
addButton.isEnabled = (urlTextField.text?.mayBeURL ?? false)
}
func updateFolderLabel() {
if let containerName = (container as? DisplayNameProvider)?.nameForDisplay {
if container is Folder {
folderLabel = "\(container?.account?.nameForDisplay ?? "") / \(containerName)"
} else {
folderLabel = containerName
}
tableView.reloadData()
}
}
}
|
2b5167858f48e64c10c8459d34844c78
| 26.943925 | 153 | 0.753177 | false | false | false | false |
ebuilderCCO/DDC-SDK-Public
|
refs/heads/master
|
ios/example-app-swift/iddc-swift/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// iddc-swift
//
// Created by Zhihui Tang on 2017-10-11.
// Copyright © 2017 Crafttang. All rights reserved.
//
import UIKit
import iddc
import AdSupport
class ViewController: UIViewController {
@IBOutlet weak var labelResult: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "DDC(\(DeviceDataCollector.versionInfo))"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonPressed(_ sender: UIButton) {
let ddc = DeviceDataCollector.getDefault(key: "YOUR_LICENCE_KEY")
ddc.externalUserID = "c23911a2-c455-4a59-96d0-c6fea09176b8"
ddc.phoneNumber = "+1234567890"
let asIdMng = ASIdentifierManager.shared()
if asIdMng.isAdvertisingTrackingEnabled {
ddc.advertisingID = asIdMng.advertisingIdentifier.uuidString
} else {
ddc.advertisingID = "00000000-0000-0000-0000-000000000000"
}
ddc.run { error in
if let err = error {
print("\(err.description)")
}
}
}
}
|
43bf69bb9acfc1b443257013bec212c0
| 24.22449 | 74 | 0.622977 | false | false | false | false |
schluchter/berlin-transport
|
refs/heads/master
|
berlin-transport/berlin-trnsprt/BTConnection.swift
|
mit
|
1
|
//
// BTConnection.swift
// berlin-transport
//
// Created by Thomas Schluchter on 10/1/14.
// Copyright (c) 2014 Thomas Schluchter. All rights reserved.
//
import Foundation
import CoreLocation
import Ono
public typealias Meters = UInt
public protocol BTConnectionSegment {
var start: BTPoint {get}
var end: BTPoint {get}
var duration: NSTimeInterval? {get}
}
public struct BTJourney: BTConnectionSegment {
public let start: BTPoint
public let end: BTPoint
public let duration: NSTimeInterval?
public let line: BTServiceDescription
public let passList: [BTStation]?
}
public struct BTWalk: BTConnectionSegment {
public let start: BTPoint
public let end: BTPoint
public let duration: NSTimeInterval?
public let distance: Meters?
}
public struct BTGisRoute: BTConnectionSegment {
public let start: BTPoint
public let end: BTPoint
public let duration: NSTimeInterval?
public let distance: Meters?
public let trafficType: IndividualTrafficType
public enum IndividualTrafficType {
case Foot
case Bike
case Car
case Taxi
}
}
public struct BTTransfer: BTConnectionSegment {
public let start: BTPoint
public let end: BTPoint
public let duration: NSTimeInterval?
}
public struct BTConnection {
public var startDate: NSDate
public var endDate: NSDate
public var travelTime: NSTimeInterval
public var numberOfTransfers: UInt
public var start: BTPoint
public var end: BTPoint
public var segments: [BTConnectionSegment]?
init(xml: ONOXMLElement) {
let overViewEl = xml.firstChildWithTag("Overview")
let segmentListEl = xml.firstChildWithTag("ConSectionList")
let connectionBaseDate = overViewEl.firstChildWithTag("Date").dateValue()
self.startDate = BTConResParser.dateTimeFromElement(overViewEl.firstChildWithXPath(".//Departure//Time"), baseDate: connectionBaseDate)!
self.endDate = BTConResParser.dateTimeFromElement(overViewEl.firstChildWithXPath(".//Arrival//Time"), baseDate: connectionBaseDate)!
self.travelTime = BTConResParser.timeIntervalForElement(xml.firstChildWithXPath(".//Duration/Time"))
self.numberOfTransfers = xml.firstChildWithXPath("//Transfers").numberValue().unsignedLongValue
self.start = BTConResParser.pointFromElement(overViewEl.firstChildWithTag("Departure"))!
self.end = BTConResParser.pointFromElement(overViewEl.firstChildWithTag("Arrival"))!
self.segments = BTConResParser.segmentsForJourney(segmentListEl)
}
}
|
afa6d7ca0b7dd7f954c4825ee3203b0c
| 31.197531 | 144 | 0.727656 | false | false | false | false |
chenzhe555/core-ios-swift
|
refs/heads/master
|
core-ios-swift/Framework_swift/CustomView/custom/LoadingView/MCActivityLoadingView_s.swift
|
mit
|
1
|
//
// MCActivityLoadingView_s.swift
// core-ios-swift
//
// Created by mc962 on 16/2/28.
// Copyright © 2016年 陈哲是个好孩子. All rights reserved.
//
import UIKit
public class MCActivityLoadingView_s: BaseLoadingView_s {
//MARK: *************** .h(Protocal Enum ...)
//MARK: *************** .h(Property Method ...)
static var onceToken: dispatch_once_t = 0;
static var customLoadingView: MCActivityLoadingView_s!
public class func shareManager() -> MCActivityLoadingView_s! {
dispatch_once(&onceToken) { () -> Void in
customLoadingView = super.getInstance() as! MCActivityLoadingView_s;
MCKitTool_s.getMainWindow()?.insertSubview(customLoadingView, atIndex: kMCActivityViewInsertIndex);
};
return customLoadingView;
}
public func showMCActivityView(topSpace: CGFloat,bottomSpace: CGFloat,labelText: String?) -> Void {
super.initTheme();
self.frame = CGRectMake(self.x, topSpace, self.width, SCREENH - topSpace - bottomSpace);
if(labelText == nil)
{
self.bgView.frame = CGRectMake((self.width - kMCActivityViewNoTextBGWidth)/2, (self.height - kMCActivityViewNoTextBGHeight)/2, kMCActivityViewNoTextBGWidth, kMCActivityViewNoTextBGHeight);
self.activity.center = CGPointMake(self.bgView.width/2, self.bgView.height/2);
self.contentLabel.hidden = true;
}
else
{
self.contentLabel.text = labelText;
self.bgView.frame = CGRectMake((self.width - kMCActivityViewBGWidth)/2, (self.height - kMCActivityViewBGHeight)/2, kMCActivityViewBGWidth, kMCActivityViewBGHeight);
self.activity.center = CGPointMake(self.bgView.width/2, self.bgView.height/2 - 15);
self.contentLabel.frame = CGRectMake((self.bgView.width - self.contentLabel.width)/2, self.bgView.height - self.contentLabel.height - 15, self.contentLabel.width, self.contentLabel.height);
self.contentLabel.hidden = false;
}
self.activity.startAnimating();
}
override public func stopLoadingView() {
self.activity.stopAnimating();
super.stopLoadingView();
}
//MARK: *************** .m(Category ...)
//MCActivityView宽高(带文字)
let kMCActivityViewBGWidth:CGFloat = 120.0
let kMCActivityViewBGHeight:CGFloat = 120.0
//MCActivityView宽高(不带文字)
let kMCActivityViewNoTextBGWidth:CGFloat = 70.0
let kMCActivityViewNoTextBGHeight:CGFloat = 70.0
//文字距bgView左右间隙
let kMCActivityViewLeftSpace:CGFloat = 6.0
//菊花转
private var activity: UIActivityIndicatorView!;
//显示文本
private var contentLabel: MCLabel_s!;
//MARK: *************** .m(Method ...)
override public init(frame: CGRect) {
super.init(frame: frame);
self.activity = UIActivityIndicatorView();
self.activity.activityIndicatorViewStyle = .WhiteLarge;
self.bgView.addSubview(self.activity);
self.contentLabel = MCLabel_s();
self.contentLabel.limitWidth = (kMCActivityViewBGWidth - kMCActivityViewLeftSpace*2);
self.contentLabel.font = UIFont.systemFontOfSize(14.0);
self.contentLabel.textAlignment = .Center;
self.contentLabel.textColor = UIColor.whiteColor();
self.bgView.addSubview(self.contentLabel);
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
}
|
a78741cbc52aa2edd915f6086aca9e52
| 35.71875 | 201 | 0.646241 | false | false | false | false |
5lucky2xiaobin0/PandaTV
|
refs/heads/master
|
PandaTV/PandaTV/Classes/Main/Controller/ShowBasicVC.swift
|
mit
|
1
|
//
// ShowBasicVC.swift
// PandaTV
//
// Created by 钟斌 on 2017/3/24.
// Copyright © 2017年 xiaobin. All rights reserved.
//
import UIKit
import MJRefresh
let AcellID = "cellID"
class ShowBasicVC: UIViewController {
var viewItem : ShowBasicVM = ShowBasicVM()
var index = 0
lazy var loadImageView : LoadImageView = {
let vc = LoadImageView.getView()
vc.frame = self.view.bounds
return vc
}()
lazy var scrollImageView : CycleView = {
let cycleVC = CycleView.getView()
cycleVC.frame = CGRect(x: 0, y: -cycleViewH, width: screenW, height: cycleViewH)
cycleVC.backgroundColor = UIColor.red
return cycleVC
}()
lazy var showCollectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = gameItemMargin
layout.minimumInteritemSpacing = gameItemMargin
layout.headerReferenceSize = CGSize(width: screenW, height: gameItemMargin)
layout.sectionInset = UIEdgeInsetsMake(0, gameItemMargin, 0, gameItemMargin)
let allView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
allView.register(UINib(nibName: "GameCell", bundle: nil), forCellWithReuseIdentifier: gameCell)
allView.register(UINib(nibName: "ShowCell", bundle: nil), forCellWithReuseIdentifier: showCell)
allView.register(UINib(nibName: "HeaderCell", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerCell)
allView.register(UINib(nibName: "FooterCell", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: footerCell)
allView.register(UINib(nibName: "GameThumbImageCell", bundle: nil) , forCellWithReuseIdentifier: thundimageCell)
allView.backgroundColor = UIColor.white
allView.showsVerticalScrollIndicator = false
allView.showsHorizontalScrollIndicator = false
allView.dataSource = self
allView.delegate = self
return allView
}()
override func viewDidLoad() {
super.viewDidLoad()
//添加子控件
setUI()
//设置加载图片
setLoadImage()
//手动加载数据 第一次直接使用MJRefresh会有个非常别扭的视觉效果
loadData()
}
override func viewDidLayoutSubviews() {
let layout = showCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: gameItemW, height: gameItemH)
showCollectionView.frame = self.view.bounds
}
}
// MARK: - UI设置
extension ShowBasicVC {
func setUI(){
showCollectionView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadData))
showCollectionView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
view.addSubview(showCollectionView)
}
func setLoadImage() {
view.addSubview(loadImageView)
loadImageView.startAnimation()
}
func removeLoadImage() {
loadImageView.stopAnimation()
loadImageView.removeFromSuperview()
}
}
// MARK: - 加载数据
extension ShowBasicVC {
func loadData(){
}
func loadMoreData(){
}
}
extension ShowBasicVC : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewItem.itemArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: gameCell, for: indexPath) as! GameCell
let item = viewItem.itemArr[indexPath.item]
cell.gameItem = item
return cell
}
}
|
d288489a5ba169e4d7ac07042d3c376d
| 31.048387 | 166 | 0.681429 | false | false | false | false |
davidozhang/spycodes
|
refs/heads/master
|
Spycodes/Views/SCTableViewCell.swift
|
mit
|
1
|
import ISEmojiView
import UIKit
protocol SCTableViewCellEmojiDelegate: class {
func tableViewCell(onEmojiSelected emoji: String)
}
class SCTableViewCell: UITableViewCell {
weak var emojiDelegate: SCTableViewCellEmojiDelegate?
var indexPath: IndexPath?
enum InputType: Int {
case regular = 0
case emoji = 1
}
@IBOutlet weak var leftLabel: SCLabel!
@IBOutlet weak var primaryLabel: SCLabel!
@IBOutlet weak var secondaryLabel: SCLabel!
@IBOutlet weak var rightLabel: SCLabel!
@IBOutlet weak var rightImage: UIImageView!
@IBOutlet weak var rightTextView: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
if let _ = self.leftLabel {
// Pregame modal info view cell specific
self.leftLabel.font = SCFonts.regularSizeFont(.regular)
}
if let _ = self.primaryLabel {
self.primaryLabel.font = SCFonts.intermediateSizeFont(.regular)
}
if let _ = self.secondaryLabel {
self.secondaryLabel.font = SCFonts.smallSizeFont(.regular)
self.secondaryLabel.numberOfLines = 2
}
if let _ = self.rightLabel {
self.rightLabel.font = SCFonts.intermediateSizeFont(.bold)
}
if let _ = self.rightTextView {
self.rightTextView.font = SCFonts.intermediateSizeFont(.regular)
self.rightTextView.tintColor = .clear
}
self.backgroundColor = .clear
self.selectionStyle = .none
}
func setInputView(inputType: InputType) {
switch inputType {
case .regular:
break
case .emoji:
let emojiView = ISEmojiView()
emojiView.delegate = self
self.rightTextView.inputView = emojiView
}
}
}
extension SCTableViewCell: ISEmojiViewDelegate {
func emojiViewDidSelectEmoji(emojiView: ISEmojiView, emoji: String) {
self.rightTextView.text = emoji
self.rightTextView.resignFirstResponder()
self.emojiDelegate?.tableViewCell(onEmojiSelected: emoji)
}
func emojiViewDidPressDeleteButton(emojiView: ISEmojiView) {
self.rightTextView.text = ""
}
}
|
a34bfa05c59ac77d7851854ecc1b6983
| 28.223684 | 76 | 0.648357 | false | false | false | false |
itsProf/quito-seguro-ios
|
refs/heads/master
|
Quito Seguro/Create Report/CreateReportViewController.swift
|
mit
|
1
|
//
// CreateReportViewController.swift
// Quito Seguro
//
// Created by Jorge Tapia on 4/11/16.
// Copyright © 2016 Prof Apps. All rights reserved.
//
import UIKit
import GoogleMaps
import Firebase
class CreateReportViewController: UIViewController {
@IBOutlet weak var sendButton: UIBarButtonItem!
@IBOutlet weak var offenseLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var mapView: GMSMapView!
@IBOutlet weak var pinImageView: UIImageView!
var hasUserLocation = false
var isInsideQuito = false
var report = [String: AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupMap()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
mapView.addObserver(self, forKeyPath: "myLocation", options: .New, context: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
validate()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
mapView.removeObserver(self, forKeyPath: "myLocation")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "myLocation" && object is GMSMapView {
if !hasUserLocation {
let myLocation: CLLocation = change![NSKeyValueChangeNewKey] as! CLLocation
if isValidCoordinate(myLocation.coordinate) {
mapView.animateToCameraPosition(GMSCameraPosition.cameraWithLatitude(myLocation.coordinate.latitude,
longitude: myLocation.coordinate.longitude, zoom: 17.0))
}
hasUserLocation = true
}
}
}
// MARK: - Actions
@IBAction func sendAction(sender: AnyObject) {
sendReport()
}
// MARK: - UI methods
private func setupUI() {
navigationController?.navigationBar.tintColor = UIColor.whiteColor()
mapView.layer.cornerRadius = 4.0
}
private func validate() {
if let offense = report["offense"] as? String {
offenseLabel.text = NSLocalizedString(offense, comment: "Localized offense")
}
if let date = report["date"] as? Double {
dateLabel.text = NSLocalizedString(AppUtils.formattedStringFromDate(date), comment: "Localized offense")
}
sendButton.enabled = report["offense"] != nil && report["date"] != nil && isInsideQuito
}
private func reset() {
report = [String: AnyObject]()
offenseLabel.text = "What happened?"
dateLabel.text = "When did it happen?"
setupMap()
}
// MARK: - Map methods
private func setupMap() {
mapView.delegate = self
mapView.myLocationEnabled = true
mapView.settings.compassButton = true
mapView.settings.indoorPicker = true
mapView.animateToCameraPosition(GMSCameraPosition.cameraWithLatitude(AppUtils.quitoLocation.coordinate.latitude,
longitude: AppUtils.quitoLocation.coordinate.longitude, zoom: 11.0))
mapView.clear()
drawBounds()
}
private func drawBounds() {
let path = GMSMutablePath()
path.addCoordinate(CLLocationCoordinate2D(latitude: -0.0413704, longitude: -78.5881530))
path.addCoordinate(CLLocationCoordinate2D(latitude: -0.3610194, longitude: -78.5881530))
path.addCoordinate(CLLocationCoordinate2D(latitude: -0.3610194, longitude: -78.4078789))
path.addCoordinate(CLLocationCoordinate2D(latitude: -0.0413704, longitude: -78.4078789))
path.addCoordinate(CLLocationCoordinate2D(latitude: -0.0413704, longitude: -78.5881530))
let polyline = GMSPolyline(path: path)
polyline.strokeColor = AppTheme.redColor
polyline.geodesic = true
polyline.map = mapView
}
private func isValidCoordinate(coordinate: CLLocationCoordinate2D) -> Bool {
return (coordinate.latitude < -0.0413704 && coordinate.latitude > -0.3610194) && (coordinate.longitude < -78.4078789 && coordinate.longitude > -78.5881530)
}
// MARK: - Firebase methods
private func sendReport() {
// TODO: allow report sending once per hour
let reportsRef = Firebase(url: "\(AppUtils.firebaseAppURL)/reports")
report["platform"] = "iOS"
let newReportRef = reportsRef.childByAutoId()
newReportRef.setValue(report, withCompletionBlock: { (error, ref) in
if error != nil {
dispatch_async(dispatch_get_main_queue()) {
AppUtils.presentAlertController("Error", message: error.localizedDescription, presentingViewController: self, completion: nil)
}
} else {
AppUtils.presentAlertController("Quito Seguro", message: NSLocalizedString("REPORT_SENT", comment: "Report sent message"), presentingViewController: self) {
dispatch_async(dispatch_get_main_queue()) {
self.reset()
self.validate()
self.tabBarController?.selectedIndex = 0
}
}
}
})
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let navigationController = segue.destinationViewController as! UINavigationController
if segue.identifier == "selectOffenseFromCreateSegue" {
let destinationViewController = navigationController.topViewController as! OffensesTableViewController
destinationViewController.delegate = self
}
if segue.identifier == "selectDateFromCreateSegue" {
let destinationViewController = navigationController.topViewController as! SelectDateViewController
destinationViewController.delegate = self
}
}
}
extension CreateReportViewController: GMSMapViewDelegate {
func mapView(mapView: GMSMapView, didChangeCameraPosition position: GMSCameraPosition) {
report["lat"] = position.target.latitude
report["lng"] = position.target.longitude
isInsideQuito = isValidCoordinate(CLLocationCoordinate2D(latitude: position.target.latitude, longitude: position.target.longitude))
validate()
}
}
|
649ace6d8384fb713de7808c8133b679
| 35.419355 | 172 | 0.634928 | false | false | false | false |
adolfrank/Swift_practise
|
refs/heads/master
|
20-day/20-day/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// 20-day
//
// Created by Hongbo Yu on 16/4/28.
// Copyright © 2016年 Frank. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textFieldView: UITextView!
@IBOutlet weak var bottomBar: UIView!
@IBOutlet weak var charCountLable: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
textFieldView.delegate = self
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyBoardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyBoardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
func keyBoardWillShow(note:NSNotification) {
let userInfo = note.userInfo
let keyBoardBounds = (userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let deltaY = keyBoardBounds.size.height
let animations:(() -> Void) = {
self.bottomBar.transform = CGAffineTransformMakeTranslation(0,-deltaY)
}
if duration > 0 {
let options = UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue << 16))
UIView.animateWithDuration(duration, delay: 0, options:options, animations: animations, completion: nil)
}else {
animations()
}
}
func keyBoardWillHide(note:NSNotification) {
let userInfo = note.userInfo
let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let animations:(() -> Void) = {
self.bottomBar.transform = CGAffineTransformIdentity
}
if duration > 0 {
let options = UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue << 16))
UIView.animateWithDuration(duration, delay: 0, options:options, animations: animations, completion: nil)
}else{
animations()
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
view.endEditing(true)
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let myTextViewString = textFieldView.text
charCountLable.text = "\(140 - myTextViewString.characters.count)"
if range.length > 140{
return false
}
let newLength = (myTextViewString?.characters.count)! + range.length
return newLength < 140
}
}
|
7c4db7c011cf7e7e3cbaba6d5b4c8bf4
| 33.6 | 171 | 0.653519 | false | false | false | false |
itsjingun/govhacknz_mates
|
refs/heads/master
|
Mates/Controllers/MTSMateDetailsViewController.swift
|
gpl-2.0
|
1
|
//
// MTSMateDetailsViewController.swift
// Mates
//
// Created by Eddie Chae on 4/07/15.
// Copyright (c) 2015 Governmen. All rights reserved.
//
import UIKit
class MTSMateDetailsViewController: MTSBaseViewController {
var userProfile: MTSUserProfile?
// UI Views
@IBOutlet weak var buttonSendRequest: UIButton!
@IBOutlet weak var labelNameAndAge: UILabel!
@IBOutlet weak var labelGender: UILabel!
@IBOutlet weak var labelLocation: UILabel!
@IBOutlet weak var labelTenants: UILabel!
@IBOutlet weak var labelAgeRange: UILabel!
@IBOutlet weak var labelOtherInfo: UILabel!
@IBAction func onSendRequestButtonTouch(sender: AnyObject) {
let requestService = MTSRequestService()
requestService.sendRequest(self.userProfile!,
success: { () -> () in
self.showAlertViewWithTitle("Request sent", message: "Your request was sent successfully!", onComplete: nil)
self.navigationController?.popViewControllerAnimated(true)
}) { (code, error) -> () in
self.showAlertViewWithTitle("Error", message: error, onComplete: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
private func setupViews() {
if self.userProfile == nil {
return
}
self.labelNameAndAge.text = userProfile!.username + ", " + String(userProfile!.age)
self.labelGender.text = userProfile!.genderString.uppercaseString
self.labelLocation.text = userProfile!.location
self.labelTenants.text = String(userProfile!.minNumberOfPeople) + " - " + String(userProfile!.maxNumberOfPeople) + " PEOPLE"
self.labelAgeRange.text = String(userProfile!.minAge) + " - " + String(userProfile!.maxAge) + " YEARS OLD"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
93f5c75d4d0ecc3f8ae468008dc489c3
| 33.285714 | 132 | 0.659167 | false | false | false | false |
wesj/firefox-ios-1
|
refs/heads/master
|
SyncTests/LiveStorageClientTests.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import FxA
import Shared
import Account
import XCTest
private class KeyFetchError: ErrorType {
var description: String {
return "key fetch error"
}
}
class LiveStorageClientTests : LiveAccountTest {
func getKeys(kB: NSData, token: TokenServerToken) -> Deferred<Result<Record<KeysPayload>>> {
let endpoint = token.api_endpoint
XCTAssertTrue(endpoint.rangeOfString("services.mozilla.com") != nil, "We got a Sync server.")
let cryptoURI = NSURL(string: endpoint + "/storage/")
let authorizer: Authorizer = {
(r: NSMutableURLRequest) -> NSMutableURLRequest in
let helper = HawkHelper(id: token.id, key: token.key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
r.addValue(helper.getAuthorizationValueFor(r), forHTTPHeaderField: "Authorization")
return r
}
let keyBundle: KeyBundle = KeyBundle.fromKB(kB)
let f: (JSON) -> KeysPayload = { return KeysPayload($0) }
let keysFactory: (String) -> KeysPayload? = Keys(defaultBundle: keyBundle).factory("crypto", f)
let workQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let resultQueue = dispatch_get_main_queue()
let storageClient = Sync15StorageClient(serverURI: cryptoURI!, authorizer: authorizer, workQueue: workQueue, resultQueue: resultQueue)
let keysFetcher = storageClient.collectionClient("crypto", factory: keysFactory)
return keysFetcher.get("keys").map({
// Unwrap the response.
res in
if let r = res.successValue {
return Result(success: r.value)
}
return Result(failure: KeyFetchError())
})
}
func getState(user: String, password: String) -> Deferred<Result<FxAState>> {
let err: NSError = NSError(domain: FxAClientErrorDomain, code: 0, userInfo: nil)
return Deferred(value: Result<FxAState>(failure: FxAClientError.Local(err)))
}
func getTokenAndDefaultKeys() -> Deferred<Result<(TokenServerToken, KeyBundle)>> {
let authState = self.syncAuthState(NSDate.now())
let keysPayload: Deferred<Result<Record<KeysPayload>>> = authState.bind {
tokenResult in
if let (token, forKey) = tokenResult.successValue {
return self.getKeys(forKey, token: token)
}
XCTAssertEqual(tokenResult.failureValue!.description, "")
return Deferred(value: Result(failure: KeyFetchError()))
}
let result = Deferred<Result<(TokenServerToken, KeyBundle)>>()
keysPayload.upon {
res in
if let rec = res.successValue {
XCTAssert(rec.id == "keys", "GUID is correct.")
XCTAssert(rec.modified > 1000, "modified is sane.")
let payload: KeysPayload = rec.payload as KeysPayload
println("Body: \(payload.toString(pretty: false))")
XCTAssert(rec.id == "keys", "GUID inside is correct.")
let arr = payload["default"].asArray![0].asString
if let keys = payload.defaultKeys {
// Extracting the token like this is not great, but...
result.fill(Result(success: (authState.value.successValue!.token, keys)))
return
}
}
result.fill(Result(failure: KeyFetchError()))
}
return result
}
func testLive() {
let expectation = expectationWithDescription("Waiting on value.")
let deferred = getTokenAndDefaultKeys()
deferred.upon {
res in
if let (token, keyBundle) = res.successValue {
println("Yay")
} else {
XCTAssertEqual(res.failureValue!.description, "")
}
expectation.fulfill()
}
// client: mgWl22CIzHiE
waitForExpectationsWithTimeout(20) { (error) in
XCTAssertNil(error, "\(error)")
}
}
func testStateMachine() {
let expectation = expectationWithDescription("Waiting on value.")
let authState = self.getAuthState(NSDate.now())
let d = chainDeferred(authState, SyncStateMachine.toReady)
d.upon { result in
if let ready = result.successValue {
XCTAssertTrue(ready.collectionKeys.defaultBundle.encKey.length == 32)
XCTAssertTrue(ready.scratchpad.global != nil)
if let clients = ready.scratchpad.global?.engines?["clients"] {
XCTAssertTrue(countElements(clients.syncID) == 12)
}
}
XCTAssertTrue(result.isSuccess)
expectation.fulfill()
}
waitForExpectationsWithTimeout(20) { (error) in
XCTAssertNil(error, "\(error)")
}
}
}
|
5fa75cd90eeb8c41c7cb76d6d81bab6e
| 38.6 | 142 | 0.607733 | false | false | false | false |
exsortis/TenCenturiesKit
|
refs/heads/master
|
Sources/TenCenturiesKit/Requests/Posts.swift
|
mit
|
1
|
import Foundation
public struct Posts {
/**
Delete a post.
- parameter postId: The ID of the post to delete.
*/
public static func delete(postId : Int) -> Request<DeleteResponse> {
let method = HTTPMethod.delete
return Request<DeleteResponse>(path: "/content/\(postId)", method: method, parse: Request<DeleteResponse>.parser)
}
// UNDOCUMENTED
// public static func edit() -> Request<Post> {
//
// }
//
// public static func list() -> Request<Post> {
//
// }
/**
Get one or more posts by ID.
- parameter postIds: An array of post IDs to retrieve.
*/
public static func get(postIds : [Int]) -> Request<[Post]> {
if postIds.count == 1,
let postId = postIds.first {
let method = HTTPMethod.get(Payload.empty)
return Request<[Post]>(path: "/content/\(postId)", method: method, parse: Request<[Post]>.parser)
}
let parameters = [
Parameter(name: "post_ids", value: postIds.map(String.init).joined(separator: ","))
]
let method = HTTPMethod.get(Payload.parameters(parameters))
return Request<[Post]>(path: "/content", method: method, parse: Request<[Post]>.parser)
}
// public static func search() -> Request<Post> {
//
// }
/**
Pin a post.
- parameter pin: The pin to apply to the post.
- parameter postId: The post to pin.
*/
public static func pin(_ pin : Pin, postId : Int) -> Request<Empty> {
let parameters = [
Parameter(name: "post_id", value: "\(postId)"),
Parameter(name: "colour", value: pin.rawValue),
]
let method = HTTPMethod.post(Payload.parameters(parameters))
return Request<Empty>(path: "/content/pin", method: method, parse: Request<Empty>.parser)
}
/**
Repost a post.
- parameter postId: The post to repost.
*/
public static func repost(postId : Int) -> Request<Post> {
let method = HTTPMethod.post(Payload.empty)
return Request<Post>(path: "/content/repost/\(postId)", method: method, parse: Request<Post>.parser)
}
/**
Star a post.
- parameter postId: The post to star.
*/
public static func star(postId : Int) -> Request<[Post]> {
let method = HTTPMethod.post(Payload.empty)
return Request<[Post]>(path: "/content/star/\(postId)", method: method, parse: Request<[Post]>.parser)
}
/**
Create a new post.
- parameter content: The text of the post.
- parameter title: The (optional) title of the post.
- parameter privacy: The privacy type of the post.
*/
public static func create(content : String, title : String? = nil, privacy : Privacy = .public) -> Request<Post> {
let parameters = [
Parameter(name: "content", value: content),
Parameter(name: "title", value: title.flatMap(toOptionalString)),
Parameter(name: "privacy_type", value: privacy.rawValue),
]
let method = HTTPMethod.post(Payload.parameters(parameters))
return Request<Post>(path: "/content", method: method, parse: Request<Post>.parser)
}
/**
Replies to a post.
- parameter to: The ID of the post being replied to.
- parameter content: The text of the post.
- parameter title: The (optional) title of the post.
- parameter privacy: The privacy type of the post.
*/
public static func reply(to postId : Int, content : String, title : String? = nil, privacy : Privacy = .public) -> Request<Post> {
let parameters = [
Parameter(name: "content", value: content),
Parameter(name: "reply_to", value: "\(postId)"),
Parameter(name: "title", value: title.flatMap(toOptionalString)),
Parameter(name: "privacy_type", value: privacy.rawValue),
]
let method = HTTPMethod.post(Payload.parameters(parameters))
return Request<Post>(path: "/content", method: method, parse: Request<Post>.parser)
}
}
|
c8279ca245a46b1b1223a6737cf37a41
| 31.637795 | 134 | 0.592521 | false | false | false | false |
Virpik/T
|
refs/heads/master
|
src/UI/TImage.swift
|
mit
|
1
|
//
// TImage.swift
// TDemo
//
// Created by Virpik on 26/10/2017.
// Copyright © 2017 Virpik. All rights reserved.
//
import Foundation
import UIKit
public extension UIImage {
var png: Data? {
return self.pngData()
}
var jpg: Data? {
return self.jpegData(compressionQuality: 0)
}
public static var defaultColor: UIColor {
return UIColor.red
}
public convenience init(color: UIColor, size: CGSize) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(cgImage: image!.cgImage!)
}
public static func image1x1(color: UIColor?) -> UIImage {
let color = color ?? self.defaultColor
let size = CGSize(width: 1, height: 1)
let image = UIImage(color: color, size: size)
return image
}
public static func image10x10(color: UIColor?) -> UIImage {
let color = color ?? self.defaultColor
let size = CGSize(width: 10, height: 10)
let image = UIImage(color: color, size: size)
return image
}
public static func image20x20(color: UIColor?) -> UIImage {
let color = color ?? self.defaultColor
let size = CGSize(width: 20, height: 20)
let image = UIImage(color: color, size: size)
return image
}
public static func image50x50(color: UIColor?) -> UIImage {
let color = color ?? self.defaultColor
let size = CGSize(width: 50, height: 50)
let image = UIImage(color: color, size: size)
return image
}
public static func image100x100(color: UIColor?) -> UIImage {
let color = color ?? self.defaultColor
let size = CGSize(width: 100, height: 100)
let image = UIImage(color: color, size: size)
return image
}
public static func imageBoundsScreen(color: UIColor?) -> UIImage {
let color = color ?? self.defaultColor
let size = UIScreen.main.bounds.size
let image = UIImage(color: color, size: size)
return image
}
//https://stackoverflow.com/questions/31314412/how-to-resize-image-in-swift
public func resize(size: CGSize) -> UIImage {
let image = self
let targetSize = size
let size = image.size
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
|
1e2fd66ed9339a699cc474a562b5a869
| 27.142857 | 96 | 0.578146 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.