repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
zhxnlai/UIColor-ChineseTraditionalColors
ChineseTraditionalColors/ChineseTraditionalColors/CTCCollectionViewCell.swift
1
1213
// // CTCCollectionViewCell.swift // ChineseTraditionalColors // // Created by Zhixuan Lai on 4/27/15. // Copyright (c) 2015 Zhixuan Lai. All rights reserved. // import UIKit class CTCCollectionViewCell: UICollectionViewCell { var color: UIColor? { didSet { if let color = color { contentView.backgroundColor = color } } } var attributedText: NSAttributedString? { didSet { if let attributedText = attributedText { label.attributedText = attributedText } } } private var label = UILabel() override init(frame: CGRect) { super.init(frame: frame) setup() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { contentView.addSubview(label) label.adjustsFontSizeToFitWidth = true label.numberOfLines = 0 } override func layoutSubviews() { super.layoutSubviews() let labelInset = UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15) label.frame = UIEdgeInsetsInsetRect(bounds, labelInset) } }
mit
5a81b556b229417830c3d42483b3cc9c
22.326923
79
0.582852
4.852
false
false
false
false
mkrisztian95/iOS
Tardis/BlogTableViewCellContent.swift
1
2505
// // BlogTableViewCellContent.swift // Tardis // // Created by Molnar Kristian on 7/22/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import Firebase @IBDesignable class BlogTableViewCellContent: UIView { var view: UIView! let storage = FIRStorage.storage() @IBOutlet weak var backgroundView: UIView! @IBOutlet weak var backgroundImage: UIImageView! @IBOutlet weak var briefView: UITextView! @IBOutlet weak var titleLabel: UILabel! var tapped = false func xibSetup() { view = loadViewFromNib() // use bounds not frame or it'll be offset view.frame = bounds // Make the view stretch with containing view view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] // Adding custom subview on top of our view (over any custom drawing > see note below) addSubview(view) } func loadViewFromNib() -> UIView { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: "BlogTableViewCellContent", bundle: bundle) let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView view.layer.cornerRadius = 5.0 return view } override init(frame: CGRect) { // 1. setup any properties here // 2. call super.init(frame:) super.init(frame: frame) // 3. Setup view from .xib file xibSetup() } func setUp(obj:[String:AnyObject], color:UIColor) { let storageRef = storage.referenceForURL("gs://tardis-x.appspot.com") let spaceRef = storageRef.child(obj["image"] as! String) // Fetch the download URL spaceRef.downloadURLWithCompletion { (URL, error) -> Void in if (error != nil) { // Handle any errors } else { // APPImages(). print( (URL?.absoluteString)!) APPImages().setUpBackground(self.backgroundImage, urlString: (URL?.absoluteString)!) // Get the download URL for 'images/stars.jpg' } } self.backgroundImage.image = UIImage(named: "Google")! self.titleLabel.text = obj["title"] as? String self.briefView.text = obj["brief"] as? String titleLabel.backgroundColor = color self.titleLabel.adjustsFontSizeToFitWidth = true } required init?(coder aDecoder: NSCoder) { // 1. setup any properties here // 2. call super.init(coder:) super.init(coder: aDecoder) // 3. Setup view from .xib file xibSetup() } }
apache-2.0
b4f04aaef01de6b88d14ee23df6cde95
27.454545
97
0.653355
4.317241
false
false
false
false
johansson/SwiftlyYelp
SwiftlyYelp/BusinessCell.swift
1
1235
// // BusinessCell.swift // SwiftlyYelp // // Created by Will Johansson on 2015-04-25. // Copyright (c) 2015 Will Johansson. All rights reserved. // import UIKit class BusinessCell: UITableViewCell { static let reuseId = "BusinessCellReuseId" @IBOutlet weak var businessImageView: UIImageView! @IBOutlet weak var businessNameLabel: UILabel! @IBOutlet weak var businessRatingImageView: UIImageView! @IBOutlet weak var businessReviewCountLabel: UILabel! @IBOutlet weak var businessAddressLabel: UILabel! @IBOutlet weak var businessCategoryLabel: UILabel! @IBOutlet weak var businessDistanceLabel: UILabel! @IBOutlet weak var businessPricinessLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() businessImageView.layer.cornerRadius = 3 businessImageView.clipsToBounds = true // not sure if I need this? Seems to work without? businessNameLabel.preferredMaxLayoutWidth = businessNameLabel.frame.size.width } override func layoutSubviews() { super.layoutSubviews() // ditto ^? businessNameLabel.preferredMaxLayoutWidth = businessNameLabel.frame.size.width } }
apache-2.0
bf639af04fbc90f015feea8d95feea18
30.666667
86
0.703644
4.920319
false
false
false
false
22377832/swiftdemo
TouchsDemo/TouchsDemo/DetailViewController.swift
1
1996
// // DetailViewController.swift // TouchsDemo // // Created by adults on 2017/4/5. // Copyright © 2017年 adults. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var label: UILabel! var sampleTitle: String! // Preview action items. lazy var previewActions: [UIPreviewActionItem] = { func previewActionForTitle(_ title: String, style: UIPreviewActionStyle = .default) -> UIPreviewAction { return UIPreviewAction(title: title, style: style) { previewAction, viewController in guard let detailViewController = viewController as? DetailViewController, let sampleTitle = detailViewController.sampleTitle else { return } print("\(previewAction.title) triggered from `DetailViewController` for item: \(sampleTitle)") } } let action1 = previewActionForTitle("Default Action") let action2 = previewActionForTitle("Destructive Action", style: .destructive) let subAction1 = previewActionForTitle("Sub Action 1") let subAction2 = previewActionForTitle("Sub Action 2") let groupedActions = UIPreviewActionGroup(title: "Sub Actions…", style: .default, actions: [subAction1, subAction2] ) return [action1, action2, groupedActions] }() // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() // Update the user interface for the detail item. if let sampleTitle = sampleTitle { label.text = sampleTitle } // Set up the detail view's `navigationItem`. navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem navigationItem.leftItemsSupplementBackButton = true } // MARK: Preview actions override var previewActionItems : [UIPreviewActionItem] { return previewActions } }
mit
f46b58396377c934b11872f0d9bb1cce
33.327586
125
0.649422
5.267196
false
false
false
false
jaanussiim/weather-scrape
Sources/Row.swift
1
1659
/* * Copyright 2016 JaanusSiim * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation struct Row { private(set) var columns: [Column] func column(named: String) -> Column? { return columns.filter({ $0.title == named}).first } mutating func append(columns: [Column]) { let nextColumns = self.columns + columns self.columns = nextColumns } func double(_ name: String) -> Double { guard let c = string(for: name) where c.characters.count > 0 else { return -1000 } return Double(c)! } func integer(_ name: String) -> Int { guard let c = string(for: name) where c.characters.count > 0 else { return -1000 } return Int(c)! } private func string(for name: String) -> String? { guard let s = column(named: name)?.value else { return nil } let stripped = s.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines()) let cleaned = stripped.replacingOccurrences(of: ",", with: ".") return cleaned } }
apache-2.0
5aac9f679b6d2297ba8a2b5e54955d11
28.625
88
0.620253
4.365789
false
false
false
false
Erin-Mounts/BridgeAppSDK
BridgeAppSDK/AppDelegate.swift
1
4494
/* Copyright (c) 2015, 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. */ import UIKit import ResearchKit @UIApplicationMain public class AppDelegate: UIResponder, UIApplicationDelegate { let healthStore = HKHealthStore() public var window: UIWindow? var containerViewController: ResearchContainerViewController? { return window?.rootViewController as? ResearchContainerViewController } public func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { let standardDefaults = NSUserDefaults.standardUserDefaults() if standardDefaults.objectForKey("ORKSampleFirstRun") == nil { ORKPasscodeViewController.removePasscodeFromKeychain() standardDefaults.setValue("ORKSampleFirstRun", forKey: "ORKSampleFirstRun") } // Appearance customization let pageControlAppearance = UIPageControl.appearance() pageControlAppearance.pageIndicatorTintColor = UIColor.lightGrayColor() pageControlAppearance.currentPageIndicatorTintColor = UIColor.blackColor() // Dependency injection. containerViewController?.injectHealthStore(healthStore) return true } public func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { lockApp() return true } public func applicationWillResignActive(application: UIApplication) { if ORKPasscodeViewController.isPasscodeStoredInKeychain() { // Hide content so it doesn't appear in the app switcher. containerViewController?.contentHidden = true } } public func applicationWillEnterForeground(application: UIApplication) { lockApp() } func lockApp() { /* Only lock the app if there is a stored passcode and a passcode controller isn't already being shown. */ guard ORKPasscodeViewController.isPasscodeStoredInKeychain() && !(containerViewController?.presentedViewController is ORKPasscodeViewController) else { return } window?.makeKeyAndVisible() let passcodeViewController = ORKPasscodeViewController.passcodeAuthenticationViewControllerWithText("Welcome back to ResearchKit Sample App", delegate: self) as! ORKPasscodeViewController containerViewController?.presentViewController(passcodeViewController, animated: false, completion: nil) } } extension AppDelegate: ORKPasscodeDelegate { public func passcodeViewControllerDidFinishWithSuccess(viewController: UIViewController) { containerViewController?.contentHidden = false viewController.dismissViewControllerAnimated(true, completion: nil) } public func passcodeViewControllerDidFailAuthentication(viewController: UIViewController) { } }
bsd-3-clause
595fa80336479893e88cd1bf1c08f075
43.49505
195
0.754339
5.968127
false
false
false
false
qvacua/vimr
NvimView/Support/DrawerPerf/AppDelegate.swift
1
1272
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import GameKit import os @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet var window: NSWindow! var result = [[[FontGlyphRun]]](repeating: [], count: count) func applicationDidFinishLaunching(_: Notification) { var results = [CFTimeInterval]() let repeatCount = 5 for _ in 0..<repeatCount { let rd = GKRandomDistribution( randomSource: GKMersenneTwisterRandomSource(seed: 129_384_832), lowestValue: 0, highestValue: repeatCount - 1 ) let indices = (0..<count).map { _ in rd.nextInt() % 3 } let time = self.measure { for i in 0..<count { result[i] = self.perf.render(indices[i]) } } results.append(time) } self.log.default( "\(results.reduce(0, +) / Double(results.count))s: \(results)" ) NSApp.terminate(self) } private let perf = PerfTester() private let log = OSLog( subsystem: "com.qvacua.DrawerPerf", category: "perf-tester" ) private func measure(_ body: () -> Void) -> CFTimeInterval { let start = CFAbsoluteTimeGetCurrent() body() return CFAbsoluteTimeGetCurrent() - start } } private let count = 500
mit
b0d8a8cae5f996946b6f79973facb47c
23
71
0.636006
3.987461
false
false
false
false
RedRoster/rr-ios
RedRoster/Roster/SubjectViewController.swift
1
7252
// // SubjectViewController.swift // RedRoster // // Created by Daniel Li on 3/28/16. // Copyright © 2016 dantheli. All rights reserved. // import UIKit class SubjectViewController: RosterViewController, UITableViewDataSource, UITableViewDelegate { var subject: Subject! var filteredCourses: [Course] = [] var searchField: SearchTextField! var searchLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() title = subject.abbreviation + " Courses" setupTableView() setupSearchField() fetch() } func setupSearchField() { searchField = SearchTextField(frame: CGRect(x: 0.0, y: 0.0, width: view.frame.width, height: 44.0)) searchField.autoresizingMask = [.flexibleWidth] searchField.leftMargin = 16.0 searchField.rightMargin = 16.0 searchField.delegate = self searchField.returnKeyType = .search searchField.clearButtonMode = .always searchField.alpha = 0.0 searchField.backgroundColor = UIColor.rosterSearchBackgroundColor() searchField.textColor = UIColor.darkGray searchField.font = UIFont.systemFont(ofSize: 14.0) let placeholder = NSAttributedString(string: "Search courses by number or title", attributes: [NSForegroundColorAttributeName : UIColor.lightGray, NSFontAttributeName : UIFont.systemFont(ofSize: 14.0)]) searchField.attributedPlaceholder = placeholder searchField.addTarget(self, action: #selector(textFieldChanged), for: .editingChanged) let border = UIView(frame: CGRect(x: 0.0, y: searchField.frame.height - 1.0, width: searchField.frame.width, height: 1.0)) border.backgroundColor = UIColor.rosterBackgroundColor() border.autoresizingMask = .flexibleWidth searchField.addSubview(border) view.addSubview(searchField) tableView.contentInset = UIEdgeInsets(top: searchField.frame.size.height, left: 0, bottom: 0, right: 0) tableView.scrollIndicatorInsets = UIEdgeInsets(top: searchField.frame.size.height, left: 0, bottom: 0, right: 0) } override func setupTableView() { super.setupTableView() tableView.dataSource = self tableView.delegate = self tableView.register(UINib(nibName: "CourseCell", bundle: nil), forCellReuseIdentifier: "CourseCell") tableView.rowHeight = 77.0 tableView.separatorColor = UIColor.rosterCellSeparatorColor() tableView.indicatorStyle = .black tableView.keyboardDismissMode = .onDrag searchLabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: self.tableView.frame.width, height: 44.0)) searchLabel.text = "" searchLabel.textColor = UIColor.rosterCellSubtitleColor() searchLabel.textAlignment = .center searchLabel.font = UIFont.systemFont(ofSize: 14.0) tableView.tableFooterView = searchLabel } override func fetch() { if subject.courses.isEmpty { setupActivityIndicator() tableView.alpha = 0.0 } setupNotification(subject.courses) NetworkManager.fetchCourses(subjectWithId: subject.id, andAbbreviation: subject.abbreviation, termSlug: subject.term?.slug ?? "") { error in if let error = error { self.alert(errorMessage: error.localizedDescription, completion: nil) } self.activityIndicator?.removeFromSuperview() } } override func configureTableView() { if !subject.courses.isEmpty { tableView.reloadData() UIView.animate(withDuration: 0.25, animations: { self.tableView.alpha = 1.0 self.searchField.alpha = 1.0 }) } } // MARK: TableView func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchField.text != "" ? filteredCourses.count : subject.courses.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CourseCell", for: indexPath) as! CourseCell let course = searchField.text != "" ? filteredCourses[indexPath.row] : subject.courses[indexPath.row] cell.backgroundColor = UIColor.rosterCellBackgroundColor() let subjectString = NSMutableAttributedString(string: "\(subject.abbreviation)", attributes: [NSForegroundColorAttributeName : UIColor.rosterRed()]) let numberString = NSMutableAttributedString(string: " \(course.activeCourseNumber)", attributes: [NSForegroundColorAttributeName : UIColor.rosterCellTitleColor()]) subjectString.append(numberString) cell.numberLabel.attributedText = subjectString cell.titleLabel.text = course.title cell.titleLabel.textColor = UIColor.rosterCellSubtitleColor() cell.titleLabel.sizeToFit() // cell.peopleicon.image = UIImage(named: "person") // cell.peopleicon.tintColor = UIColor.grayColor() // cell.peopleLabel.text = String(course.users.count) // cell.peopleLabel.textColor = UIColor.grayColor() cell.peopleicon.isHidden = true cell.peopleLabel.isHidden = true let background = UIView() background.backgroundColor = UIColor.rosterCellSelectionColor() cell.selectedBackgroundView = background return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let courseViewController = CourseViewController() courseViewController.course = searchField.text != "" ? filteredCourses[indexPath.row] : subject.courses[indexPath.row] courseViewController.schedule = schedule navigationController?.pushViewController(courseViewController, animated: true) } // MARK: - Search func filterTableView(forQuery query: String) { if query != "" { filteredCourses = subject.courses.filter { return $0.title.range(of: query, options: [.caseInsensitive]) != nil || $0.shortHand.range(of: query, options: [.caseInsensitive]) != nil } if filteredCourses.count == 0 { searchLabel.text = "No courses match your search." } else { searchLabel.text = "" } } else { searchLabel.text = "" } tableView.reloadData() } } extension SubjectViewController: UITextFieldDelegate { func textFieldShouldClear(_ textField: UITextField) -> Bool { filterTableView(forQuery: "") return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { view.endEditing(true) return true } func textFieldChanged() { filterTableView(forQuery: searchField.text ?? "") } }
apache-2.0
9438c377945840e3d255c3e0ddf3f931
38.194595
210
0.646256
5.168211
false
false
false
false
riteshhgupta/RGListKit
Pods/ReactiveCocoa/ReactiveCocoa/ObjC+RuntimeSubclassing.swift
2
5063
import ReactiveSwift /// Whether the runtime subclass has already been swizzled. fileprivate let runtimeSubclassedKey = AssociationKey(default: false) /// A known RAC runtime subclass of the instance. `nil` if the runtime subclass /// has not been requested for the instance before. fileprivate let knownRuntimeSubclassKey = AssociationKey<AnyClass?>(default: nil) extension NSObject { /// Swizzle the given selectors. /// /// - warning: The swizzling **does not** apply on a per-instance basis. In /// other words, repetitive swizzling of the same selector would /// overwrite previous swizzling attempts, despite a different /// instance being supplied. /// /// - parameters: /// - pairs: Tuples of selectors and the respective implementions to be /// swapped in. /// - key: An association key which determines if the swizzling has already /// been performed. internal func swizzle(_ pairs: (Selector, Any)..., key hasSwizzledKey: AssociationKey<Bool>) { let subclass: AnyClass = swizzleClass(self) try! ReactiveCocoa.synchronized(subclass) { let subclassAssociations = Associations(subclass as AnyObject) if !subclassAssociations.value(forKey: hasSwizzledKey) { subclassAssociations.setValue(true, forKey: hasSwizzledKey) for (selector, body) in pairs { let method = class_getInstanceMethod(subclass, selector)! let typeEncoding = method_getTypeEncoding(method)! if method_getImplementation(method) == _rac_objc_msgForward { let succeeds = class_addMethod(subclass, selector.interopAlias, imp_implementationWithBlock(body), typeEncoding) precondition(succeeds, "RAC attempts to swizzle a selector that has message forwarding enabled with a runtime injected implementation. This is unsupported in the current version.") } else { let succeeds = class_addMethod(subclass, selector, imp_implementationWithBlock(body), typeEncoding) precondition(succeeds, "RAC attempts to swizzle a selector that has already a runtime injected implementation. This is unsupported in the current version.") } } } } } } /// ISA-swizzle the class of the supplied instance. /// /// - note: If the instance has already been isa-swizzled, the swizzling happens /// in place in the runtime subclass created by external parties. /// /// - warning: The swizzling **does not** apply on a per-instance basis. In /// other words, repetitive swizzling of the same selector would /// overwrite previous swizzling attempts, despite a different /// instance being supplied. /// /// - parameters: /// - instance: The instance to be swizzled. /// /// - returns: The runtime subclass of the perceived class of the instance. internal func swizzleClass(_ instance: NSObject) -> AnyClass { if let knownSubclass = instance.associations.value(forKey: knownRuntimeSubclassKey) { return knownSubclass } let perceivedClass: AnyClass = instance.objcClass let realClass: AnyClass = object_getClass(instance)! let realClassAssociations = Associations(realClass as AnyObject) if perceivedClass != realClass { // If the class is already lying about what it is, it's probably a KVO // dynamic subclass or something else that we shouldn't subclass at runtime. synchronized(realClass) { let isSwizzled = realClassAssociations.value(forKey: runtimeSubclassedKey) if !isSwizzled { replaceGetClass(in: realClass, decoy: perceivedClass) realClassAssociations.setValue(true, forKey: runtimeSubclassedKey) } } return realClass } else { let name = subclassName(of: perceivedClass) let subclass: AnyClass = name.withCString { cString in if let existingClass = objc_getClass(cString) as! AnyClass? { return existingClass } else { let subclass: AnyClass = objc_allocateClassPair(perceivedClass, cString, 0)! replaceGetClass(in: subclass, decoy: perceivedClass) objc_registerClassPair(subclass) return subclass } } object_setClass(instance, subclass) instance.associations.setValue(subclass, forKey: knownRuntimeSubclassKey) return subclass } } private func subclassName(of class: AnyClass) -> String { return String(cString: class_getName(`class`)).appending("_RACSwift") } /// Swizzle the `-class` and `+class` methods. /// /// - parameters: /// - class: The class to swizzle. /// - perceivedClass: The class to be reported by the methods. private func replaceGetClass(in class: AnyClass, decoy perceivedClass: AnyClass) { let getClass: @convention(block) (UnsafeRawPointer?) -> AnyClass = { _ in return perceivedClass } let impl = imp_implementationWithBlock(getClass as Any) _ = class_replaceMethod(`class`, ObjCSelector.getClass, impl, ObjCMethodEncoding.getClass) _ = class_replaceMethod(object_getClass(`class`), ObjCSelector.getClass, impl, ObjCMethodEncoding.getClass) }
mit
6e3a2274294cf6f4d0bbc0ba01db9273
38.554688
186
0.708671
4.417976
false
false
false
false
sammyd/VT_InAppPurchase
prototyping/GreenGrocer/GreenGrocer/ShoppingListTableViewController.swift
1
3530
/* * 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 import CoreSpotlight class ShoppingListTableViewController: UITableViewController, DataStoreOwner, IAPContainer { var dataStore : DataStore? var iapHelper : IAPHelper? override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 70 } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataStore?.shoppingLists.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ShoppingListCell", forIndexPath: indexPath) if let cell = cell as? ShoppingListTableViewCell { cell.shoppingList = dataStore?.shoppingLists[indexPath.row] } return cell } // MARK: - Table view delegate override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { if let shoppingList = dataStore?.shoppingLists[indexPath.row] { dataStore?.removeShoppingList(shoppingList) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } } // 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?) { if let destVC = segue.destinationViewController as? ShoppingListViewController { let selectedRowIndex = tableView.indexPathForSelectedRow destVC.shoppingList = dataStore?.shoppingLists[selectedRowIndex?.row ?? 0] destVC.dataStore = dataStore } else if let destVC = segue.destinationViewController as? CreateShoppingListViewController { destVC.dataStore = dataStore destVC.iapHelper = iapHelper } } } extension ShoppingListTableViewController { @IBAction func unwindToShoppingListTableVC(unwindSegue: UIStoryboardSegue) { tableView.reloadData() } }
mit
984a40d7ea84862031b1c56c4962cc25
36.157895
155
0.750708
5.3003
false
false
false
false
orta/RxSwift
RxSwift/RxSwift/Observables/Implementations/Throttle.swift
1
4025
// // Throttle.swift // Rx // // Created by Krunoslav Zaher on 3/22/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class Throttle_<Element, SchedulerType: Scheduler> : Sink<Element>, ObserverType { typealias ParentType = Throttle<Element, SchedulerType> typealias ThrottleState = ( value: Element?, cancellable: SerialDisposable, id: UInt64 ) let parent: ParentType var lock = NSRecursiveLock() var throttleState: ThrottleState = ( value: nil, cancellable: SerialDisposable(), id: 0 ) init(parent: ParentType, observer: ObserverOf<Element>, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let cancellable = self.throttleState.cancellable let subscription = parent.source.subscribe(self) return CompositeDisposable(subscription, cancellable) } func on(event: Event<Element>) { switch event { case .Next: break case .Error: fallthrough case .Completed: throttleState.cancellable.dispose() break } var latestId = self.lock.calculateLocked { () -> UInt64 in let observer = self.observer var oldValue = self.throttleState.value self.throttleState.id = self.throttleState.id &+ 1 switch event { case .Next(let boxedValue): self.throttleState.value = boxedValue.value case .Error(let error): self.throttleState.value = nil self.observer.on(event) self.dispose() case .Completed: self.throttleState.value = nil if let value = oldValue { self.observer.on(.Next(Box(value))) } self.observer.on(.Completed) self.dispose() } return self.throttleState.id } switch event { case .Next(let boxedValue): let d = SingleAssignmentDisposable() self.throttleState.cancellable.setDisposable(d) let scheduler = self.parent.scheduler let dueTime = self.parent.dueTime let _ = scheduler.scheduleRelative(latestId, dueTime: dueTime) { (id) in return success(self.propagate()) } >== { disposeTimer -> Result<Void> in d.setDisposable(disposeTimer) return SuccessResult } >>! { e -> Result<Void> in self.lock.performLocked { self.observer.on(.Error(e)) self.dispose() } return SuccessResult } default: break } } func propagate() { var originalValue: Element? = self.lock.calculateLocked { var originalValue = self.throttleState.value self.throttleState.value = nil return originalValue } if let value = originalValue { self.observer.on(.Next(Box(value))) } } } class Throttle<Element, SchedulerType: Scheduler> : Producer<Element> { let source: Observable<Element> let dueTime: SchedulerType.TimeInterval let scheduler: SchedulerType init(source: Observable<Element>, dueTime: SchedulerType.TimeInterval, scheduler: SchedulerType) { self.source = source self.dueTime = dueTime self.scheduler = scheduler } override func run(observer: ObserverOf<Element>, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = Throttle_(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } }
mit
fc55d02b0593665d6bcc1ada79c6a657
29.270677
119
0.554534
5.166881
false
false
false
false
10686142/eChance
Iraffle/QuizLostVC.swift
1
1850
// // QuizLostVC.swift // Iraffle // // Created by Vasco Meerman on 03/05/2017. // Copyright © 2017 Vasco Meerman. All rights reserved. // import UIKit class QuizLostVC: UIViewController { @IBOutlet weak var rightAnswerLabel: UILabel! @IBOutlet weak var backHomeButton: UIButton! @IBOutlet weak var timerLabel: UILabel! // Timer let timeCheck = TimerCall() var seconds = 0 override func viewDidLoad() { super.viewDidLoad() // Set the timer let dateCompDict = timeCheck.getDateComponents() let secondsLeft = timeCheck.getSecondsLeft(dateDict: dateCompDict) seconds = secondsLeft runTimer() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func backHomeTapped(_ sender: Any) { let vc = storyboard?.instantiateViewController(withIdentifier: "homeVC") as! HomeVC present(vc, animated: true, completion: nil) } // This method call initializes the timer. It specifies the timeInterval (how often the a method will be called) and the selector (the method being called). func runTimer() { timeCheck.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(updateTimer)), userInfo: nil, repeats: true) timeCheck.isTimerRunning = true } func updateTimer() { // To stop so it doesn't go negative. if seconds < 1 { timeCheck.timer.invalidate() //Send alert to indicate "time's up!" } else { seconds -= 1 //This will decrement(count down)the seconds. timerLabel.text = timeCheck.timeString(time: TimeInterval(seconds)) //This will update the label. } } }
mit
4535ffd9d52ed81decc6a79a586e6fd2
30.87931
160
0.642509
4.509756
false
false
false
false
grigaci/Sensoriada
SensoriadaExample/Classes/GUI/Nodes/ViewController/SRAllNodesTableViewController.swift
1
1658
// // SRAllNodesTableViewController.swift // SensoriadaExample // // Created by bogdan on 09/01/15. // Copyright (c) 2015 Grigaci. All rights reserved. // import UIKit import Sensoriada class SRAllNodesTableViewController: UITableViewController { var datasource: SRAllNodesDatasource! @IBOutlet weak var syncBarButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() self.datasource = SRAllNodesDatasource(self.tableView) self.sync(nil) } @IBAction func sync(sender: AnyObject!) { self.syncBarButton.enabled = false self.datasource.reload({ (error) in if error != nil { self.showError(error!) } self.syncBarButton.enabled = true }) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "SRSensorViewControllerSegue" { let sensorViewController = segue.destinationViewController as SRSensorTableViewController if let cell = sender as? UITableViewCell { let indexPath = self.tableView.indexPathForCell(cell) let node = self.datasource!.allNodes[indexPath!.section] as SRSensorsNode let sensor = node.sensors[indexPath!.row] sensorViewController.sensor = sensor } } } private func showError(error: NSError) { let message = "Could not fetch data! Error: \(error)" let alertView = UIAlertView(title: "Error", message: message, delegate: nil, cancelButtonTitle: nil) alertView.show() } }
mit
08724dc957a271ac8d87391c07ed1b0d
30.283019
108
0.639928
4.778098
false
false
false
false
sopinetchat/SopinetChat-iOS
Pod/Views/SChatComposerTextView.swift
1
5111
// // SChatComposerTextView.swift // Pods // // Created by David Moreno Lora on 2/5/16. // // import UIKit import Foundation class SChatComposerTextView: UITextView { var placeHolder: String = NSBundle.sChatLocalizedStringForKey("schat_new_message") var placeHolderTextColor: UIColor = UIColor.lightGrayColor() // MARK: Initialization func sChatConfigureTextView() { self.translatesAutoresizingMaskIntoConstraints = false let cornerRadius: CGFloat = 6.0 self.backgroundColor = UIColor.whiteColor() self.layer.borderWidth = 0.5 self.layer.borderColor = UIColor.lightGrayColor().CGColor self.layer.cornerRadius = cornerRadius self.scrollIndicatorInsets = UIEdgeInsetsMake(cornerRadius, 0.0, cornerRadius, 0.0) self.textContainerInset = UIEdgeInsetsMake(4.0, 2.0, 4.0, 2.0) self.contentInset = UIEdgeInsetsMake(1.0, 0.0, 1.0, 0.0) self.scrollEnabled = true self.scrollsToTop = false self.userInteractionEnabled = true self.font = UIFont.systemFontOfSize(16.0) self.textColor = UIColor.blackColor() self.textAlignment = .Natural self.contentMode = .Redraw self.dataDetectorTypes = .None self.keyboardAppearance = .Default self.keyboardType = .Default self.returnKeyType = .Default self.text = "" self.sChatAddTextViewNotificationObservers() } override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) self.sChatConfigureTextView() } required public init?(coder: NSCoder) { super.init(coder: coder) self.sChatConfigureTextView() } // MARK: Composer TextView override func hasText() -> Bool { return self.text.sChatStringByTrimingWhitespace().characters.count > 0 } func setComposerText(text: String) { self.text = text self.setNeedsDisplay() } func setComposerFont(font: UIFont) { self.font = font self.setNeedsDisplay() } func setComposerTextAlignment(textAlignment: NSTextAlignment) { self.textAlignment = textAlignment self.setNeedsDisplay() } // MARK: Setters func setComposerPlaceHolder(placeHolder: String) { if placeHolder == self.placeHolder { return } self.placeHolder = placeHolder self.setNeedsDisplay() } func setComposerPlaceHolderTextColor(placeHolderTextColor: UIColor) { if placeHolderTextColor == self.placeHolderTextColor { return } self.placeHolderTextColor = placeHolderTextColor self.setNeedsDisplay() } // MARK: Drawing override func drawRect(rect: CGRect) { super.drawRect(rect) if self.text.characters.count == 0 { self.placeHolderTextColor.set() self.placeHolder.drawInRect(CGRectInset(rect, 7.0, 4.0), withAttributes: self.sChatPlaceHolderTextAttributes() as! [String : AnyObject]) } } // MARK: Utils func sChatPlaceHolderTextAttributes() -> NSDictionary { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = .ByTruncatingTail paragraphStyle.alignment = self.textAlignment return [NSFontAttributeName : self.font!, NSForegroundColorAttributeName: self.placeHolderTextColor, NSParagraphStyleAttributeName: paragraphStyle] } // MARK: Notifications func sChatAddTextViewNotificationObservers() { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.sChatDidReceiveTextViewNotification(_:)), name: UITextViewTextDidChangeNotification, object: self) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.sChatDidReceiveTextViewNotification(_:)), name: UITextViewTextDidBeginEditingNotification, object: self) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.sChatDidReceiveTextViewNotification(_:)), name: UITextViewTextDidEndEditingNotification, object: self) } func sChatRemoveTextViewNotificationObservers() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextViewTextDidChangeNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextViewTextDidBeginEditingNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextViewTextDidEndEditingNotification, object: nil) } func sChatDidReceiveTextViewNotification(notification: NSNotification) { self.setNeedsDisplay() } }
gpl-3.0
8ecb04fc9e853d6c78b19c0b0a2eea6c
29.789157
192
0.647036
5.672586
false
false
false
false
ShaneQi/ZEGBot
Sources/HelperTypes.swift
1
1248
// // HelperTypes.swift // ZEGBot // // Created by Shane Qi on 4/5/20. // /// Building a `Sendable` object to send message to. /// When you only want the bot to do things in a standalone manner instead of responding to incoming updates, /// you won't have the `Sendable` objects (like `Chat`, `Message`, etc.) to pass in sending methods, /// you can use this struct to build a `Sendable` object. /// /// e.g. bot.send(message: "hello", to: AnyChat(chatId: MY_CHANNEL_ID)) /// /// discussion: if `replyToMessageId` isn't nil, the receiver will be the message of the chat /// (new message will be sent in a replying manner). public struct AnyChat: Sendable, Replyable { public let chatId: Int public let replyToMessageId: Int? public init(chatId: Int, replyToMessageId: Int? = nil) { self.chatId = chatId self.replyToMessageId = replyToMessageId } } /// Building a `ForwardableMessage` object to forward. /// /// e.g. bot.forward(message: AnyMessage(chatId: MY_CHAT_ID, messageId: MY_MESSAGE_ID, to: AnyChat(chatId: MY_CHANNEL_ID)) public struct AnyMessage: ForwardableMessage { public let chatId: Int public let messageId: Int public init(chatId: Int, messageId: Int) { self.chatId = chatId self.messageId = messageId } }
apache-2.0
f831d6c2ca92dafca94c56683c6c7146
28.714286
122
0.710737
3.438017
false
false
false
false
TongLin91/Lazesnor
Lazesnor/Models/Route.swift
1
1665
// // Route.swift // Lazesnor // // Created by Tong Lin on 5/4/17. // Copyright © 2017 TongLin91. All rights reserved. // import Foundation class Route { let bounds: Bounds let overviewPolyline: String let distance: String let duration: String // let steps: [Step] let nullStringHandler = "No data available" init(_ dict: [String: Any]) { if let mapBounds = dict["bounds"] as? [String: [String: Double]]{ self.bounds = Bounds(mapBounds) }else{ self.bounds = Bounds([String: [String: Double]]()) } if let overview_polyline = dict["overview_polyline"] as? [String: String]{ self.overviewPolyline = overview_polyline["points"] ?? "" }else{ self.overviewPolyline = "" } guard let legs = dict["legs"] as? [Any], let leg = legs.first as? [String: Any] else{ print("No transit available to input destination.") self.distance = "not available" self.duration = "not available" // self.steps = [] return } if let distance = leg["distance"] as? [String: Any], let duration = leg["duration"] as? [String: Any] { self.distance = distance["text"] as? String ?? "" self.duration = duration["text"] as? String ?? "" }else{ self.distance = nullStringHandler self.duration = nullStringHandler } // if let steps = leg["steps"] as? [[String: Any]]{ // // } } }
mit
3215f4831fb0be927e99e25900b7bfbf
27.689655
82
0.51262
4.310881
false
false
false
false
ReactiveKit/ReactiveGitter
Carthage/Checkouts/Bond/Tests/BondTests/Helpers.swift
2
6166
// // Helpers.swift // Bond // // Created by Srdan Rasic on 29/08/16. // Copyright © 2016 Swift Bond. All rights reserved. // import XCTest @testable import ReactiveKit @testable import Bond func XCTAssertEqual(_ lhs: CGFloat, _ rhs: CGFloat, precision: CGFloat = 0.01, file: StaticString = #file, line: UInt = #line) { XCTAssert(abs(lhs - rhs) < precision, file: file, line: line) } extension Event { func isEqualTo(_ event: Event<Element, Error>) -> Bool { switch (self, event) { case (.completed, .completed): return true case (.failed, .failed): return true case (.next(let left), .next(let right)): if let left = left as? Int, let right = right as? Int { return left == right } else if let left = left as? Bool, let right = right as? Bool { return left == right } else if let left = left as? Float, let right = right as? Float { return left == right } else if let left = left as? [Int], let right = right as? [Int] { return left == right } else if let left = left as? (Int?, Int), let right = right as? (Int?, Int) { return left.0 == right.0 && left.1 == right.1 } else if let left = left as? String, let right = right as? String { return left == right } else if let left = left as? Date, let right = right as? Date { return left == right } else if let left = left as? [String], let right = right as? [String] { return left == right } else if let left = asOptional(left) as? Optional<String>, let right = asOptional(right) as? Optional<String> { return left == right } else if let left = left as? ObservableArrayEvent<Int>, let right = right as? ObservableArrayEvent<Int> { return left.change == right.change && (left.source === right.source || right.source === AnyObservableArray) } else if let left = left as? Observable2DArrayEvent<String, Int>, let right = right as? Observable2DArrayEvent<String, Int> { return left.change == right.change && (left.source === right.source || right.source === AnyObservable2DArray) } else if left is Void, right is Void { return true } else { fatalError("Cannot compare that element type. \(left)") } default: return false } } } private func asOptional(_ object: Any) -> Any? { let mirror = Mirror(reflecting: object) if mirror.displayStyle != .optional { return object } else if mirror.children.count == 0 { return nil } else { return mirror.children.first!.value } } extension SignalProtocol { func expectNext(_ expectedElements: [Element], _ message: @autoclosure () -> String = "", expectation: XCTestExpectation? = nil, file: StaticString = #file, line: UInt = #line) { expect(expectedElements.map { .next($0) } + [.completed], message, expectation: expectation, file: file, line: line) } func expect(_ expectedEvents: [Event<Element, Error>], _ message: @autoclosure () -> String = "", expectation: XCTestExpectation? = nil, file: StaticString = #file, line: UInt = #line) { var eventsToProcess = expectedEvents var receivedEvents: [Event<Element, Error>] = [] let message = message() let _ = observe { event in receivedEvents.append(event) if eventsToProcess.count == 0 { XCTFail("Got more events then expected.") return } let expected = eventsToProcess.removeFirst() XCTAssert(event.isEqualTo(expected), message + "(Got \(receivedEvents) instead of \(expectedEvents))", file: file, line: line) if event.isTerminal { expectation?.fulfill() } } } } let AnyObservableArray = ObservableArray<Int>() let AnyObservable2DArray = Observable2DArray<String,Int>() extension Observable2DArrayChange: Equatable { public static func ==(lhs: Observable2DArrayChange, rhs: Observable2DArrayChange) -> Bool { switch (lhs, rhs) { case (.reset, .reset): return true case (.insertItems(let lhs), .insertItems(let rhs)): return lhs == rhs case (.deleteItems(let lhs), .deleteItems(let rhs)): return lhs == rhs case (.updateItems(let lhs), .updateItems(let rhs)): return lhs == rhs case (.moveItem(let lhsFrom, let lhsTo), .moveItem(let rhsFrom, let rhsTo)): return lhsFrom == rhsFrom && lhsTo == rhsTo case (.insertSections(let lhs), .insertSections(let rhs)): return lhs == rhs case (.deleteSections(let lhs), .deleteSections(let rhs)): return lhs == rhs case (.updateSections(let lhs), .updateSections(let rhs)): return lhs == rhs case (.moveSection(let lhsFrom, let lhsTo), .moveSection(let rhsFrom, let rhsTo)): return lhsFrom == rhsFrom && lhsTo == rhsTo case (.beginBatchEditing, .beginBatchEditing): return true case (.endBatchEditing, .endBatchEditing): return true default: return false } } } extension DataSourceEventKind: Equatable { public static func ==(lhs: DataSourceEventKind, rhs: DataSourceEventKind) -> Bool { switch (lhs, rhs) { case (.reload, .reload): return true case (.insertItems(let lhs), .insertItems(let rhs)): return lhs == rhs case (.deleteItems(let lhs), .deleteItems(let rhs)): return lhs == rhs case (.reloadItems(let lhs), .reloadItems(let rhs)): return lhs == rhs case (.moveItem(let lhsFrom, let lhsTo), .moveItem(let rhsFrom, let rhsTo)): return lhsFrom == rhsFrom && lhsTo == rhsTo case (.insertSections(let lhs), .insertSections(let rhs)): return lhs == rhs case (.deleteSections(let lhs), .deleteSections(let rhs)): return lhs == rhs case (.reloadSections(let lhs), .reloadSections(let rhs)): return lhs == rhs case (.moveSection(let lhsFrom, let lhsTo), .moveSection(let rhsFrom, let rhsTo)): return lhsFrom == rhsFrom && lhsTo == rhsTo case (.beginUpdates, .beginUpdates): return true case (.endUpdates, .endUpdates): return true default: return false } } }
mit
b4b0ae33c7f3b7762c2b53ddb4c1655f
36.138554
132
0.629197
4.126506
false
false
false
false
stripe/stripe-ios
StripeUICore/StripeUICore/Source/Elements/DropdownFieldElement.swift
1
5786
// // DropdownFieldElement.swift // StripeUICore // // Created by Yuki Tokuhiro on 6/17/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import Foundation import UIKit @_spi(STP) import StripeCore /** A textfield whose input view is a `UIPickerView` with a list of the strings. For internal SDK use only */ @objc(STP_Internal_DropdownFieldElement) @_spi(STP) public class DropdownFieldElement: NSObject { public typealias DidUpdateSelectedIndex = (Int) -> Void public struct DropdownItem { public init(pickerDisplayName: String, labelDisplayName: String, accessibilityLabel: String, rawData: String) { self.pickerDisplayName = pickerDisplayName self.labelDisplayName = labelDisplayName self.accessibilityLabel = accessibilityLabel self.rawData = rawData } /// Item label displayed in the picker public let pickerDisplayName: String /// Item label displayed in inline label when item has been selected public let labelDisplayName: String /// Accessibility label to use when this is in the inline label public let accessibilityLabel: String /// The underlying data for this dropdown item. /// e.g., A country dropdown item might display "United States" but its `rawData` is "US". /// This is ignored by `DropdownFieldElement`, and is intended as a convenience to be used in conjunction with `selectedItem` public let rawData: String } // MARK: - Public properties weak public var delegate: ElementDelegate? public let items: [DropdownItem] public var selectedItem: DropdownItem { return items[selectedIndex] } public var selectedIndex: Int { didSet { updatePickerField() } } public var didUpdate: DidUpdateSelectedIndex? private(set) lazy var pickerView: UIPickerView = { let picker = UIPickerView() picker.delegate = self picker.dataSource = self return picker }() private(set) lazy var pickerFieldView: PickerFieldView = { let pickerFieldView = PickerFieldView( label: label, shouldShowChevron: true, pickerView: pickerView, delegate: self, theme: theme ) return pickerFieldView }() // MARK: - Private properties private let label: String? private let theme: ElementsUITheme private var previouslySelectedIndex: Int /** - Parameters: - items: Items to populate this dropdown with. - defaultIndex: Defaults the dropdown to the item with the corresponding index. - label: Label for the dropdown - didUpdate: Called when the user has finished selecting a new item. - Note: - Items must contain at least one item. - If `defaultIndex` is outside of the bounds of the `items` array, then a default of `0` is used. - `didUpdate` is not called if the user does not change their input before hitting "Done" */ public init( items: [DropdownItem], defaultIndex: Int = 0, label: String?, theme: ElementsUITheme = .default, didUpdate: DidUpdateSelectedIndex? = nil ) { assert(!items.isEmpty, "`items` must contain at least one item") self.label = label self.theme = theme self.items = items self.didUpdate = didUpdate // Default to defaultIndex, if in bounds if defaultIndex < 0 || defaultIndex >= items.count { self.selectedIndex = 0 } else { self.selectedIndex = defaultIndex } self.previouslySelectedIndex = selectedIndex super.init() if !items.isEmpty { updatePickerField() } } public func select(index: Int) { selectedIndex = index didFinish(pickerFieldView) } } private extension DropdownFieldElement { func updatePickerField() { if pickerView.selectedRow(inComponent: 0) != selectedIndex { pickerView.selectRow(selectedIndex, inComponent: 0, animated: false) } pickerFieldView.displayText = items[selectedIndex].labelDisplayName pickerFieldView.displayTextAccessibilityLabel = items[selectedIndex].accessibilityLabel } } // MARK: Element extension DropdownFieldElement: Element { public var view: UIView { return pickerFieldView } public func beginEditing() -> Bool { return pickerFieldView.becomeFirstResponder() } } // MARK: UIPickerViewDelegate extension DropdownFieldElement: UIPickerViewDelegate { public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return items[row].pickerDisplayName } public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedIndex = row } } extension DropdownFieldElement: UIPickerViewDataSource { public func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return items.count } } // MARK: - PickerFieldViewDelegate extension DropdownFieldElement: PickerFieldViewDelegate { func didBeginEditing(_ pickerFieldView: PickerFieldView) { // No-op } func didFinish(_ pickerFieldView: PickerFieldView) { if previouslySelectedIndex != selectedIndex { didUpdate?(selectedIndex) } previouslySelectedIndex = selectedIndex delegate?.continueToNextField(element: self) } }
mit
e39e3dc204d67db3e24876709d6a1b54
29.935829
133
0.655661
5.146797
false
false
false
false
kstaring/swift
test/Constraints/override.swift
4
1487
// RUN: %target-parse-verify-swift class Base { func foo() {} } class Sub: Base { override func foo() {} } func removeOverrides<SomeSub: Sub>(concrete: Sub, generic: SomeSub) { _ = concrete.foo() _ = generic.foo() } class Base1 { func foo1(a : Int, b : @escaping () -> ()) {} // expected-note{{potential overridden instance method 'foo1(a:b:)' here}} func foo2(a : @escaping (Int)->(Int), b : @escaping () -> ()) {} // expected-note{{potential overridden instance method 'foo2(a:b:)' here}} } class Sub1 : Base1 { override func foo1(a : Int, b : () -> ()) {} // expected-error {{method does not override any method from its superclass}} expected-note {{type does not match superclass instance method with type '(Int, @escaping () -> ()) -> ()'}} {{34-34=@escaping }} override func foo2(a : (Int)->(Int), b : () -> ()) {} // expected-error {{method does not override any method from its superclass}} expected-note{{type does not match superclass instance method with type '(@escaping (Int) -> (Int), @escaping () -> ()) -> ()'}} {{25-25=@escaping }} {{43-43=@escaping }} } class Base2 { func foo<T>(a : @escaping (T) -> ()) {} // expected-note{{potential overridden instance method 'foo(a:)' here}} } class Sub2 : Base2 { override func foo<T>(a : (T) -> ()) {} // expected-error {{method does not override any method from its superclass}} expected-note{{type does not match superclass instance method with type '(@escaping (T) -> ()) -> ()'}}{{28-28=@escaping }} }
apache-2.0
3df2fea5c43d98945d9ae8db963620bb
45.46875
303
0.6308
3.507075
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/GroupCallTileRowItem.swift
1
1594
// // GroupCallTileRowItem.swift // Telegram // // Created by Mikhail Filimonov on 04.06.2021. // Copyright © 2021 Telegram. All rights reserved. // import Foundation import TGUIKit import SwiftSignalKit import Postbox import TelegramCore final class GroupCallTileRowItem : GeneralRowItem { fileprivate let takeView: ()->(NSSize, GroupCallTileView)? init(_ initialSize: NSSize, stableId: AnyHashable, takeView: @escaping()->(NSSize, GroupCallTileView)?) { self.takeView = takeView super.init(initialSize, stableId: stableId) } override var height: CGFloat { let value = takeView() if let value = value { return value.1.getSize(value.0).height + 5 } return 1 } override var instantlyResize: Bool { return true } override func viewClass() -> AnyClass { return GroupCallTileRowView.self } } private final class GroupCallTileRowView: TableRowView { required init(frame frameRect: NSRect) { super.init(frame: frameRect) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var backdorColor: NSColor { return GroupCallTheme.windowBackground } override func set(item: TableRowItem, animated: Bool = false) { super.set(item: item, animated: animated) guard let item = item as? GroupCallTileRowItem else { return } if let view = item.takeView() { addSubview(view.1) } } }
gpl-2.0
af672322050bed3dc308d4cda0f5b611
23.507692
109
0.628374
4.577586
false
false
false
false
apple/swift-driver
Sources/SwiftDriver/Driver/OutputFileMap.swift
1
9991
//===--------------- OutputFileMap.swift - Swift Output File Map ----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 struct Foundation.Data import class Foundation.JSONEncoder import class Foundation.JSONDecoder import class TSCBasic.DiagnosticsEngine import protocol TSCBasic.FileSystem import struct TSCBasic.AbsolutePath import struct TSCBasic.ByteString import struct TSCBasic.RelativePath /// Mapping of input file paths to specific output files. public struct OutputFileMap: Hashable, Codable { static let singleInputKey = try! VirtualPath.intern(path: ".") /// The known mapping from input file to specific output files. public var entries: [VirtualPath.Handle: [FileType: VirtualPath.Handle]] = [:] public init() { } public init(entries: [VirtualPath.Handle: [FileType: VirtualPath.Handle]]) { self.entries = entries } /// For the given input file, retrieve or create an output file for the given /// file type. public func getOutput(inputFile: VirtualPath.Handle, outputType: FileType) throws -> VirtualPath.Handle { // If we already have an output file, retrieve it. if let output = try existingOutput(inputFile: inputFile, outputType: outputType) { return output } let inputFile = VirtualPath.lookup(inputFile) if inputFile == .standardOutput { fatalError("Standard output cannot be an input file") } // Form the virtual path. return VirtualPath.createUniqueTemporaryFile(RelativePath(inputFile.basenameWithoutExt.appendingFileTypeExtension(outputType))).intern() } public func existingOutput(inputFile: VirtualPath.Handle, outputType: FileType) throws -> VirtualPath.Handle? { if let path = entries[inputFile]?[outputType] { return path } switch outputType { case .swiftDocumentation, .swiftSourceInfoFile: // Infer paths for these entities using .swiftmodule path. guard let path = entries[inputFile]?[.swiftModule] else { return nil } return try VirtualPath.lookup(path).replacingExtension(with: outputType).intern() case .jsonAPIBaseline, .jsonABIBaseline: // Infer paths for these entities using .swiftsourceinfo path. guard let path = entries[inputFile]?[.swiftSourceInfoFile] else { return nil } return try VirtualPath.lookup(path).replacingExtension(with: outputType).intern() case .object: // We may generate .o files from bitcode .bc files, but the output file map // uses .swift file as the key for .o file paths. So we need to dig further. let entry = entries.first { return $0.value.contains { return $0.value == inputFile } } if let entry = entry { if let path = entries[entry.key]?[outputType] { return path } } return nil default: return nil } } public func existingOutputForSingleInput(outputType: FileType) throws -> VirtualPath.Handle? { try existingOutput(inputFile: Self.singleInputKey, outputType: outputType) } public func resolveRelativePaths(relativeTo absPath: AbsolutePath) -> OutputFileMap { let resolvedKeyValues: [(VirtualPath.Handle, [FileType : VirtualPath.Handle])] = entries.map { entry in let resolvedKey: VirtualPath.Handle // Special case for single dependency record, leave it as is if entry.key == Self.singleInputKey { resolvedKey = entry.key } else { resolvedKey = try! VirtualPath.intern(path: VirtualPath.lookup(entry.key).resolvedRelativePath(base: absPath).description) } let resolvedValue = entry.value.mapValues { try! VirtualPath.intern(path: VirtualPath.lookup($0).resolvedRelativePath(base: absPath).description) } return (resolvedKey, resolvedValue) } return OutputFileMap(entries: .init(resolvedKeyValues, uniquingKeysWith: { _, _ in fatalError("Paths collided after resolving") })) } /// Slow, but only for debugging output public func getInput(outputFile: VirtualPath) -> VirtualPath? { entries .compactMap { $0.value.values.contains(outputFile.intern()) ? VirtualPath.lookup($0.key) : nil } .first } /// Load the output file map at the given path. @_spi(Testing) public static func load( fileSystem: FileSystem, file: VirtualPath, diagnosticEngine: DiagnosticsEngine ) throws -> OutputFileMap { // Load and decode the file. let contents = try fileSystem.readFileContents(file) let result = try JSONDecoder().decode(OutputFileMapJSON.self, from: Data(contents.contents)) // Convert the loaded entries into virtual output file map. var outputFileMap = OutputFileMap() outputFileMap.entries = try result.toVirtualOutputFileMap() return outputFileMap } /// Store the output file map at the given path. public func store( fileSystem: FileSystem, file: AbsolutePath, diagnosticEngine: DiagnosticsEngine ) throws { let encoder = JSONEncoder() #if os(Linux) || os(Android) encoder.outputFormatting = [.prettyPrinted] #else if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) { encoder.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes] } #endif let contents = try encoder.encode(OutputFileMapJSON.fromVirtualOutputFileMap(entries).entries) try fileSystem.writeFileContents(file, bytes: ByteString(contents)) } /// Human-readable textual representation var description: String { var result = "" func outputPairDescription(inputPath: VirtualPath.Handle, outputPair: (FileType, VirtualPath.Handle)) -> String { "\(inputPath.description) -> \(outputPair.0.description): \"\(outputPair.1.description)\"\n" } let maps = entries.map { ($0, $1) }.sorted { VirtualPath.lookup($0.0).description < VirtualPath.lookup($1.0).description } for (input, map) in maps { let pairs = map.map { ($0, $1) }.sorted { $0.0.description < $1.0.description } for (outputType, outputPath) in pairs { result += outputPairDescription(inputPath: input, outputPair: (outputType, outputPath)) } } return result } } /// Struct for loading the JSON file from disk. fileprivate struct OutputFileMapJSON: Codable { /// The top-level key. private struct Key: CodingKey { var stringValue: String init?(stringValue: String) { self.stringValue = stringValue } var intValue: Int? { nil } init?(intValue: Int) { nil } } /// The data associated with an input file. /// `fileprivate` so that the `store` method above can see it fileprivate struct Entry: Codable { private struct CodingKeys: CodingKey { let fileType: FileType init(fileType: FileType) { self.fileType = fileType } init?(stringValue: String) { guard let fileType = FileType(name: stringValue) else { return nil } self.fileType = fileType } var stringValue: String { fileType.name } var intValue: Int? { nil } init?(intValue: Int) { nil } } let paths: [FileType: String] fileprivate init(paths: [FileType: String]) { self.paths = paths } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) paths = try Dictionary(uniqueKeysWithValues: container.allKeys.map { key in (key.fileType, try container.decode(String.self, forKey: key)) } ) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try paths.forEach { fileType, path in try container.encode(path, forKey: CodingKeys(fileType: fileType)) } } } /// The parsed entries /// `fileprivate` so that the `store` method above can see it fileprivate let entries: [String: Entry] init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Key.self) let result = try container.allKeys.map { ($0.stringValue, try container.decode(Entry.self, forKey: $0)) } self.init(entries: Dictionary(uniqueKeysWithValues: result)) } private init(entries: [String: Entry]) { self.entries = entries } /// Converts into virtual path entries. func toVirtualOutputFileMap() throws -> [VirtualPath.Handle : [FileType : VirtualPath.Handle]] { Dictionary(try entries.map { input, entry in (try VirtualPath.intern(path: input), try entry.paths.mapValues(VirtualPath.intern(path:))) }, uniquingKeysWith: { $1 }) } /// Converts from virtual path entries static func fromVirtualOutputFileMap( _ entries: [VirtualPath.Handle : [FileType : VirtualPath.Handle]] ) -> Self { func convert(entry: (key: VirtualPath.Handle, value: [FileType: VirtualPath.Handle])) -> (String, Entry) { // We use a VirtualPath with an empty path for the master entry, but its name is "." and we need "" let fixedIfMaster = VirtualPath.lookup(entry.key).name == "." ? "" : VirtualPath.lookup(entry.key).name return (fixedIfMaster, convert(outputs: entry.value)) } func convert(outputs: [FileType: VirtualPath.Handle]) -> Entry { Entry(paths: outputs.mapValues({ VirtualPath.lookup($0).name })) } return Self(entries: Dictionary(uniqueKeysWithValues: entries.map(convert(entry:)))) } } extension String { /// Append the extension for the given file type to the string. func appendingFileTypeExtension(_ type: FileType) -> String { let ext = type.rawValue if ext.isEmpty { return self } return self + "." + ext } }
apache-2.0
1d1a6904ed5ba49ca926ea390ea6a5c6
34.682143
140
0.681413
4.434532
false
false
false
false
voyages-sncf-technologies/Collor
Example/Collor/Alphabet/cell/AlphabetCollectionViewCell.swift
1
1838
// // AlphabetCollectionViewCell.swift // Collor // // Created by Guihal Gwenn on 29/01/2019. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit import Collor public final class AlphabetCollectionViewCell: UICollectionViewCell, CollectionCellAdaptable { @IBOutlet weak var label: UILabel! public override func awakeFromNib() { super.awakeFromNib() // Initialization code } public func update(with adapter: CollectionAdapter) { guard let adapter = adapter as? AlphabetAdapterProtocol else { fatalError("AlphabetAdapterProtocol required") } label.attributedText = adapter.label } } public protocol AlphabetAdapterProtocol: CollectionAdapter { var label: NSAttributedString { get } } public struct AlphabetAdapter: AlphabetAdapterProtocol { public let label: NSAttributedString public init(country: String) { label = NSAttributedString(string: country) } } public final class AlphabetDescriptor: CollectionCellDescribable { public let identifier: String = "AlphabetCollectionViewCell" public let className: String = "AlphabetCollectionViewCell" public var selectable: Bool = false let adapter: AlphabetAdapterProtocol public init(adapter: AlphabetAdapterProtocol) { self.adapter = adapter } public func size(_ collectionView: UICollectionView, sectionDescriptor: CollectionSectionDescribable) -> CGSize { let sectionInset = sectionDescriptor.sectionInset(collectionView) let width: CGFloat = collectionView.bounds.width - sectionInset.left - sectionInset.right - 80 return CGSize(width: width, height: adapter.label.height(width)) } public func getAdapter() -> CollectionAdapter { return adapter } }
bsd-3-clause
2ed84fc85810ef272646dc13fd52601e
28.15873
117
0.710397
5.160112
false
false
false
false
mercadopago/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/Payment.swift
1
6790
// // Payment.swift // MercadoPagoSDK // // Created by Matias Gualino on 6/3/15. // Copyright (c) 2015 com.mercadopago. All rights reserved. // import Foundation public class Payment : NSObject { public var binaryMode : Bool! public var callForAuthorizeId : String! public var captured : Bool! public var card : Card! public var currencyId : String! public var dateApproved : NSDate! public var dateCreated : NSDate! public var dateLastUpdated : NSDate! public var _description : String! public var externalReference : String! public var feesDetails : [FeesDetail]! public var _id : Int = 0 public var installments : Int = 0 public var liveMode : Bool! public var metadata : NSObject! public var moneyReleaseDate : NSDate! public var notificationUrl : String! public var order : Order! public var payer : Payer! public var paymentMethodId : String! public var paymentTypeId : String! public var refunds : [Refund]! public var statementDescriptor : String! public var status : String! public var statusDetail : String! public var transactionAmount : Double = 0 public var transactionAmountRefunded : Double = 0 public var transactionDetails : TransactionDetails! public var collectorId : String! public var couponAmount : Double = 0 public var differentialPricingId : NSNumber = 0 public var issuerId : Int = 0 public class func fromJSON(json : NSDictionary) -> Payment { let payment : Payment = Payment() if json["id"] != nil && !(json["id"]! is NSNull) { payment._id = (json["id"]! as? Int)! } if json["binary_mode"] != nil && !(json["binary_mode"]! is NSNull) { payment.binaryMode = JSON(json["binary_mode"]!).asBool } if json["captured"] != nil && !(json["captured"]! is NSNull) { payment.captured = JSON(json["captured"]!).asBool } if json["currency_id"] != nil && !(json["currency_id"]! is NSNull) { payment.currencyId = JSON(json["currency_id"]!).asString } if json["money_release_date"] != nil && !(json["money_release_date"]! is NSNull) { payment.moneyReleaseDate = getDateFromString(json["money_release_date"] as? String) } if json["date_created"] != nil && !(json["date_created"]! is NSNull) { payment.dateCreated = getDateFromString(json["date_created"] as? String) } if json["date_last_updated"] != nil && !(json["date_last_updated"]! is NSNull) { payment.dateLastUpdated = getDateFromString(json["date_last_updated"] as? String) } if json["date_approved"] != nil && !(json["date_approved"]! is NSNull) { payment.dateApproved = getDateFromString(json["date_approved"] as? String) } if json["description"] != nil && !(json["description"]! is NSNull) { payment._description = JSON(json["description"]!).asString } if json["external_reference"] != nil && !(json["external_reference"]! is NSNull) { payment.externalReference = JSON(json["external_reference"]!).asString } if json["installments"] != nil && !(json["installments"]! is NSNull) { payment.installments = (json["installments"] as? Int )! } if json["live_mode"] != nil && !(json["live_mode"]! is NSNull) { payment.liveMode = JSON(json["live_mode"]!).asBool } if json["notification_url"] != nil && !(json["notification_url"]! is NSNull) { payment.notificationUrl = JSON(json["notification_url"]!).asString } var feesDetails : [FeesDetail] = [FeesDetail]() if let feesDetailsArray = json["fee_details"] as? NSArray { for i in 0..<feesDetailsArray.count { if let feedDic = feesDetailsArray[i] as? NSDictionary { feesDetails.append(FeesDetail.fromJSON(feedDic)) } } } payment.feesDetails = feesDetails if let cardDic = json["card"] as? NSDictionary { payment.card = Card.fromJSON(cardDic) } if let orderDic = json["order"] as? NSDictionary { payment.order = Order.fromJSON(orderDic) } if let payerDic = json["payer"] as? NSDictionary { payment.payer = Payer.fromJSON(payerDic) } if json["payment_method_id"] != nil && !(json["payment_method_id"]! is NSNull) { payment.paymentMethodId = JSON(json["payment_method_id"]!).asString } if json["payment_type_id"] != nil && !(json["payment_type_id"]! is NSNull) { payment.paymentTypeId = JSON(json["payment_type_id"]!).asString } var refunds : [Refund] = [Refund]() if let refArray = json["refunds"] as? NSArray { for i in 0..<refArray.count { if let refDic = refArray[i] as? NSDictionary { refunds.append(Refund.fromJSON(refDic)) } } } payment.refunds = refunds if json["statement_descriptor"] != nil && !(json["statement_descriptor"]! is NSNull) { payment.statementDescriptor = JSON(json["statement_descriptor"]!).asString } if json["status"] != nil && !(json["status"]! is NSNull) { payment.status = JSON(json["status"]!).asString } if json["status_detail"] != nil && !(json["status_detail"]! is NSNull) { payment.statusDetail = JSON(json["status_detail"]!).asString } if json["transaction_amount"] != nil && !(json["transaction_amount"]! is NSNull) { payment.transactionAmount = JSON(json["transaction_amount"]!).asDouble! } if json["transaction_amount_refunded"] != nil && !(json["transaction_amount_refunded"]! is NSNull) { payment.transactionAmountRefunded = JSON(json["transaction_amount_refunded"]!).asDouble! } if let tdDic = json["transaction_details"] as? NSDictionary { payment.transactionDetails = TransactionDetails.fromJSON(tdDic) } payment.collectorId = json["collector_id"] as? String if json["coupon_amount"] != nil && !(json["coupon_amount"]! is NSNull) { payment.couponAmount = JSON(json["coupon_amount"]!).asDouble! } if json["differential_pricing_id"] != nil && !(json["differential_pricing_id"]! is NSNull) { payment.differentialPricingId = NSNumber(longLong: (json["differential_pricing_id"] as? NSString)!.longLongValue) } if json["issuer_id"] != nil && !(json["issuer_id"]! is NSNull) { payment.issuerId = (json["issuer_id"] as? NSString)!.integerValue } return payment } public class func getDateFromString(string: String!) -> NSDate! { if string == nil { return nil } let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" var dateArr = string.characters.split {$0 == "T"}.map(String.init) return dateFormatter.dateFromString(dateArr[0]) } }
mit
fad3b65fc36e97306183cd514623c428
40.408537
116
0.633579
3.913545
false
false
false
false
kesun421/firefox-ios
Storage/SQL/SQLiteBookmarksSyncing.swift
3
55677
/* 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 Deferred import Foundation import Shared import XCGLogger private let log = Logger.syncLogger extension SQLiteBookmarks: LocalItemSource { public func getLocalItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { return self.db.getMirrorItemFromTable(TableBookmarksLocal, guid: guid) } public func getLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID { return self.db.getMirrorItemsFromTable(TableBookmarksLocal, guids: guids) } public func prefetchLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { log.debug("Not implemented for SQLiteBookmarks.") return succeed() } } extension SQLiteBookmarks: MirrorItemSource { public func getMirrorItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { return self.db.getMirrorItemFromTable(TableBookmarksMirror, guid: guid) } public func getMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID { return self.db.getMirrorItemsFromTable(TableBookmarksMirror, guids: guids) } public func prefetchMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { log.debug("Not implemented for SQLiteBookmarks.") return succeed() } } extension SQLiteBookmarks { func getSQLToOverrideFolder(_ folder: GUID, atModifiedTime modified: Timestamp) -> (sql: [String], args: Args) { return self.getSQLToOverrideFolders([folder], atModifiedTime: modified) } func getSQLToOverrideFolders(_ folders: [GUID], atModifiedTime modified: Timestamp) -> (sql: [String], args: Args) { if folders.isEmpty { return (sql: [], args: []) } let vars = BrowserDB.varlist(folders.count) let args: Args = folders // Copy it to the local table. // Most of these will be NULL, because we're only dealing with folders, // and typically only the Mobile Bookmarks root. let overrideSQL = "INSERT OR IGNORE INTO \(TableBookmarksLocal) " + "(guid, type, date_added, bmkUri, title, parentid, parentName, feedUri, siteUri, pos," + " description, tags, keyword, folderName, queryId, is_deleted, " + " local_modified, sync_status, faviconID) " + "SELECT guid, type, date_added, bmkUri, title, parentid, parentName, " + "feedUri, siteUri, pos, description, tags, keyword, folderName, queryId, " + "is_deleted, " + "\(modified) AS local_modified, \(SyncStatus.changed.rawValue) AS sync_status, faviconID " + "FROM \(TableBookmarksMirror) WHERE guid IN \(vars)" // Copy its mirror structure. let dropSQL = "DELETE FROM \(TableBookmarksLocalStructure) WHERE parent IN \(vars)" let copySQL = "INSERT INTO \(TableBookmarksLocalStructure) " + "SELECT * FROM \(TableBookmarksMirrorStructure) WHERE parent IN \(vars)" // Mark as overridden. let markSQL = "UPDATE \(TableBookmarksMirror) SET is_overridden = 1 WHERE guid IN \(vars)" return (sql: [overrideSQL, dropSQL, copySQL, markSQL], args: args) } func getSQLToOverrideNonFolders(_ records: [GUID], atModifiedTime modified: Timestamp) -> (sql: [String], args: Args) { log.info("Getting SQL to override \(records).") if records.isEmpty { return (sql: [], args: []) } let vars = BrowserDB.varlist(records.count) let args: Args = records.map { $0 } // Copy any that aren't overridden to the local table. let overrideSQL = "INSERT OR IGNORE INTO \(TableBookmarksLocal) " + "(guid, type, date_added, bmkUri, title, parentid, parentName, feedUri, siteUri, pos," + " description, tags, keyword, folderName, queryId, is_deleted, " + " local_modified, sync_status, faviconID) " + "SELECT guid, type, date_added, bmkUri, title, parentid, parentName, " + "feedUri, siteUri, pos, description, tags, keyword, folderName, queryId, " + "is_deleted, " + "\(modified) AS local_modified, \(SyncStatus.changed.rawValue) AS sync_status, faviconID " + "FROM \(TableBookmarksMirror) WHERE guid IN \(vars) AND is_overridden = 0" // Mark as overridden. let markSQL = "UPDATE \(TableBookmarksMirror) SET is_overridden = 1 WHERE guid IN \(vars)" return (sql: [overrideSQL, markSQL], args: args) } /** * Insert a bookmark into the specified folder. * If the folder doesn't exist, or is deleted, insertion will fail. * * Preconditions: * * `deferred` has not been filled. * * this function is called inside a transaction that hasn't been finished. * * Postconditions: * * `deferred` has been filled with success or failure. * * the transaction will include any status/overlay changes necessary to save the bookmark. * * the return value determines whether the transaction should be committed, and * matches the success-ness of the Deferred. * * Sorry about the long line. If we break it, the indenting below gets crazy. */ fileprivate func insertBookmarkInTransaction(url: URL, title: String, favicon: Favicon?, intoFolder parent: GUID, withTitle parentTitle: String, conn: SQLiteDBConnection) throws { log.debug("Inserting bookmark in transaction on thread \(Thread.current)") // Keep going if this does not throw. func change(_ sql: String, args: Args?, desc: String) throws { try conn.executeChange(sql, withArgs: args) } let urlString = url.absoluteString let newGUID = Bytes.generateGUID() let now = Date.now() let parentArgs: Args = [parent] //// Insert the new bookmark and icon without touching structure. var args: Args = [ newGUID, BookmarkNodeType.bookmark.rawValue, now, urlString, title, parent, parentTitle, Date.nowNumber(), SyncStatus.new.rawValue, ] let faviconID: Int? // Insert the favicon. if let icon = favicon { faviconID = self.favicons.insertOrUpdateFaviconInTransaction(icon, conn: conn) } else { faviconID = nil } log.debug("Inserting bookmark with GUID \(newGUID) and specified icon \(faviconID ??? "nil").") // If the caller didn't provide an icon (and they usually don't!), // do a reverse lookup in history. We use a view to make this simple. let iconValue: String if let faviconID = faviconID { iconValue = "?" args.append(faviconID ) } else { iconValue = "(SELECT iconID FROM \(ViewIconForURL) WHERE url = ?)" args.append(urlString ) } let insertSQL = "INSERT INTO \(TableBookmarksLocal) " + "(guid, type, date_added, bmkUri, title, parentid, parentName, local_modified, sync_status, faviconID) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, \(iconValue))" try change(insertSQL, args: args, desc: "Error inserting \(newGUID).") func bumpParentStatus(_ status: Int) throws { let bumpSQL = "UPDATE \(TableBookmarksLocal) SET sync_status = \(status), local_modified = \(now) WHERE guid = ?" try change(bumpSQL, args: parentArgs, desc: "Error bumping \(parent)'s modified time.") } func overrideParentMirror() throws { // We do this slightly tortured work so that we can reuse these queries // in a different context. let (sql, args) = getSQLToOverrideFolder(parent, atModifiedTime: now) var generator = sql.makeIterator() while let query = generator.next() { try change(query, args: args, desc: "Error running overriding query.") } } //// Make sure our parent is overridden and appropriately bumped. // See discussion here: <https://github.com/mozilla/firefox-ios/commit/2041f1bbde430de29aefb803aae54ed26db47d23#commitcomment-14572312> // Note that this isn't as obvious as you might think. We must: let localStatusFactory: (SDRow) -> (Int, Bool) = { row in let status = row["sync_status"] as! Int let deleted = (row["is_deleted"] as! Int) != 0 return (status, deleted) } let overriddenFactory: (SDRow) -> Bool = { row in row.getBoolean("is_overridden") } // TODO: these can be merged into a single query. let mirrorStatusSQL = "SELECT is_overridden FROM \(TableBookmarksMirror) WHERE guid = ?" let localStatusSQL = "SELECT sync_status, is_deleted FROM \(TableBookmarksLocal) WHERE guid = ?" let mirrorStatus = conn.executeQuery(mirrorStatusSQL, factory: overriddenFactory, withArgs: parentArgs)[0] let localStatus = conn.executeQuery(localStatusSQL, factory: localStatusFactory, withArgs: parentArgs)[0] let parentExistsInMirror = mirrorStatus != nil let parentExistsLocally = localStatus != nil // * Figure out if we were already overridden. We only want to re-clone // if we weren't. if !parentExistsLocally { if !parentExistsInMirror { throw DatabaseError(description: "Folder \(parent) doesn't exist in either mirror or local.") } // * Mark the parent folder as overridden if necessary. // Overriding the parent involves copying the parent's structure, so that // we can amend it, but also the parent's row itself so that we know it's // changed. try overrideParentMirror() } else { let (status, deleted) = localStatus! if deleted { throw DatabaseError(description: "Local folder \(parent) is deleted.") } // * Bump the overridden parent's modified time. We already copied its // structure and values, and if it's in the local table it'll either // already be New or Changed. if let syncStatus = SyncStatus(rawValue: status) { switch syncStatus { case .synced: log.debug("We don't expect folders to ever be marked as Synced.") try bumpParentStatus(SyncStatus.changed.rawValue) case .new: fallthrough case .changed: // Leave it marked as new or changed, but bump the timestamp. try bumpParentStatus(syncStatus.rawValue) } } else { log.warning("Local folder marked with unknown state \(status). This should never occur.") try bumpParentStatus(SyncStatus.changed.rawValue) } } /// Add the new bookmark as a child in the modified local structure. // We always append the new row: after insertion, the new item will have the largest index. let newIndex = "(SELECT (COALESCE(MAX(idx), -1) + 1) AS newIndex FROM \(TableBookmarksLocalStructure) WHERE parent = ?)" let structureSQL = "INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) " + "VALUES (?, ?, \(newIndex))" let structureArgs: Args = [parent, newGUID, parent] try change(structureSQL, args: structureArgs, desc: "Error adding new item \(newGUID) to local structure.") } /** * Assumption: the provided folder GUID exists in either the local table or the mirror table. */ func insertBookmark(_ url: URL, title: String, favicon: Favicon?, intoFolder parent: GUID, withTitle parentTitle: String) -> Success { log.debug("Inserting bookmark task on thread \(Thread.current)") return db.transaction { conn -> Void in try self.insertBookmarkInTransaction(url: url, title: title, favicon: favicon, intoFolder: parent, withTitle: parentTitle, conn: conn) } } } private extension BookmarkMirrorItem { // Let's say the buffer structure table looks like this: // =============================== // | parent | child | idx | // ------------------------------- // | aaaa | bbbb | 5 | // | aaaa | cccc | 8 | // | aaaa | dddd | 19 | // =============================== // And the self.children array has 5 children (2 new to insert). // Then this function should be called with offset = 3 and nextIdx = 20 func getChildrenArgs(offset: Int = 0, nextIdx: Int = 0) -> [Args] { // Only folders have children, and we manage roots ourselves. if self.type != .folder || self.guid == BookmarkRoots.RootGUID { return [] } let parent = self.guid var idx = nextIdx return self.children?.suffix(from: offset).map { child in let ret: Args = [parent, child, idx] idx += 1 return ret } ?? [] } func getUpdateOrInsertArgs() -> Args { let args: Args = [ self.type.rawValue , self.dateAdded, self.serverModified, self.isDeleted ? 1 : 0 , self.hasDupe ? 1 : 0, self.parentID, self.parentName ?? "", // Workaround for dirty data before Bug 1318414. self.feedURI, self.siteURI, self.pos, self.title, self.description, self.bookmarkURI, self.tags, self.keyword, self.folderName, self.queryID, self.guid, ] return args } } private func deleteStructureForGUIDs(_ guids: [GUID], fromTable table: String, connection: SQLiteDBConnection, withMaxVars maxVars: Int=BrowserDB.MaxVariableNumber) throws { log.debug("Deleting \(guids.count) parents from \(table).") let chunks = chunk(guids, by: maxVars) for chunk in chunks { let delStructure = "DELETE FROM \(table) WHERE parent IN \(BrowserDB.varlist(chunk.count))" let args: Args = chunk.flatMap { $0 } try connection.executeChange(delStructure, withArgs: args) } } private func insertStructureIntoTable(_ table: String, connection: SQLiteDBConnection, children: [Args], maxVars: Int) throws { if children.isEmpty { return } // Insert the new structure rows. This uses three vars per row. let maxRowsPerInsert: Int = maxVars / 3 let chunks = chunk(children, by: maxRowsPerInsert) for chunk in chunks { log.verbose("Inserting \(chunk.count)…") let childArgs: Args = chunk.flatMap { $0 } // Flatten [[a, b, c], [...]] into [a, b, c, ...]. let ins = "INSERT INTO \(table) (parent, child, idx) VALUES " + Array<String>(repeating: "(?, ?, ?)", count: chunk.count).joined(separator: ", ") log.debug("Inserting \(chunk.count) records (out of \(children.count)).") try connection.executeChange(ins, withArgs: childArgs) } } /** * This stores incoming records in a buffer. * When appropriate, the buffer is merged with the mirror and local storage * in the DB. */ open class SQLiteBookmarkBufferStorage: BookmarkBufferStorage { let db: BrowserDB public init(db: BrowserDB) { self.db = db } open func synchronousBufferCount() -> Int? { return self.db.runQuery("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", args: nil, factory: IntFactory).value.successValue?[0] } public func getUpstreamRecordCount() -> Deferred<Int?> { let sql = "SELECT (SELECT COUNT(*) FROM \(TableBookmarksBuffer)) + " + "(SELECT COUNT(*) FROM \(TableBookmarksMirror) WHERE is_overridden = 0) " + "AS c" return self.db.runQuery(sql, args: nil, factory: IntFactory).bind { result in return Deferred(value: result.successValue?[0]!) } } /** * Remove child records for any folders that've been deleted or are empty. */ fileprivate func deleteChildrenInTransactionWithGUIDs(_ guids: [GUID], connection: SQLiteDBConnection, withMaxVars maxVars: Int=BrowserDB.MaxVariableNumber) throws { try deleteStructureForGUIDs(guids, fromTable: TableBookmarksBufferStructure, connection: connection, withMaxVars: maxVars) } open func isEmpty() -> Deferred<Maybe<Bool>> { return self.db.queryReturnsNoResults("SELECT 1 FROM \(TableBookmarksBuffer)") } /** * This is a little gnarly because our DB access layer is rough. * Within a single transaction, we walk the list of items, attempting to update * and inserting if the update failed. (TODO: batch the inserts!) * Once we've added all of the records, we flatten all of their children * into big arg lists and hard-update the structure table. */ open func applyRecords(_ records: [BookmarkMirrorItem]) -> Success { return self.applyRecords(records, withMaxVars: BrowserDB.MaxVariableNumber) } open func applyRecords(_ records: [BookmarkMirrorItem], withMaxVars maxVars: Int) -> Success { let guids = records.map { $0.guid } let deleted = records.filter { $0.isDeleted }.map { $0.guid } let values = records.map { $0.getUpdateOrInsertArgs() } let children = records.filter { !$0.isDeleted }.flatMap { $0.getChildrenArgs() } let folders = records.filter { $0.type == BookmarkNodeType.folder }.map { $0.guid } return db.transaction { conn -> Void in // These have the same values in the same order. let update = "UPDATE \(TableBookmarksBuffer) SET " + "type = ?, date_added = ?, server_modified = ?, is_deleted = ?, " + "hasDupe = ?, parentid = ?, parentName = ?, " + "feedUri = ?, siteUri = ?, pos = ?, title = ?, " + "description = ?, bmkUri = ?, tags = ?, keyword = ?, " + "folderName = ?, queryId = ? " + "WHERE guid = ?" // We used to use INSERT OR IGNORE here, but it muffles legitimate errors. The only // real use for that is/was to catch duplicates, but the UPDATE we run first should // serve that purpose just as well. let insert = "INSERT INTO \(TableBookmarksBuffer) " + "(type, date_added, server_modified, is_deleted, hasDupe, parentid, parentName, " + "feedUri, siteUri, pos, title, description, bmkUri, tags, keyword, folderName, queryId, guid) " + "VALUES " + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" for args in values { try conn.executeChange(update, withArgs: args) if conn.numberOfRowsModified > 0 { continue } try conn.executeChange(insert, withArgs: args) } // Delete existing structure for any folders we've seen. We always trust the folders, // not the children's parent pointers, so we do this here: we'll insert their current // children right after, when we process the child structure rows. // We only drop the child structure for deleted folders, not the record itself. // Deleted records stay in the buffer table so that we know about the deletion // when we do a real sync! log.debug("\(folders.count) folders and \(deleted.count) deleted maybe-folders to drop from buffer structure table.") try self.deleteChildrenInTransactionWithGUIDs(folders + deleted, connection: conn) // (Re-)insert children in chunks. log.debug("Inserting \(children.count) children.") try insertStructureIntoTable(TableBookmarksBufferStructure, connection: conn, children: children, maxVars: maxVars) // Drop pending deletions of items we just received. // In practice that means we have made the choice that we will always // discard local deletions if there was a modification or a deletion made remotely. log.debug("Deleting \(guids.count) pending deletions.") let chunks = chunk(guids, by: BrowserDB.MaxVariableNumber) for chunk in chunks { let delPendingDeletions = "DELETE FROM \(TablePendingBookmarksDeletions) WHERE id IN \(BrowserDB.varlist(chunk.count))" let args: Args = chunk.flatMap { $0 } try conn.executeChange(delPendingDeletions, withArgs: args) } } } open func doneApplyingRecordsAfterDownload() -> Success { self.db.checkpoint() return succeed() } } extension SQLiteBookmarkBufferStorage: BufferItemSource { public func getBufferItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { return self.db.getMirrorItemFromTable(TableBookmarksBuffer, guid: guid) } public func getBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID { return self.db.getMirrorItemsFromTable(TableBookmarksBuffer, guids: guids) } public func getBufferChildrenGUIDsForParent(_ guid: GUID) -> Deferred<Maybe<[GUID]>> { return self.getChildrenGUIDsOf(guid) } public func prefetchBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { log.debug("Not implemented.") return succeed() } } extension BrowserDB { fileprivate func getMirrorItemFromTable(_ table: String, guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { let args: Args = [guid] let sql = "SELECT * FROM \(table) WHERE guid = ?" return self.runQuery(sql, args: args, factory: BookmarkFactory.mirrorItemFactory) >>== { cursor in guard let item = cursor[0] else { return deferMaybe(DatabaseError(description: "Expected to find \(guid) in \(table) but did not.")) } return deferMaybe(item) } } fileprivate func getMirrorItemsFromTable<T: Collection>(_ table: String, guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID { var acc: [GUID: BookmarkMirrorItem] = [:] func accumulate(_ args: Args) -> Success { let sql = "SELECT * FROM \(table) WHERE guid IN \(BrowserDB.varlist(args.count))" return self.runQuery(sql, args: args, factory: BookmarkFactory.mirrorItemFactory) >>== { cursor in cursor.forEach { row in guard let row = row else { return } // Oh, Cursor. acc[row.guid] = row } return succeed() } } let args: Args = guids.map { $0 } if args.count < BrowserDB.MaxVariableNumber { return accumulate(args) >>> { deferMaybe(acc) } } let chunks = chunk(args, by: BrowserDB.MaxVariableNumber) return walk(chunks.lazy.map { Array($0) }, f: accumulate) >>> { deferMaybe(acc) } } } extension MergedSQLiteBookmarks: BookmarkBufferStorage { public func synchronousBufferCount() -> Int? { return self.buffer.synchronousBufferCount() } public func getUpstreamRecordCount() -> Deferred<Int?> { return self.buffer.getUpstreamRecordCount() } public func isEmpty() -> Deferred<Maybe<Bool>> { return self.buffer.isEmpty() } public func applyRecords(_ records: [BookmarkMirrorItem]) -> Success { return self.buffer.applyRecords(records) } public func doneApplyingRecordsAfterDownload() -> Success { // It doesn't really matter which one we checkpoint -- they're both backed by the same DB. return self.buffer.doneApplyingRecordsAfterDownload() } public func validate() -> Success { return self.buffer.validate() } public func getBufferedDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> { return self.buffer.getBufferedDeletions() } public func applyBufferCompletionOp(_ op: BufferCompletionOp, itemSources: ItemSources) -> Success { return self.buffer.applyBufferCompletionOp(op, itemSources: itemSources) } } extension MergedSQLiteBookmarks: BufferItemSource { public func getBufferItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { return self.buffer.getBufferItemWithGUID(guid) } public func getBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID { return self.buffer.getBufferItemsWithGUIDs(guids) } public func getBufferChildrenGUIDsForParent(_ guid: GUID) -> Deferred<Maybe<[GUID]>> { return self.buffer.getChildrenGUIDsOf(guid) } public func prefetchBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { return self.buffer.prefetchBufferItemsWithGUIDs(guids) } } extension MergedSQLiteBookmarks: MirrorItemSource { public func getMirrorItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { return self.local.getMirrorItemWithGUID(guid) } public func getMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID { return self.local.getMirrorItemsWithGUIDs(guids) } public func prefetchMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { return self.local.prefetchMirrorItemsWithGUIDs(guids) } } extension MergedSQLiteBookmarks: LocalItemSource { public func getLocalItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { return self.local.getLocalItemWithGUID(guid) } public func getLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID { return self.local.getLocalItemsWithGUIDs(guids) } public func prefetchLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { return self.local.prefetchLocalItemsWithGUIDs(guids) } } extension MergedSQLiteBookmarks: ShareToDestination { public func shareItem(_ item: ShareItem) -> Success { return self.local.shareItem(item) } } // Not actually implementing SyncableBookmarks, just a utility for MergedSQLiteBookmarks to do so. extension SQLiteBookmarks { public func isUnchanged() -> Deferred<Maybe<Bool>> { return self.db.queryReturnsNoResults("SELECT 1 FROM \(TableBookmarksLocal)") } // Retrieve all the local bookmarks that are not present remotely in order to avoid merge logic later. public func getLocalBookmarksModifications(limit: Int) -> Deferred<Maybe<(deletions: [GUID], additions: [BookmarkMirrorItem])>> { let deletionsQuery = "SELECT id FROM \(TablePendingBookmarksDeletions) " + "LIMIT ?" let deletionsArgs: Args = [limit] return db.runQuery(deletionsQuery, args: deletionsArgs, factory: StringFactory) >>== { let deletedGUIDs = $0.asArray() let newLimit = limit - deletedGUIDs.count let additionsQuery = "SELECT * FROM \(TableBookmarksLocal) AS bookmarks " + "WHERE type = \(BookmarkNodeType.bookmark.rawValue) AND sync_status = \(SyncStatus.new.rawValue) AND parentID = ? " + "AND NOT EXISTS (SELECT 1 FROM \(TableBookmarksBuffer) buf WHERE buf.guid = bookmarks.guid) " + "LIMIT ?" let additionsArgs: Args = [BookmarkRoots.MobileFolderGUID, newLimit] return self.db.runQuery(additionsQuery, args: additionsArgs, factory: BookmarkFactory.mirrorItemFactory) >>== { return deferMaybe((deletedGUIDs, $0.asArray())) } } } public func getLocalDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> { let sql = "SELECT guid, local_modified FROM \(TableBookmarksLocal) " + "WHERE is_deleted = 1" return self.db.runQuery(sql, args: nil, factory: { ($0["guid"] as! GUID, $0.getTimestamp("local_modified")!) }) >>== { deferMaybe($0.asArray()) } } } extension MergedSQLiteBookmarks: SyncableBookmarks { public func isUnchanged() -> Deferred<Maybe<Bool>> { return self.local.isUnchanged() } public func getLocalBookmarksModifications(limit: Int) -> Deferred<Maybe<(deletions: [GUID], additions: [BookmarkMirrorItem])>> { return self.local.getLocalBookmarksModifications(limit: limit) } public func getLocalDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> { return self.local.getLocalDeletions() } public func treeForMirror() -> Deferred<Maybe<BookmarkTree>> { return self.local.treeForMirror() } public func treesForEdges() -> Deferred<Maybe<(local: BookmarkTree, buffer: BookmarkTree)>> { return self.local.treeForLocal() >>== { local in return self.local.treeForBuffer() >>== { buffer in return deferMaybe((local: local, buffer: buffer)) } } } } // MARK: - Validation of buffer contents. // Note that these queries tend to not have exceptions for deletions. // That's because a record can't be deleted in isolation -- if it's // deleted its parent should be changed, too -- and so our views will // correctly reflect that. We'll have updated rows in the structure table, // and updated values -- and thus a complete override -- for the parent and // the deleted child. private let allBufferStructuresReferToRecords = [ "SELECT s.child AS pointee, s.parent AS pointer FROM", ViewBookmarksBufferStructureOnMirror, "s LEFT JOIN", ViewBookmarksBufferOnMirror, "b ON b.guid = s.child WHERE b.guid IS NULL", ].joined(separator: " ") private let allNonDeletedBufferRecordsAreInStructure = [ "SELECT b.guid AS missing, b.parentid AS parent FROM", ViewBookmarksBufferOnMirror, "b LEFT JOIN", ViewBookmarksBufferStructureOnMirror, "s ON b.guid = s.child WHERE s.child IS NULL AND", "b.is_deleted IS 0 AND b.parentid IS NOT '\(BookmarkRoots.RootGUID)'", ].joined(separator: " ") private let allRecordsAreChildrenOnce = [ "SELECT s.child FROM", ViewBookmarksBufferStructureOnMirror, "s INNER JOIN (", "SELECT child, COUNT(*) AS dupes FROM", ViewBookmarksBufferStructureOnMirror, "GROUP BY child HAVING dupes > 1", ") i ON s.child = i.child", ].joined(separator: " ") private let bufferParentidMatchesStructure = [ "SELECT b.guid, b.parentid, s.parent, s.child, s.idx FROM", TableBookmarksBuffer, "b JOIN", TableBookmarksBufferStructure, "s ON b.guid = s.child WHERE b.parentid IS NOT s.parent", ].joined(separator: " ") public enum BufferInconsistency { case missingValues case missingStructure case overlappingStructure case parentIDDisagreement public var query: String { switch self { case .missingValues: return allBufferStructuresReferToRecords case .missingStructure: return allNonDeletedBufferRecordsAreInStructure case .overlappingStructure: return allRecordsAreChildrenOnce case .parentIDDisagreement: return bufferParentidMatchesStructure } } public var trackingEvent: String { switch self { case .missingValues: return "missingvalues" case .missingStructure: return "missingstructure" case .overlappingStructure: return "overlappingstructure" case .parentIDDisagreement: return "parentiddisagreement" } } public var description: String { switch self { case .missingValues: return "Not all buffer structures refer to records." case .missingStructure: return "Not all buffer records are in structure." case .overlappingStructure: return "Some buffer structures refer to the same records." case .parentIDDisagreement: return "Some buffer record parent IDs don't match structure." } } var idsFactory: (SDRow) -> [String] { switch self { case .missingValues: return self.getConcernedIDs(colNames: ["pointee", "pointer"]) case .missingStructure: return self.getConcernedIDs(colNames: ["missing", "parent"]) case .overlappingStructure: return self.getConcernedIDs(colNames: ["child"]) case .parentIDDisagreement: return self.getConcernedIDs(colNames: ["guid", "parentid", "parent", "child"]) } } private func getConcernedIDs(colNames: [String]) -> ((SDRow) -> [String]) { return { (row: SDRow) in colNames.flatMap({ row[$0] as? String}) } } public static let all: [BufferInconsistency] = [.missingValues, .missingStructure, .overlappingStructure, .parentIDDisagreement] } public struct BufferInvalidError: MaybeErrorType { public let description = "Bookmarks buffer contains invalid data" public let inconsistencies: [BufferInconsistency: [GUID]] public let validationDuration: Int64 public init(inconsistencies: [BufferInconsistency: [GUID]], validationDuration: Int64) { self.inconsistencies = inconsistencies self.validationDuration = validationDuration } } extension SQLiteBookmarkBufferStorage { public func validate() -> Success { func idsFor(inconsistency inc: BufferInconsistency) -> () -> Deferred<Maybe<(type: BufferInconsistency, ids: [String])>> { return { self.db.runQuery(inc.query, args: nil, factory: inc.idsFactory) >>== { deferMaybe((type: inc, ids: $0.asArray().reduce([], +))) } } } let start = Date.now() let ops = BufferInconsistency.all.map { idsFor(inconsistency: $0) } return accumulate(ops) >>== { results in var inconsistencies = [BufferInconsistency: [GUID]]() results.forEach { type, ids in guard !ids.isEmpty else { return } inconsistencies[type] = ids } return inconsistencies.isEmpty ? succeed() : deferMaybe(BufferInvalidError(inconsistencies: inconsistencies, validationDuration: Int64(Date.now() - start))) } } public func getBufferedDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> { let sql = "SELECT guid, server_modified FROM \(TableBookmarksBuffer) " + "WHERE is_deleted = 1" return self.db.runQuery(sql, args: nil, factory: { ($0["guid"] as! GUID, $0.getTimestamp("server_modified")!) }) >>== { deferMaybe($0.asArray()) } } } extension SQLiteBookmarks { fileprivate func structureQueryForTable(_ table: String, structure: String) -> String { // We use a subquery so we get back rows for overridden folders, even when their // children aren't in the shadowing table. let sql = "SELECT s.parent AS parent, s.child AS child, COALESCE(m.type, -1) AS type " + "FROM \(structure) s LEFT JOIN \(table) m ON s.child = m.guid AND m.is_deleted IS NOT 1 " + "ORDER BY s.parent, s.idx ASC" return sql } fileprivate func remainderQueryForTable(_ table: String, structure: String) -> String { // This gives us value rows that aren't children of a folder. // You might notice that these complementary LEFT JOINs are how you // express a FULL OUTER JOIN in sqlite. // We exclude folders here because if they have children, they'll appear // in the structure query, and if they don't, they'll appear in the bottom // half of this query. let sql = "SELECT m.guid AS guid, m.type AS type " + "FROM \(table) m LEFT JOIN \(structure) s ON s.child = m.guid " + "WHERE m.is_deleted IS NOT 1 AND m.type IS NOT \(BookmarkNodeType.folder.rawValue) AND s.child IS NULL " + "UNION ALL " + // This gives us folders with no children. "SELECT m.guid AS guid, m.type AS type " + "FROM \(table) m LEFT JOIN \(structure) s ON s.parent = m.guid " + "WHERE m.is_deleted IS NOT 1 AND m.type IS \(BookmarkNodeType.folder.rawValue) AND s.parent IS NULL " return sql } fileprivate func statusQueryForTable(_ table: String) -> String { return "SELECT guid, is_deleted FROM \(table)" } fileprivate func treeForTable(_ table: String, structure: String, alwaysIncludeRoots includeRoots: Bool) -> Deferred<Maybe<BookmarkTree>> { // The structure query doesn't give us non-structural rows -- that is, if you // make a value-only change to a record, and it's not otherwise mentioned by // way of being a child of a structurally modified folder, it won't appear here at all. // It also doesn't give us empty folders, because they have no children. // We run a separate query to get those. let structureSQL = self.structureQueryForTable(table, structure: structure) let remainderSQL = self.remainderQueryForTable(table, structure: structure) let statusSQL = self.statusQueryForTable(table) func structureFactory(_ row: SDRow) -> StructureRow { let typeCode = row["type"] as! Int let type = BookmarkNodeType(rawValue: typeCode) // nil if typeCode is invalid (e.g., -1). return (parent: row["parent"] as! GUID, child: row["child"] as! GUID, type: type) } func nonStructureFactory(_ row: SDRow) -> BookmarkTreeNode { let guid = row["guid"] as! GUID let typeCode = row["type"] as! Int if let type = BookmarkNodeType(rawValue: typeCode) { switch type { case .folder: return BookmarkTreeNode.folder(guid: guid, children: []) default: return BookmarkTreeNode.nonFolder(guid: guid) } } else { return BookmarkTreeNode.unknown(guid: guid) } } func statusFactory(_ row: SDRow) -> (GUID, Bool) { return (row["guid"] as! GUID, row.getBoolean("is_deleted")) } return self.db.runQuery(statusSQL, args: nil, factory: statusFactory) >>== { cursor in var deleted = Set<GUID>() var modified = Set<GUID>() cursor.forEach { pair in let (guid, del) = pair! // Oh, cursor. if del { deleted.insert(guid) } else { modified.insert(guid) } } return self.db.runQuery(remainderSQL, args: nil, factory: nonStructureFactory) >>== { cursor in let nonFoldersAndEmptyFolders = cursor.asArray() return self.db.runQuery(structureSQL, args: nil, factory: structureFactory) >>== { cursor in let structureRows = cursor.asArray() let tree = BookmarkTree.mappingsToTreeForStructureRows(structureRows, withNonFoldersAndEmptyFolders: nonFoldersAndEmptyFolders, withDeletedRecords: deleted, modifiedRecords: modified, alwaysIncludeRoots: includeRoots) return deferMaybe(tree) } } } } public func treeForMirror() -> Deferred<Maybe<BookmarkTree>> { return self.treeForTable(TableBookmarksMirror, structure: TableBookmarksMirrorStructure, alwaysIncludeRoots: true) } public func treeForBuffer() -> Deferred<Maybe<BookmarkTree>> { return self.treeForTable(TableBookmarksBuffer, structure: TableBookmarksBufferStructure, alwaysIncludeRoots: false) } public func treeForLocal() -> Deferred<Maybe<BookmarkTree>> { return self.treeForTable(TableBookmarksLocal, structure: TableBookmarksLocalStructure, alwaysIncludeRoots: false) } } // MARK: - Applying merge operations. public extension SQLiteBookmarkBufferStorage { public func applyBufferCompletionOp(_ op: BufferCompletionOp, itemSources: ItemSources) -> Success { log.debug("Marking buffer rows as applied.") if op.isNoOp { log.debug("Nothing to do.") return succeed() } var queries: [(sql: String, args: Args?)] = [] op.processedBufferChanges.subsetsOfSize(BrowserDB.MaxVariableNumber).forEach { guids in let varlist = BrowserDB.varlist(guids.count) let args: Args = guids.map { $0 } queries.append((sql: "DELETE FROM \(TableBookmarksBufferStructure) WHERE parent IN \(varlist)", args: args)) queries.append((sql: "DELETE FROM \(TableBookmarksBuffer) WHERE guid IN \(varlist)", args: args)) } return self.db.run(queries) } public func getChildrenGUIDsOf(_ guid: GUID) -> Deferred<Maybe<[GUID]>> { let sql = "SELECT child FROM \(TableBookmarksBufferStructure) WHERE parent = ? ORDER BY idx ASC" let args: Args = [guid] return self.db.runQuery(sql, args: args, factory: StringFactory) >>== { deferMaybe($0.asArray()) } } } extension MergedSQLiteBookmarks { public func applyLocalOverrideCompletionOp(_ op: LocalOverrideCompletionOp, itemSources: ItemSources) -> Success { log.debug("Applying local op to merged.") if op.isNoOp { log.debug("Nothing to do.") return succeed() } // This is a little tortured because we want it all to happen in a single transaction. // We walk through the accrued work items, applying them in the right order (e.g., structure // then value). If at any point we fail, we abort, roll back the transaction by throwing. return local.db.transaction { conn -> Void in // So we can trample the DB in any order. try conn.executeChange("PRAGMA defer_foreign_keys = ON") log.debug("Deleting \(op.mirrorItemsToDelete.count) mirror items.") try op.mirrorItemsToDelete.withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in let args: Args = guids.map { $0 } let varlist = BrowserDB.varlist(guids.count) let sqlMirrorStructure = "DELETE FROM \(TableBookmarksMirrorStructure) WHERE parent IN \(varlist)" try conn.executeChange(sqlMirrorStructure, withArgs: args) let sqlMirror = "DELETE FROM \(TableBookmarksMirror) WHERE guid IN \(varlist)" try conn.executeChange(sqlMirror, withArgs: args) } // Copy from other tables for simplicity. // Do this *before* we throw away local and buffer changes! // This is one reason why the local override step needs to be processed before the buffer is cleared. try op.mirrorValuesToCopyFromBuffer.withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in let args: Args = guids.map { $0 } let varlist = BrowserDB.varlist(guids.count) let copySQL = [ "INSERT OR REPLACE INTO \(TableBookmarksMirror)", "(guid, type, date_added, parentid, parentName, feedUri, siteUri, pos, title, description,", "bmkUri, tags, keyword, folderName, queryId, server_modified)", "SELECT guid, type, date_added, parentid, parentName, feedUri, siteUri, pos, title, description,", "bmkUri, tags, keyword, folderName, queryId, server_modified", "FROM \(TableBookmarksBuffer)", "WHERE guid IN", varlist ].joined(separator: " ") try conn.executeChange(copySQL, withArgs: args) } try op.mirrorValuesToCopyFromLocal.withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in let args: Args = guids.map { $0 } let varlist = BrowserDB.varlist(guids.count) let copySQL = [ "INSERT OR REPLACE INTO \(TableBookmarksMirror)", "(guid, type, date_added, parentid, parentName, feedUri, siteUri, pos, title, description,", "bmkUri, tags, keyword, folderName, queryId, faviconID, server_modified)", "SELECT guid, type, date_added, parentid, parentName, feedUri, siteUri, pos, title, description,", "bmkUri, tags, keyword, folderName, queryId, faviconID,", // This will be fixed up in batches after the initial copy. "0 AS server_modified", "FROM \(TableBookmarksLocal) WHERE guid IN", varlist ].joined(separator: " ") try conn.executeChange(copySQL, withArgs: args) } try op.modifiedTimes.forEach { (time, guids) in // This will never be too big: we upload in chunks // smaller than 999! precondition(guids.count < BrowserDB.MaxVariableNumber) log.debug("Swizzling server modified time to \(time) for \(guids.count) GUIDs.") let args: Args = guids.map { $0 } let varlist = BrowserDB.varlist(guids.count) let updateSQL = [ "UPDATE \(TableBookmarksMirror) SET server_modified = \(time)", "WHERE guid IN", varlist, ].joined(separator: " ") try conn.executeChange(updateSQL, withArgs: args) } log.debug("Marking \(op.processedLocalChanges.count) local changes as processed.") try op.processedLocalChanges.withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in let args: Args = guids.map { $0 } let varlist = BrowserDB.varlist(guids.count) let sqlLocalStructure = "DELETE FROM \(TableBookmarksLocalStructure) WHERE parent IN \(varlist)" try conn.executeChange(sqlLocalStructure, withArgs: args) let sqlLocal = "DELETE FROM \(TableBookmarksLocal) WHERE guid IN \(varlist)" try conn.executeChange(sqlLocal, withArgs: args) // If the values change, we'll handle those elsewhere, but at least we need to mark these as non-overridden. let sqlMirrorOverride = "UPDATE \(TableBookmarksMirror) SET is_overridden = 0 WHERE guid IN \(varlist)" try conn.executeChange(sqlMirrorOverride, withArgs: args) } if !op.mirrorItemsToUpdate.isEmpty { let updateSQL = [ "UPDATE \(TableBookmarksMirror) SET", "type = ?, date_added = ?, server_modified = ?, is_deleted = ?,", "hasDupe = ?, parentid = ?, parentName = ?,", "feedUri = ?, siteUri = ?, pos = ?, title = ?,", "description = ?, bmkUri = ?, tags = ?, keyword = ?,", "folderName = ?, queryId = ?, is_overridden = 0", "WHERE guid = ?", ].joined(separator: " ") try op.mirrorItemsToUpdate.forEach { (_, mirrorItem) in let args = mirrorItem.getUpdateOrInsertArgs() try conn.executeChange(updateSQL, withArgs: args) } } if !op.mirrorItemsToInsert.isEmpty { let insertSQL = [ "INSERT OR IGNORE INTO \(TableBookmarksMirror) (", "type, date_added, server_modified, is_deleted,", "hasDupe, parentid, parentName,", "feedUri, siteUri, pos, title,", "description, bmkUri, tags, keyword,", "folderName, queryId, guid", "VALUES", "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ].joined(separator: " ") try op.mirrorItemsToInsert.forEach { (_, mirrorItem) in let args = mirrorItem.getUpdateOrInsertArgs() try conn.executeChange(insertSQL, withArgs: args) } } if !op.mirrorStructures.isEmpty { let structureRows = op.mirrorStructures.flatMap { (parent, children) in return children.enumerated().map { (idx, child) -> Args in let vals: Args = [parent, child, idx] return vals } } let parents = op.mirrorStructures.map { $0.0 } try deleteStructureForGUIDs(parents, fromTable: TableBookmarksMirrorStructure, connection: conn) try insertStructureIntoTable(TableBookmarksMirrorStructure, connection: conn, children: structureRows, maxVars: BrowserDB.MaxVariableNumber) } } } public func applyBufferUpdatedCompletionOp(_ op: BufferUpdatedCompletionOp) -> Success { log.debug("Applying buffer updates.") if op.isNoOp { log.debug("Nothing to do.") return succeed() } return local.db.transaction { conn -> Void in // So we can trample the DB in any order. try conn.executeChange("PRAGMA defer_foreign_keys = ON") try op.deletedValues.withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in let args: Args = guids.map { $0 } let varlist = BrowserDB.varlist(guids.count) // This will leave the idx column sparse for the buffer children. let sqlBufferStructure = "DELETE FROM \(TableBookmarksBufferStructure) WHERE child IN \(varlist)" try conn.executeChange(sqlBufferStructure, withArgs: args) // This will also delete items from the pending deletions table on cascade. let sqlBuffer = "DELETE FROM \(TableBookmarksBuffer) WHERE guid IN \(varlist)" try conn.executeChange(sqlBuffer, withArgs: args) } let insertSQL = [ "INSERT OR IGNORE INTO \(TableBookmarksBuffer) (", "type, date_added, server_modified, is_deleted,", "hasDupe, parentid, parentName,", "feedUri, siteUri, pos, title,", "description, bmkUri, tags, keyword,", "folderName, queryId, guid)", "VALUES", "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ].joined(separator: " ") let args = op.mobileRoot.getUpdateOrInsertArgs() try conn.executeChange(insertSQL, withArgs: args) // We update server_modified in another operation because the first statement is an INSERT OR IGNORE // and we can't turn that into a INSERT OR REPLACE because this will cascade delete children // in the buffer structure table. let updateMobileRootTimeSQL = [ "UPDATE \(TableBookmarksBuffer) SET server_modified = \(op.modifiedTime)", "WHERE guid = ?", ].joined(separator: " ") try conn.executeChange(updateMobileRootTimeSQL, withArgs: [op.mobileRoot.guid]) try op.bufferValuesToMoveFromLocal.withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in let args: Args = guids.map { $0 } let varlist = BrowserDB.varlist(guids.count) let copySQL = [ "INSERT OR REPLACE INTO \(TableBookmarksBuffer)", "(guid, type, date_added, parentid, parentName, feedUri, siteUri, pos, title, description,", "bmkUri, tags, keyword, folderName, queryId, server_modified)", "SELECT guid, type, date_added, parentid, parentName, feedUri, siteUri, pos, title, description,", "bmkUri, tags, keyword, folderName, queryId,", "\(op.modifiedTime) AS server_modified", "FROM \(TableBookmarksLocal) WHERE guid IN", varlist ].joined(separator: " ") try conn.executeChange(copySQL, withArgs: args) } try op.bufferValuesToMoveFromLocal.withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in let args: Args = guids.map { $0 } let varlist = BrowserDB.varlist(guids.count) // This will leave the idx column sparse for the local children. let sqlLocalStructure = "DELETE FROM \(TableBookmarksLocalStructure) WHERE child IN \(varlist)" try conn.executeChange(sqlLocalStructure, withArgs: args) let sqlLocal = "DELETE FROM \(TableBookmarksLocal) WHERE guid IN \(varlist)" try conn.executeChange(sqlLocal, withArgs: args) } if op.bufferValuesToMoveFromLocal.count > 0 { guard let allChildren = op.mobileRoot.children else { let err = DatabaseError(description: "Absent mobileRoot children. Aborting.") log.error("applyBufferUpdatedCompletionOp(_:) encountered error: \(err.localizedDescription)") throw err } let offset = allChildren.count - op.bufferValuesToMoveFromLocal.count let sqlNextIdx = "SELECT (COALESCE(MAX(idx), -1) + 1) AS newIndex FROM \(TableBookmarksBufferStructure) WHERE parent = ?" let nextIdxArgs: Args = [BookmarkRoots.MobileFolderGUID] let nextIdx = conn.executeQuery(sqlNextIdx, factory: IntFactory, withArgs: nextIdxArgs).asArray()[0] let toInsertArgs = Array(op.mobileRoot.getChildrenArgs(offset: offset, nextIdx: nextIdx)) try insertStructureIntoTable(TableBookmarksBufferStructure, connection: conn, children: toInsertArgs, maxVars: BrowserDB.MaxVariableNumber) } } } }
mpl-2.0
4e306d76d34e1c4839c754ab72cd4fd0
44.785362
249
0.606125
4.916549
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/Sections/Message/Friend/FriendMessageModel.swift
1
904
// // FriendMessageModel.swift // HiPDA // // Created by leizh007 on 2017/6/28. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation import Argo import Runes import Curry struct FriendMessageModel: BaseMessageModel { let isRead: Bool let sender: User let time: String } // MARK: - Serializable extension FriendMessageModel: Serializable { } // MARK: - Decodable extension FriendMessageModel: Decodable { static func decode(_ json: JSON) -> Decoded<FriendMessageModel> { return curry(FriendMessageModel.init(isRead:sender:time:)) <^> json <| "isRead" <*> json <| "sender" <*> json <| "time" } } // MARK: - Equalable extension FriendMessageModel: Equatable { static func ==(lhs: FriendMessageModel, rhs: FriendMessageModel) -> Bool { return lhs.sender == rhs.sender && lhs.time == rhs.time } }
mit
a994b0818dc85876a45d9de5394972fd
20.97561
78
0.654828
4.022321
false
false
false
false
GitHubOfJW/JavenKit
JavenKit/JWPhotoBrowserViewController/Transitioning/JWPhotoInteractiveTransitioning.swift
1
4276
// // JWPhotoInteractiveTransitioning.swift // JWCoreImageBrowser // // Created by 朱建伟 on 2016/11/29. // Copyright © 2016年 zhujianwei. All rights reserved. // import UIKit class JWPhotoInteractiveTransitioning:UIPercentDrivenInteractiveTransition { private weak var browserVc:JWPhotoBrowserViewController? func addPopInteractiveTransition(browserViewController:JWPhotoBrowserViewController) { let pan:UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(JWPhotoInteractiveTransitioning.handlerPanReg(pan:))) pan.maximumNumberOfTouches = 1 pan.minimumNumberOfTouches = 1 //将传入的控制器保存,因为要利用它触发转场操作 self.browserVc = browserViewController browserViewController.view.addGestureRecognizer(pan) } var isStart:Bool = false //处理 func handlerPanReg(pan:UIPanGestureRecognizer) { let translationY:CGFloat = pan.translation(in: pan.view).y let percent:CGFloat = abs(translationY) / (((browserVc?.view.bounds.height)!)) // print("translationY:\(translationY)") switch pan.state { case .changed://改变 self.update(percent) //设置位置 self.browserVc?.operationView.transform = CGAffineTransform(translationX: 0, y: translationY) break case .began://开始 self.isStart = true //获取到oprationView if (self.browserVc?.collectionView?.visibleCells.count)! > 0{ let cell:JWPhotoBrowserCell = self.browserVc!.collectionView?.visibleCells.first as! JWPhotoBrowserCell let rect:CGRect = cell.photoImageView.convert(cell.photoImageView.bounds, to: browserVc!.view) self.browserVc?.operationView.image = cell.photoImageView.image //cell.photoImageView.snapshotView(afterScreenUpdates:false)! self.browserVc?.operationView.frame = rect self.browserVc?.view.addSubview((self.browserVc?.operationView)!) } self.browserVc?.collectionView?.isHidden = true self.browserVc?.dismiss(animated: true, completion: { }) break case .failed://结束 取消 fallthrough case .cancelled: fallthrough case .ended: self.isStart = false if abs(translationY) > ((browserVc?.view.bounds.height)!)/8 { if let oprationView = self.browserVc?.operationView{ //默认向上滑动 var transform = CGAffineTransform(translationX: 0, y:-(browserVc?.view.bounds.height)!)// oprationView.frame.maxY //下滑 if translationY > 0 { transform = CGAffineTransform(translationX: 0, y: (browserVc?.view.bounds.height)!)//(self.browserVc?.view.bounds.height)! - oprationView.frame.minY } UIView.animate(withDuration: Double(self.duration * (1.0 - percent)), animations: { oprationView.transform = transform }, completion: { (finished) in oprationView.removeFromSuperview() // self.browserVc?.collectionView?.isHidden = true }) } self.finish() }else{ if let oprationView = browserVc?.operationView { UIView.animate(withDuration: Double(self.duration * (1.0 - percent)), animations: { oprationView.transform = CGAffineTransform.identity }, completion: { (finished) in oprationView.removeFromSuperview() self.browserVc?.collectionView?.isHidden = false }) } self.cancel() } break default: break } } }
mit
b30c9feb52a5e1feac3bdd29cac3ed28
38
173
0.554996
5.363753
false
false
false
false
milseman/swift
test/PrintAsObjC/enums.swift
13
5193
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-source-import -emit-module -emit-module-doc -o %t %s -import-objc-header %S/Inputs/enums.h -disable-objc-attr-requires-foundation-module // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %t/enums.swiftmodule -typecheck -emit-objc-header-path %t/enums.h -import-objc-header %S/Inputs/enums.h -disable-objc-attr-requires-foundation-module // RUN: %FileCheck %s < %t/enums.h // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t/enums.h // RUN: %check-in-clang %t/enums.h // RUN: %check-in-clang -fno-modules -Qunused-arguments %t/enums.h -include Foundation.h -include ctypes.h -include CoreFoundation.h // REQUIRES: objc_interop import Foundation // NEGATIVE-NOT: NSMalformedEnumMissingTypedef : // NEGATIVE-NOT: enum EnumNamed // CHECK-LABEL: enum FooComments : NSInteger; // CHECK-LABEL: enum NegativeValues : int16_t; // CHECK-LABEL: enum ObjcEnumNamed : NSInteger; // CHECK-LABEL: @interface AnEnumMethod // CHECK-NEXT: - (enum NegativeValues)takeAndReturnEnum:(enum FooComments)foo SWIFT_WARN_UNUSED_RESULT; // CHECK-NEXT: - (void)acceptPlainEnum:(enum NSMalformedEnumMissingTypedef)_; // CHECK-NEXT: - (enum ObjcEnumNamed)takeAndReturnRenamedEnum:(enum ObjcEnumNamed)foo SWIFT_WARN_UNUSED_RESULT; // CHECK-NEXT: - (void)acceptTopLevelImportedWithA:(enum TopLevelRaw)a b:(TopLevelEnum)b c:(TopLevelOptions)c d:(TopLevelTypedef)d e:(TopLevelAnon)e; // CHECK-NEXT: - (void)acceptMemberImportedWithA:(enum MemberRaw)a b:(enum MemberEnum)b c:(MemberOptions)c d:(enum MemberTypedef)d e:(MemberAnon)e ee:(MemberAnon2)ee; // CHECK: @end @objc class AnEnumMethod { @objc func takeAndReturnEnum(_ foo: FooComments) -> NegativeValues { return .Zung } @objc func acceptPlainEnum(_: NSMalformedEnumMissingTypedef) {} @objc func takeAndReturnRenamedEnum(_ foo: EnumNamed) -> EnumNamed { return .A } @objc func acceptTopLevelImported(a: TopLevelRaw, b: TopLevelEnum, c: TopLevelOptions, d: TopLevelTypedef, e: TopLevelAnon) {} @objc func acceptMemberImported(a: Wrapper.Raw, b: Wrapper.Enum, c: Wrapper.Options, d: Wrapper.Typedef, e: Wrapper.Anon, ee: Wrapper.Anon2) {} } // CHECK-LABEL: typedef SWIFT_ENUM_NAMED(NSInteger, ObjcEnumNamed, "EnumNamed") { // CHECK-NEXT: ObjcEnumNamedA = 0, // CHECK-NEXT: ObjcEnumNamedB = 1, // CHECK-NEXT: ObjcEnumNamedC = 2, // CHECK-NEXT: ObjcEnumNamedD = 3, // CHECK-NEXT: ObjcEnumNamedHelloDolly = 4, // CHECK-NEXT: }; @objc(ObjcEnumNamed) enum EnumNamed: Int { case A, B, C, d, helloDolly } // CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, EnumWithNamedConstants) { // CHECK-NEXT: kEnumA SWIFT_COMPILE_NAME("A") = 0, // CHECK-NEXT: kEnumB SWIFT_COMPILE_NAME("B") = 1, // CHECK-NEXT: kEnumC SWIFT_COMPILE_NAME("C") = 2, // CHECK-NEXT: }; @objc enum EnumWithNamedConstants: Int { @objc(kEnumA) case A @objc(kEnumB) case B @objc(kEnumC) case C } // CHECK-LABEL: typedef SWIFT_ENUM(unsigned int, ExplicitValues) { // CHECK-NEXT: ExplicitValuesZim = 0, // CHECK-NEXT: ExplicitValuesZang = 219, // CHECK-NEXT: ExplicitValuesZung = 220, // CHECK-NEXT: }; // NEGATIVE-NOT: ExplicitValuesDomain @objc enum ExplicitValues: CUnsignedInt { case Zim, Zang = 219, Zung func methodNotExportedToObjC() {} } // CHECK: /// Foo: A feer, a female feer. // CHECK-NEXT: typedef SWIFT_ENUM(NSInteger, FooComments) { // CHECK: /// Zim: A zeer, a female zeer. // CHECK-NEXT: FooCommentsZim = 0, // CHECK-NEXT: FooCommentsZang = 1, // CHECK-NEXT: FooCommentsZung = 2, // CHECK-NEXT: }; /// Foo: A feer, a female feer. @objc public enum FooComments: Int { /// Zim: A zeer, a female zeer. case Zim case Zang, Zung } // CHECK-LABEL: typedef SWIFT_ENUM(int16_t, NegativeValues) { // CHECK-NEXT: Zang = -219, // CHECK-NEXT: Zung = -218, // CHECK-NEXT: }; @objc enum NegativeValues: Int16 { case Zang = -219, Zung func methodNotExportedToObjC() {} } // CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, SomeError) { // CHECK-NEXT: SomeErrorBadness = 9001, // CHECK-NEXT: SomeErrorWorseness = 9002, // CHECK-NEXT: }; // CHECK-NEXT: static NSString * _Nonnull const SomeErrorDomain = @"enums.SomeError"; @objc enum SomeError: Int, Error { case Badness = 9001 case Worseness } // CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, SomeOtherError) { // CHECK-NEXT: SomeOtherErrorDomain = 0, // CHECK-NEXT: }; // NEGATIVE-NOT: NSString * _Nonnull const SomeOtherErrorDomain @objc enum SomeOtherError: Int, Error { case Domain // collision! } // CHECK-LABEL: typedef SWIFT_ENUM_NAMED(NSInteger, ObjcErrorType, "SomeRenamedErrorType") { // CHECK-NEXT: ObjcErrorTypeBadStuff = 0, // CHECK-NEXT: }; // CHECK-NEXT: static NSString * _Nonnull const ObjcErrorTypeDomain = @"enums.SomeRenamedErrorType"; @objc(ObjcErrorType) enum SomeRenamedErrorType: Int, Error { case BadStuff } // CHECK-NOT: enum {{[A-Z]+}} // CHECK-LABEL: @interface ZEnumMethod // CHECK-NEXT: - (enum NegativeValues)takeAndReturnEnum:(enum FooComments)foo SWIFT_WARN_UNUSED_RESULT; // CHECK: @end @objc class ZEnumMethod { @objc func takeAndReturnEnum(_ foo: FooComments) -> NegativeValues { return .Zung } }
apache-2.0
2bca94fa0203154ebda58c6c1b4ae661
37.183824
229
0.716349
3.225466
false
false
false
false
rivetlogic/liferay-mobile-directory-ios
MobilePeopleDirectory/LoginViewController.swift
1
2396
// // LoginViewController.swift // MobilePeopleDirectory // // Created by Martin Zary on 1/11/15. // Copyright (c) 2015 Rivet Logic. All rights reserved. // import UIKit class LoginViewController: UIViewController, LoginScreenletDelegate { @IBOutlet weak var loginScreenlet: LoginScreenlet! var appHelper = AppHelper() var alertHelper = AlertHelper() override func viewDidLoad() { super.viewDidLoad() loginScreenlet!.delegate = self loginScreenlet!.authMethod = AuthMethod.Email.rawValue loginScreenlet!.saveCredentials = true // bg gradient let gradientLayer = CAGradientLayer() gradientLayer.frame = self.view.frame gradientLayer.colors = [MDPAppearance.sharedInstance.TopGradientColor.CGColor, MDPAppearance.sharedInstance.BottomGradientColor.CGColor] self.view.layer.insertSublayer(gradientLayer, atIndex: 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK - Liferay Login Screenlet delegate func onLoginResponse(attributes: [String : AnyObject]) { println("onLoginResponse attributes:", attributes) dismissViewControllerAnimated(true, completion: nil) } func onLoginError(error: NSError) { println(error) // handled failed login using passed error } func onCredentialsLoaded(session:LRSession) { print("Saved loaded for server " + session.server) } func onCredentialsSaved(session:LRSession) { print("Saved credentials for server " + session.server) } @IBAction func forgotPasswordPressed(sender: AnyObject) { let forgotPasswordVC = Storyboards.Login.Storyboard().instantiateViewControllerWithIdentifier("forgotPasswordView") as? ForgotPasswordViewController presentViewController(forgotPasswordVC!, animated: true, completion: nil) } /* // 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. } */ }
gpl-3.0
f2303cd746f3224ac9f961b9d54483df
32.746479
156
0.694491
5.087049
false
false
false
false
anilkumarbp/swift-sdk-new
src/Subscription/crypt/ArrayExtension.swift
9
773
// // ArrayExtension.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 10/08/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // import Foundation extension Array { /** split in chunks with given chunk size */ func chunks(chunksize:Int) -> [Array<T>] { var words = [[T]]() words.reserveCapacity(self.count / chunksize) for var idx = chunksize; idx <= self.count; idx = idx + chunksize { let word = Array(self[idx - chunksize..<idx]) // this is slow for large table words.append(word) } let reminder = Array(suffix(self, self.count % chunksize)) if (reminder.count > 0) { words.append(reminder) } return words } }
mit
60d00590f7548bad3806b74d0a53d216
27.666667
89
0.587322
4.111702
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/CryptoAssets/Sources/ERC20Kit/Domain/Transactions/ERC20OnChainTransactionEngine.swift
1
18046
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BigInt import Combine import DIKit import EthereumKit import FeatureTransactionDomain import MoneyKit import PlatformKit import RxSwift import RxToolKit import ToolKit final class ERC20OnChainTransactionEngine: OnChainTransactionEngine { // MARK: - OnChainTransactionEngine let currencyConversionService: CurrencyConversionServiceAPI let walletCurrencyService: FiatCurrencyServiceAPI var askForRefreshConfirmation: AskForRefreshConfirmation! var fiatExchangeRatePairs: Observable<TransactionMoneyValuePairs> { sourceExchangeRatePair .map { pair -> TransactionMoneyValuePairs in TransactionMoneyValuePairs( source: pair, destination: pair ) } .asObservable() } var sourceAccount: BlockchainAccount! var transactionTarget: TransactionTarget! // MARK: - Private Properties private let ethereumOnChainEngineCompanion: EthereumOnChainEngineCompanionAPI private let receiveAddressFactory: ExternalAssetAddressServiceAPI private let erc20Token: AssetModel private let feeCache: CachedValue<EthereumTransactionFee> private let feeService: EthereumKit.EthereumFeeServiceAPI private let transactionBuildingService: EthereumTransactionBuildingServiceAPI private let ethereumTransactionDispatcher: EthereumTransactionDispatcherAPI private let pendingTransactionRepository: PendingTransactionRepositoryAPI private lazy var cryptoCurrency = erc20Token.cryptoCurrency! private var erc20CryptoAccount: ERC20CryptoAccount { sourceAccount as! ERC20CryptoAccount } private var actionableBalance: Single<MoneyValue> { sourceAccount.actionableBalance.asSingle() } // MARK: - Init init( erc20Token: AssetModel, currencyConversionService: CurrencyConversionServiceAPI = resolve(), ethereumTransactionDispatcher: EthereumTransactionDispatcherAPI = resolve(), feeService: EthereumKit.EthereumFeeServiceAPI = resolve(), ethereumOnChainEngineCompanion: EthereumOnChainEngineCompanionAPI = resolve(), receiveAddressFactory: ExternalAssetAddressServiceAPI = resolve(), transactionBuildingService: EthereumTransactionBuildingServiceAPI = resolve(), pendingTransactionRepository: PendingTransactionRepositoryAPI = resolve(), walletCurrencyService: FiatCurrencyServiceAPI = resolve() ) { self.currencyConversionService = currencyConversionService self.erc20Token = erc20Token self.ethereumTransactionDispatcher = ethereumTransactionDispatcher self.feeService = feeService self.ethereumOnChainEngineCompanion = ethereumOnChainEngineCompanion self.receiveAddressFactory = receiveAddressFactory self.transactionBuildingService = transactionBuildingService self.pendingTransactionRepository = pendingTransactionRepository self.walletCurrencyService = walletCurrencyService feeCache = CachedValue( configuration: .onSubscription( schedulerIdentifier: "ERC20OnChainTransactionEngine" ) ) feeCache.setFetch(weak: self) { (self) -> Single<EthereumTransactionFee> in self.feeService .fees(cryptoCurrency: self.sourceCryptoCurrency) .asSingle() } } // MARK: - OnChainTransactionEngine func assertInputsValid() { defaultAssertInputsValid() precondition(sourceAccount is ERC20CryptoAccount) precondition(sourceCryptoCurrency.isERC20) } func initializeTransaction() -> Single<PendingTransaction> { Single.zip( walletCurrencyService .displayCurrency .asSingle(), actionableBalance ) .map { [cryptoCurrency, predefinedAmount] fiatCurrency, availableBalance -> PendingTransaction in let amount: MoneyValue if let predefinedAmount = predefinedAmount, predefinedAmount.currency == cryptoCurrency { amount = predefinedAmount } else { amount = .zero(currency: cryptoCurrency) } let feeCryptoCurrency = cryptoCurrency.feeCryptoCurrency return PendingTransaction( amount: amount, available: availableBalance, feeAmount: .zero(currency: feeCryptoCurrency), feeForFullAvailable: .zero(currency: feeCryptoCurrency), feeSelection: .init( selectedLevel: .regular, availableLevels: [.regular, .priority], asset: .crypto(feeCryptoCurrency) ), selectedFiatCurrency: fiatCurrency ) } } func doBuildConfirmations(pendingTransaction: PendingTransaction) -> Single<PendingTransaction> { Single .zip( fiatAmountAndFees(from: pendingTransaction), makeFeeSelectionOption(pendingTransaction: pendingTransaction) ) .map { fiatAmountAndFees, feeSelectionOption -> ( amountInFiat: MoneyValue, feesInFiat: MoneyValue, feeSelectionOption: TransactionConfirmations.FeeSelection ) in let (amountInFiat, feesInFiat) = fiatAmountAndFees return (amountInFiat.moneyValue, feesInFiat.moneyValue, feeSelectionOption) } .map(weak: self) { (self, payload) -> [TransactionConfirmation] in [ TransactionConfirmations.SendDestinationValue(value: pendingTransaction.amount), TransactionConfirmations.Source(value: self.sourceAccount.label), TransactionConfirmations.Destination(value: self.transactionTarget.label), payload.feeSelectionOption, TransactionConfirmations.FeedTotal( amount: pendingTransaction.amount, amountInFiat: payload.amountInFiat, fee: pendingTransaction.feeAmount, feeInFiat: payload.feesInFiat ) ] } .map { pendingTransaction.update(confirmations: $0) } } func update(amount: MoneyValue, pendingTransaction: PendingTransaction) -> Single<PendingTransaction> { guard sourceAccount != nil else { return .just(pendingTransaction) } guard let crypto = amount.cryptoValue else { return .error(TransactionValidationFailure(state: .unknownError)) } guard crypto.currencyType == cryptoCurrency else { return .error(TransactionValidationFailure(state: .unknownError)) } return Single.zip( actionableBalance, absoluteFee(with: pendingTransaction.feeLevel) ) .map { values -> PendingTransaction in let (actionableBalance, fee) = values return pendingTransaction.update( amount: amount, available: actionableBalance, fee: fee.moneyValue, feeForFullAvailable: fee.moneyValue ) } } func doOptionUpdateRequest( pendingTransaction: PendingTransaction, newConfirmation: TransactionConfirmation ) -> Single<PendingTransaction> { if let feeSelection = newConfirmation as? TransactionConfirmations.FeeSelection, feeSelection.selectedLevel != pendingTransaction.feeLevel { return updateFeeSelection( pendingTransaction: pendingTransaction, newFeeLevel: feeSelection.selectedLevel, customFeeAmount: nil ) } else { return defaultDoOptionUpdateRequest( pendingTransaction: pendingTransaction, newConfirmation: newConfirmation ) } } func validateAmount(pendingTransaction: PendingTransaction) -> Single<PendingTransaction> { validateAmounts(pendingTransaction: pendingTransaction) .andThen(validateSufficientFunds(pendingTransaction: pendingTransaction)) .andThen(validateSufficientGas(pendingTransaction: pendingTransaction)) .updateTxValidityCompletable(pendingTransaction: pendingTransaction) } func doValidateAll(pendingTransaction: PendingTransaction) -> Single<PendingTransaction> { validateAmounts(pendingTransaction: pendingTransaction) .andThen(validateSufficientFunds(pendingTransaction: pendingTransaction)) .andThen(validateSufficientGas(pendingTransaction: pendingTransaction)) .andThen(validateNoPendingTransaction()) .updateTxValidityCompletable(pendingTransaction: pendingTransaction) } func execute(pendingTransaction: PendingTransaction) -> Single<TransactionResult> { let erc20CryptoAccount = erc20CryptoAccount let erc20Token = erc20Token let network = erc20CryptoAccount.network let transactionBuildingService = transactionBuildingService let destinationAddresses = ethereumOnChainEngineCompanion .destinationAddresses( transactionTarget: transactionTarget, cryptoCurrency: sourceCryptoCurrency, receiveAddressFactory: receiveAddressFactory ) let extraGasLimit = ethereumOnChainEngineCompanion .extraGasLimit( transactionTarget: transactionTarget, cryptoCurrency: sourceCryptoCurrency, receiveAddressFactory: receiveAddressFactory ) return Single .zip( feeCache.valueSingle, destinationAddresses, extraGasLimit ) .flatMap { fee, destinationAddresses, extraGasLimit -> Single<EthereumTransactionCandidate> in erc20CryptoAccount.nonce .flatMap { nonce in transactionBuildingService.buildTransaction( amount: pendingTransaction.amount, to: destinationAddresses.destination, addressReference: destinationAddresses.referenceAddress, gasPrice: fee.gasPrice( feeLevel: pendingTransaction.feeLevel.ethereumFeeLevel ), gasLimit: fee.gasLimit( extraGasLimit: extraGasLimit, isContract: true ), nonce: nonce, chainID: network.chainID, contractAddress: erc20Token.contractAddress ).publisher } .asSingle() } .flatMap(weak: self) { (self, candidate) -> Single<EthereumTransactionPublished> in self.ethereumTransactionDispatcher.send( transaction: candidate, secondPassword: nil, network: network ) .asSingle() } .map(\.transactionHash) .map { transactionHash -> TransactionResult in .hashed(txHash: transactionHash, amount: pendingTransaction.amount) } } } extension ERC20OnChainTransactionEngine { private func validateNoPendingTransaction() -> Completable { pendingTransactionRepository .isWaitingOnTransaction( network: erc20CryptoAccount.network, address: erc20CryptoAccount.publicKey ) .replaceError(with: true) .flatMap { isWaitingOnTransaction in isWaitingOnTransaction ? AnyPublisher.failure(TransactionValidationFailure(state: .transactionInFlight)) : AnyPublisher.just(()) } .asCompletable() } private func validateAmounts(pendingTransaction: PendingTransaction) -> Completable { Completable.fromCallable { [cryptoCurrency] in guard try pendingTransaction.amount > .zero(currency: cryptoCurrency) else { throw TransactionValidationFailure(state: .belowMinimumLimit(pendingTransaction.minSpendable)) } } } private func validateSufficientFunds(pendingTransaction: PendingTransaction) -> Completable { guard sourceAccount != nil else { fatalError("sourceAccount should never be nil when this is called") } return actionableBalance .map { [sourceAccount, transactionTarget] actionableBalance -> Void in guard try pendingTransaction.amount <= actionableBalance else { throw TransactionValidationFailure( state: .insufficientFunds( actionableBalance, pendingTransaction.amount, sourceAccount!.currencyType, transactionTarget!.currencyType ) ) } } .asCompletable() } private func validateSufficientGas(pendingTransaction: PendingTransaction) -> Completable { Single .zip( ethereumAccountBalance, absoluteFee(with: pendingTransaction.feeLevel) ) .map { balance, absoluteFee -> Void in guard try absoluteFee <= balance else { throw TransactionValidationFailure( state: .belowFees(absoluteFee.moneyValue, balance.moneyValue) ) } } .asCompletable() } private func makeFeeSelectionOption( pendingTransaction: PendingTransaction ) -> Single<TransactionConfirmations.FeeSelection> { getFeeState(pendingTransaction: pendingTransaction) .map { feeState -> TransactionConfirmations.FeeSelection in TransactionConfirmations.FeeSelection( feeState: feeState, selectedLevel: pendingTransaction.feeLevel, fee: pendingTransaction.feeAmount ) } .asSingle() } private func fiatAmountAndFees( from pendingTransaction: PendingTransaction ) -> Single<(amount: FiatValue, fees: FiatValue)> { Single.zip( sourceExchangeRatePair, ethereumExchangeRatePair, .just(pendingTransaction.amount.cryptoValue ?? .zero(currency: cryptoCurrency)), .just(pendingTransaction.feeAmount.cryptoValue ?? .zero(currency: cryptoCurrency)) ) .map { sourceExchange, ethereumExchange, amount, feeAmount -> (FiatValue, FiatValue) in let erc20Quote = sourceExchange.quote.fiatValue! let ethereumQuote = ethereumExchange.quote.fiatValue! let fiatAmount = amount.convert(using: erc20Quote) let fiatFees = feeAmount.convert(using: ethereumQuote) return (fiatAmount, fiatFees) } } /// Returns Ethereum CryptoValue of the maximum fee that the user may pay. private func absoluteFee(with feeLevel: FeeLevel) -> Single<CryptoValue> { feeCache.valueSingle .flatMap(weak: self) { (self, fees) -> Single<CryptoValue> in self.ethereumOnChainEngineCompanion .absoluteFee( feeLevel: feeLevel, fees: fees, transactionTarget: self.transactionTarget, cryptoCurrency: self.sourceCryptoCurrency, receiveAddressFactory: self.receiveAddressFactory, isContract: true ) } } private var ethereumAccountBalance: Single<CryptoValue> { erc20CryptoAccount.ethereumBalance .asSingle() } /// Streams `MoneyValuePair` for the exchange rate of the source ERC20 Asset in the current fiat currency. private var sourceExchangeRatePair: Single<MoneyValuePair> { walletCurrencyService .displayCurrency .flatMap { [currencyConversionService, sourceAsset] fiatCurrency in currencyConversionService .conversionRate(from: sourceAsset, to: fiatCurrency.currencyType) .map { MoneyValuePair(base: .one(currency: sourceAsset), quote: $0) } } .asSingle() } /// Streams `MoneyValuePair` for the exchange rate of Ethereum in the current fiat currency. private var ethereumExchangeRatePair: Single<MoneyValuePair> { let feeCryptoCurrency = cryptoCurrency.feeCryptoCurrency.currencyType return walletCurrencyService .displayCurrency .flatMap { [currencyConversionService] fiatCurrency in currencyConversionService .conversionRate(from: feeCryptoCurrency, to: fiatCurrency.currencyType) .map { MoneyValuePair(base: .one(currency: feeCryptoCurrency), quote: $0) } .eraseToAnyPublisher() } .asSingle() } } extension CryptoCurrency { var feeCryptoCurrency: CryptoCurrency { switch assetModel.kind { case .erc20(contractAddress: _, parentChain: let chain): return chain.evmNetwork.cryptoCurrency default: return self } } }
lgpl-3.0
81e58382159cdbf77d4d600ab14bce37
40.482759
110
0.619285
6.077804
false
false
false
false
powerytg/PearlCam
PearlCam/PearlFX/Filters/VignetteFilterNode.swift
2
704
// // VignetteFilterNode.swift // PearlCam // // Created by Tiangong You on 6/10/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit import GPUImage class VignetteFilterNode: FilterNode { var vigFilter = Vignette() init() { super.init(filter: vigFilter) enabled = false vigFilter.end = 0.95 } var radius : Float? { didSet { if radius != nil { vigFilter.start = 1.0 - radius! } } } override func cloneFilter() -> FilterNode? { let clone = VignetteFilterNode() clone.enabled = enabled clone.radius = radius return clone } }
bsd-3-clause
7459513f83c5b12bd24e8ded367f0420
18.527778
55
0.556188
3.905556
false
false
false
false
apple/swift
test/stdlib/Diffing.swift
9
25862
// RUN: %target-run-simple-swift // REQUIRES: executable_test import Swift import StdlibUnittest let suite = TestSuite("Diffing") // This availability test has to be this awkward because of // rdar://problem/48450376 - Availability checks don't apply to top-level code if #available(SwiftStdlib 5.1, *) { suite.test("Diffing empty collections") { let a = [Int]() let b = [Int]() let diff = b.difference(from: a) expectEqual(diff, a.difference(from: a)) expectTrue(diff.isEmpty) } suite.test("Basic diffing algorithm validators") { let expectedChanges: [( source: [String], target: [String], changes: [CollectionDifference<String>.Change], line: UInt )] = [ (source: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], target: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], changes: [], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], target: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Presents", "New Years", "Champagne"], changes: [ .remove(offset: 5, element: "Lights", associatedWith: nil) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], target: ["Hannukah", "Menorah", "Dreidel", "Gelt", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], changes: [ .insert(offset: 3, element: "Gelt", associatedWith: nil) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], target: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Presents", "Tree", "Lights", "New Years", "Champagne"], changes: [ .remove(offset: 6, element: "Presents", associatedWith: 4), .insert(offset: 4, element: "Presents", associatedWith: 6) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], target: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Lights", "Presents", "Tree", "New Years", "Champagne"], changes: [ .remove(offset: 4, element: "Tree", associatedWith: 6), .insert(offset: 6, element: "Tree", associatedWith: 4) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], target: ["Hannukah", "Menorah", "Dreidel", "Presents", "Xmas", "Tree", "Lights", "New Years", "Champagne"], changes: [ .remove(offset: 6, element: "Presents", associatedWith: 3), .insert(offset: 3, element: "Presents", associatedWith: 6) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], target: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "New Years", "Champagne", "Presents"], changes: [ .remove(offset: 6, element: "Presents", associatedWith: 8), .insert(offset: 8, element: "Presents", associatedWith: 6) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], target: ["Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], changes: [ .remove(offset: 2, element: "Dreidel", associatedWith: nil), .remove(offset: 1, element: "Menorah", associatedWith: nil), .remove(offset: 0, element: "Hannukah", associatedWith: nil) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents"], target: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], changes: [ .insert(offset: 7, element: "New Years", associatedWith: nil), .insert(offset: 8, element: "Champagne", associatedWith: nil) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], target: ["New Years", "Champagne", "Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents"], changes: [ .remove(offset: 8, element: "Champagne", associatedWith: 1), .remove(offset: 7, element: "New Years", associatedWith: 0), .insert(offset: 0, element: "New Years", associatedWith: 7), .insert(offset: 1, element: "Champagne", associatedWith: 8) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], target: ["Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne", "Hannukah", "Menorah", "Dreidel"], changes: [ .remove(offset: 2, element: "Dreidel", associatedWith: 8), .remove(offset: 1, element: "Menorah", associatedWith: 7), .remove(offset: 0, element: "Hannukah", associatedWith: 6), .insert(offset: 6, element: "Hannukah", associatedWith: 0), .insert(offset: 7, element: "Menorah", associatedWith: 1), .insert(offset: 8, element: "Dreidel", associatedWith: 2) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Presents", "Xmas", "Tree", "Lights", "New Years", "Champagne"], target: ["Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], changes: [ .remove(offset: 3, element: "Presents", associatedWith: 3), .remove(offset: 2, element: "Dreidel", associatedWith: nil), .remove(offset: 1, element: "Menorah", associatedWith: nil), .remove(offset: 0, element: "Hannukah", associatedWith: nil), .insert(offset: 3, element: "Presents", associatedWith: 3) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents"], target: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Presents", "New Years", "Champagne", "Lights"], changes: [ .remove(offset: 5, element: "Lights", associatedWith: 8), .insert(offset: 6, element: "New Years", associatedWith: nil), .insert(offset: 7, element: "Champagne", associatedWith: nil), .insert(offset: 8, element: "Lights", associatedWith: 5) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], target: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years"], changes: [ .remove(offset: 8, element: "Champagne", associatedWith: nil) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Presents", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne", "Presents"], target: ["Hannukah", "Menorah", "Dreidel", "Presents", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne", "Presents"], changes: [], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Presents", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne", "Presents"], target: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "New Years", "Champagne", "Presents"], changes: [ .remove(offset: 7, element: "Presents", associatedWith: nil), .remove(offset: 3, element: "Presents", associatedWith: nil) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "New Years", "Champagne", "Presents"], target: ["Hannukah", "Menorah", "Dreidel", "Presents", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne", "Presents"], changes: [ .insert(offset: 3, element: "Presents", associatedWith: nil), .insert(offset: 7, element: "Presents", associatedWith: nil) ], line: #line), (source: ["Hannukah", "Menorah", "Dreidel", "Presents", "Xmas", "Tree", "Lights", "New Years", "Champagne", "Presents"], target: ["Hannukah", "Menorah", "Dreidel", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne", "Presents"], changes: [ .remove(offset: 3, element: "Presents", associatedWith: 6), .insert(offset: 6, element: "Presents", associatedWith: 3) ], line: #line), (source: ["Hannukah", "Menorah", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne", "Hannukah", "Dreidel"], target: ["Hannukah", "Menorah", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne", "Hannukah", "Dreidel"], changes: [], line: #line), (source: ["Hannukah", "Menorah", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne", "Hannukah", "Dreidel"], target: ["Hannukah", "Menorah", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], changes: [ .remove(offset: 9, element: "Dreidel", associatedWith: nil), .remove(offset: 8, element: "Hannukah", associatedWith: nil) ], line: #line), (source: ["Hannukah", "Menorah", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne"], target: ["Hannukah", "Menorah", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne", "Hannukah", "Dreidel"], changes: [ .insert(offset: 8, element: "Hannukah", associatedWith: nil), .insert(offset: 9, element: "Dreidel", associatedWith: nil) ], line: #line), (source: ["Hannukah", "Menorah", "Xmas", "Tree", "Lights", "Presents", "New Years", "Champagne", "Hannukah", "Dreidel"], target: ["Xmas", "Tree", "Lights", "Presents", "Hannukah", "Menorah", "New Years", "Champagne", "Hannukah", "Dreidel"], changes: [ .remove(offset: 1, element: "Menorah", associatedWith: 5), .remove(offset: 0, element: "Hannukah", associatedWith: 4), .insert(offset: 4, element: "Hannukah", associatedWith: 0), .insert(offset: 5, element: "Menorah", associatedWith: 1) ], line: #line), ] for (source, target, expected, line) in expectedChanges { let actual = target.difference(from: source).inferringMoves() expectEqual(CollectionDifference(expected), actual, "failed test at line \(line)") } } suite.test("Empty diffs have sane behaviour") { guard let diff = CollectionDifference<String>([]) else { expectUnreachable() return } expectEqual(0, diff.insertions.count) expectEqual(0, diff.removals.count) expectEqual(true, diff.isEmpty) var c = 0 diff.forEach({ _ in c += 1 }) expectEqual(0, c) } suite.test("Happy path tests for the change validator") { // Base case: one insert and one remove with legal offsets expectNotNil(CollectionDifference<Int>.init([ .insert(offset: 0, element: 0, associatedWith: nil), .remove(offset: 0, element: 0, associatedWith: nil) ])) // Code coverage: // • non-first change .remove has legal associated offset // • non-first change .insert has legal associated offset expectNotNil(CollectionDifference<Int>.init([ .remove(offset: 1, element: 0, associatedWith: 0), .remove(offset: 0, element: 0, associatedWith: 1), .insert(offset: 0, element: 0, associatedWith: 1), .insert(offset: 1, element: 0, associatedWith: 0) ])) } suite.test("Exhaustive edge case tests for the change validator") { // Base case: two inserts sharing the same offset expectNil(CollectionDifference<Int>.init([ .insert(offset: 0, element: 0, associatedWith: nil), .insert(offset: 0, element: 0, associatedWith: nil) ])) // Base case: two removes sharing the same offset expectNil(CollectionDifference<Int>.init([ .remove(offset: 0, element: 0, associatedWith: nil), .remove(offset: 0, element: 0, associatedWith: nil) ])) // Base case: illegal insertion offset expectNil(CollectionDifference<Int>.init([ .insert(offset: -1, element: 0, associatedWith: nil) ])) // Base case: illegal remove offset expectNil(CollectionDifference<Int>.init([ .remove(offset: -1, element: 0, associatedWith: nil) ])) // Base case: two inserts sharing same associated offset expectNil(CollectionDifference<Int>.init([ .insert(offset: 0, element: 0, associatedWith: 0), .insert(offset: 1, element: 0, associatedWith: 0) ])) // Base case: two removes sharing same associated offset expectNil(CollectionDifference<Int>.init([ .remove(offset: 0, element: 0, associatedWith: 0), .remove(offset: 1, element: 0, associatedWith: 0) ])) // Base case: insert with illegal associated offset expectNil(CollectionDifference<Int>.init([ .insert(offset: 0, element: 0, associatedWith: -1) ])) // Base case: remove with illegal associated offset expectNil(CollectionDifference<Int>.init([ .remove(offset: 1, element: 0, associatedWith: -1) ])) // Code coverage: non-first change has illegal offset expectNil(CollectionDifference<Int>.init([ .remove(offset: 0, element: 0, associatedWith: nil), .insert(offset: -1, element: 0, associatedWith: nil) ])) // Code coverage: non-first change has illegal associated offset expectNil(CollectionDifference<Int>.init([ .remove(offset: 0, element: 0, associatedWith: nil), .insert(offset: 0, element: 0, associatedWith: -1) ])) } suite.test("Enumeration order is safe") { let safelyOrderedChanges: [CollectionDifference<Int>.Change] = [ .remove(offset: 2, element: 0, associatedWith: nil), .remove(offset: 1, element: 0, associatedWith: 0), .remove(offset: 0, element: 0, associatedWith: 1), .insert(offset: 0, element: 0, associatedWith: 1), .insert(offset: 1, element: 0, associatedWith: 0), .insert(offset: 2, element: 0, associatedWith: nil), ] let diff = CollectionDifference<Int>.init(safelyOrderedChanges)! var enumerationOrderedChanges = [CollectionDifference<Int>.Change]() diff.forEach { c in enumerationOrderedChanges.append(c) } expectEqual(enumerationOrderedChanges, safelyOrderedChanges) } suite.test("Change validator rejects bad associations") { // .remove(1) → .insert(1) // ↑ ↓ // .insert(0) ← .remove(0) expectNil(CollectionDifference<Int>.init([ .remove(offset: 1, element: 0, associatedWith: 1), .remove(offset: 0, element: 0, associatedWith: 0), .insert(offset: 0, element: 0, associatedWith: 1), .insert(offset: 1, element: 0, associatedWith: 0) ])) // Coverage: duplicate remove offsets both with assocs expectNil(CollectionDifference<Int>.init([ .remove(offset: 0, element: 0, associatedWith: 1), .remove(offset: 0, element: 0, associatedWith: 0), ])) // Coverage: duplicate insert assocs expectNil(CollectionDifference<Int>.init([ .insert(offset: 0, element: 0, associatedWith: 1), .insert(offset: 1, element: 0, associatedWith: 1), ])) } // Full-coverage test for CollectionDifference.Change.==() suite.test("Exhaustive testing for equatable conformance") { // Differs by type: expectNotEqual( CollectionDifference<Int>.Change.insert(offset: 0, element: 0, associatedWith: 0), CollectionDifference<Int>.Change.remove(offset: 0, element: 0, associatedWith: 0) ) // Differs by type in the other direction: expectNotEqual( CollectionDifference<Int>.Change.remove(offset: 0, element: 0, associatedWith: 0), CollectionDifference<Int>.Change.insert(offset: 0, element: 0, associatedWith: 0) ) // Insert differs by offset expectNotEqual( CollectionDifference<Int>.Change.insert(offset: 0, element: 0, associatedWith: 0), CollectionDifference<Int>.Change.insert(offset: 1, element: 0, associatedWith: 0) ) // Insert differs by element expectNotEqual( CollectionDifference<Int>.Change.insert(offset: 0, element: 0, associatedWith: 0), CollectionDifference<Int>.Change.insert(offset: 0, element: 1, associatedWith: 0) ) // Insert differs by association expectNotEqual( CollectionDifference<Int>.Change.insert(offset: 0, element: 0, associatedWith: 0), CollectionDifference<Int>.Change.insert(offset: 0, element: 0, associatedWith: 1) ) // Remove differs by offset expectNotEqual( CollectionDifference<Int>.Change.remove(offset: 0, element: 0, associatedWith: 0), CollectionDifference<Int>.Change.remove(offset: 1, element: 0, associatedWith: 0) ) // Remove differs by element expectNotEqual( CollectionDifference<Int>.Change.remove(offset: 0, element: 0, associatedWith: 0), CollectionDifference<Int>.Change.remove(offset: 0, element: 1, associatedWith: 0) ) // Remove differs by association expectNotEqual( CollectionDifference<Int>.Change.remove(offset: 0, element: 0, associatedWith: 0), CollectionDifference<Int>.Change.remove(offset: 0, element: 0, associatedWith: 1) ) } suite.test("Compile-time test of hashable conformance") { let _ = Set<CollectionDifference<String>>(); } suite.test("Move inference") { let n = CollectionDifference<String>.init([ .insert(offset: 3, element: "Sike", associatedWith: nil), .insert(offset: 4, element: "Sike", associatedWith: nil), .insert(offset: 2, element: "Hello", associatedWith: nil), .remove(offset: 6, element: "Hello", associatedWith: nil), .remove(offset: 8, element: "Goodbye", associatedWith: nil), .remove(offset: 9, element: "Sike", associatedWith: nil), ]) let w = CollectionDifference<String>.init([ .insert(offset: 3, element: "Sike", associatedWith: nil), .insert(offset: 4, element: "Sike", associatedWith: nil), .insert(offset: 2, element: "Hello", associatedWith: 6), .remove(offset: 6, element: "Hello", associatedWith: 2), .remove(offset: 8, element: "Goodbye", associatedWith: nil), .remove(offset: 9, element: "Sike", associatedWith: nil), ]) expectEqual(w, n?.inferringMoves()) } suite.test("Three way merge") { let baseLines = ["Is", "it", "time", "already?"] let theirLines = ["Hi", "there", "is", "it", "time", "already?"] let myLines = ["Is", "it", "review", "time", "already?"] // Create a difference from base to theirs let diff = theirLines.difference(from: baseLines) // Apply it to mine, if possible guard let patchedLines = myLines.applying(diff) else { print("Merge conflict applying patch, manual merge required") return } // Reassemble the result expectEqual(patchedLines, ["Hi", "there", "is", "it", "review", "time", "already?"]) // print(patched) } suite.test("Diff reversal demo code") { let diff = CollectionDifference<Int>([])! let _ = CollectionDifference<Int>( diff.map({(change) -> CollectionDifference<Int>.Change in switch change { case .insert(offset: let o, element: let e, associatedWith: let a): return .remove(offset: o, element: e, associatedWith: a) case .remove(offset: let o, element: let e, associatedWith: let a): return .insert(offset: o, element: e, associatedWith: a) } }) )! } suite.test("Naive application by enumeration") { var arr = ["Is", "it", "time", "already?"] let theirLines = ["Hi", "there", "is", "it", "time", "already?"] // Create a difference from base to theirs let diff = theirLines.difference(from: arr) for c in diff { switch c { case .remove(offset: let o, element: _, associatedWith: _): arr.remove(at: o) case .insert(offset: let o, element: let e, associatedWith: _): arr.insert(e, at: o) } } expectEqual(theirLines, arr) } suite.test("Fast applicator boundary conditions") { let a = [1, 2, 3, 4, 5, 6, 7, 8] for removeMiddle in [false, true] { for insertMiddle in [false, true] { for removeLast in [false, true] { for insertLast in [false, true] { for removeFirst in [false, true] { for insertFirst in [false, true] { var b = a // Prepare b if removeMiddle { b.remove(at: 4) } if insertMiddle { b.insert(10, at: 4) } if removeLast { b.removeLast() } if insertLast { b.append(11) } if removeFirst { b.removeFirst() } if insertFirst { b.insert(12, at: 0) } // Generate diff let diff = b.difference(from: a) // Validate application expectEqual(b, a.applying(diff)!) expectEqual(a, b.applying(diff.inverse())!) }}}}}} } } if #available(SwiftStdlib 5.2, *) { suite.test("Fast applicator error condition") { let bear = "bear" let bird = "bird" let bat = "bat" let diff = bird.difference(from: bear) expectEqual(nil, bat.applying(diff)) } suite.test("Fast applicator boundary condition remove last element") { let base = [1, 2, 3] expectEqual([1, 2], base.applying(CollectionDifference<Int>([.remove(offset: base.count - 1, element: 3, associatedWith: nil)])!)) } suite.test("Fast applicator boundary condition append element") { let base = [1, 2, 3] expectEqual([1, 2, 3, 4], base.applying(CollectionDifference<Int>([.insert(offset: base.count, element: 4, associatedWith: nil)])!)) } suite.test("Fast applicator error boundary condition remove at endIndex") { let base = [1, 2, 3] expectEqual(nil, base.applying(CollectionDifference<Int>([.remove(offset: base.count, element: 4, associatedWith: nil)])!)) } suite.test("Fast applicator error boundary condition insert beyond end") { let base = [1, 2, 3] expectEqual(nil, base.applying(CollectionDifference<Int>([.insert(offset: base.count + 1, element: 5, associatedWith: nil)])!)) } suite.test("Fast applicator boundary condition replace tail") { let base = [1, 2, 3] expectEqual([1, 2, 4], base.applying(CollectionDifference<Int>([ .remove(offset: base.count - 1, element: 3, associatedWith: nil), .insert(offset: base.count - 1, element: 4, associatedWith: nil) ])!)) } suite.test("Fast applicator error boundary condition insert beyond end after tail removal") { let base = [1, 2, 3] expectEqual(nil, base.applying(CollectionDifference<Int>([ .remove(offset: base.count - 1, element: 3, associatedWith: nil), .insert(offset: base.count, element: 4, associatedWith: nil) ])!)) } suite.test("Fast applicator error boundary condition insert beyond end after non-tail removal") { let base = [1, 2, 3] expectEqual(nil, base.applying(CollectionDifference<Int>([ .remove(offset: base.count - 2, element: 2, associatedWith: nil), .insert(offset: base.count, element: 4, associatedWith: nil) ])!)) } } if #available(SwiftStdlib 5.1, *) { suite.test("Fast applicator fuzzer") { func makeArray() -> [Int] { var arr = [Int]() for _ in 0..<Int.random(in: 0..<10) { arr.append(Int.random(in: 0..<20)) } return arr } for _ in 0..<1000 { let a = makeArray() let b = makeArray() let d = b.difference(from: a) let applied = a.applying(d) expectNotNil(applied) if let applied = applied { expectEqual(b, applied) expectEqual(a, applied.applying(d.inverse())) if (b != applied) { print(""" // repro: let a = \(a) let b = \(b) let d = b.difference(from: a) expectEqual(b, a.applying(d)) expectEqual(a, applied.applying(d.inverse())) """) break } } } } } runAllTests()
apache-2.0
44fed2982d667ba50fe9467263a3dcfe
34.26603
136
0.570406
3.649068
false
false
false
false
UrbanApps/Armchair
Source/Armchair.swift
1
81037
// Armchair.swift // // Copyright (c) 2014 Armchair (http://github.com/UrbanApps/Armchair) // // 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 StoreKit import SystemConfiguration #if os(iOS) import UIKit #elseif os(OSX) import AppKit #else // Not yet supported #endif // MARK: - // MARK: PUBLIC Interface // MARK: - // MARK: Properties /* * Get/Set your Apple generated software id. * This is the only required setup value. * This call needs to be first. No default. */ public var appID: String = "" public func appID(_ appID: String) { Armchair.appID = appID Manager.defaultManager.appID = appID } /* * Get/Set the App Name to use in the prompt * Default value is your localized display name from the info.plist */ public func appName() -> String { return Manager.defaultManager.appName } public func appName(_ appName: String) { Manager.defaultManager.appName = appName } /* * Get/Set the title to use on the review prompt. * Default value is a localized "Rate <appName>" */ public func reviewTitle() -> String { return Manager.defaultManager.reviewTitle } public func reviewTitle(_ reviewTitle: String) { Manager.defaultManager.reviewTitle = reviewTitle } /* * Get/Set the message to use on the review prompt. * Default value is a localized * "If you enjoy using <appName>, would you mind taking a moment to rate it? It won't take more than a minute. Thanks for your support!" */ public func reviewMessage() -> String { return Manager.defaultManager.reviewMessage } public func reviewMessage(_ reviewMessage: String) { Manager.defaultManager.reviewMessage = reviewMessage } /* * Get/Set the cancel button title to use on the review prompt. * Default value is a localized "No, Thanks" */ public func cancelButtonTitle() -> String { return Manager.defaultManager.cancelButtonTitle } public func cancelButtonTitle(_ cancelButtonTitle: String) { Manager.defaultManager.cancelButtonTitle = cancelButtonTitle } /* * Get/Set the rate button title to use on the review prompt. * Default value is a localized "Rate <appName>" */ public func rateButtonTitle() -> String { return Manager.defaultManager.rateButtonTitle } public func rateButtonTitle(_ rateButtonTitle: String) { Manager.defaultManager.rateButtonTitle = rateButtonTitle } /* * Get/Set the remind me later button title to use on the review prompt. * It is optional, so you can set it to nil to hide the remind button from displaying * Default value is a localized "Remind me later" */ public func remindButtonTitle() -> String? { return Manager.defaultManager.remindButtonTitle } public func remindButtonTitle(_ remindButtonTitle: String?) { Manager.defaultManager.remindButtonTitle = remindButtonTitle } /* * Get/Set the NSUserDefault keys that store the usage data for Armchair * Default values are in the form of "<appID>_Armchair<Setting>" */ public func keyForArmchairKeyType(_ keyType: ArmchairKey) -> String { return Manager.defaultManager.keyForArmchairKeyType(keyType) } public func setKey(_ key: NSString, armchairKeyType: ArmchairKey) { Manager.defaultManager.setKey(key, armchairKeyType: armchairKeyType) } /* * Get/Set the prefix to the NSUserDefault keys that store the usage data for Armchair * Default value is the App ID, and it is prepended to the keys for key type, above * This prevents different apps using a shared Key/Value store from overwriting each other. */ public func keyPrefix() -> String { return Manager.defaultManager.keyPrefix } public func keyPrefix(_ keyPrefix: String) { Manager.defaultManager.keyPrefix = keyPrefix } /* * Get/Set the object that stores the usage data for Armchair * it is optional but if you pass nil, Armchair can not run. * Default value is NSUserDefaults.standardUserDefaults() */ public func userDefaultsObject() -> ArmchairDefaultsObject? { return Manager.defaultManager.userDefaultsObject } public func userDefaultsObject(_ userDefaultsObject: ArmchairDefaultsObject?) { Manager.defaultManager.userDefaultsObject = userDefaultsObject } /* * Users will need to have the same version of your app installed for this many * days before they will be prompted to rate it. * Default => 30 */ public func daysUntilPrompt() -> UInt { return Manager.defaultManager.daysUntilPrompt } public func daysUntilPrompt(_ daysUntilPrompt: UInt) { Manager.defaultManager.daysUntilPrompt = daysUntilPrompt } /* * An example of a 'use' would be if the user launched the app. Bringing the app * into the foreground (on devices that support it) would also be considered * a 'use'. * * Users need to 'use' the same version of the app this many times before * before they will be prompted to rate it. * Default => 20 */ public func usesUntilPrompt() -> UInt { return Manager.defaultManager.usesUntilPrompt } public func usesUntilPrompt(_ usesUntilPrompt: UInt) { Manager.defaultManager.usesUntilPrompt = usesUntilPrompt } /* * A significant event can be anything you want to be in your app. In a * telephone app, a significant event might be placing or receiving a call. * In a game, it might be beating a level or a boss. This is just another * layer of filtering that can be used to make sure that only the most * loyal of your users are being prompted to rate you on the app store. * If you leave this at a value of 0 (default), then this won't be a criterion * used for rating. * * To tell Armchair that the user has performed * a significant event, call the method Armchair.userDidSignificantEvent() * Default => 0 */ public func significantEventsUntilPrompt() -> UInt { return Manager.defaultManager.significantEventsUntilPrompt } public func significantEventsUntilPrompt(_ significantEventsUntilPrompt: UInt) { Manager.defaultManager.significantEventsUntilPrompt = significantEventsUntilPrompt } /* * Once the rating alert is presented to the user, they might select * 'Remind me later'. This value specifies how many days Armchair * will wait before reminding them. A value of 0 disables reminders and * removes the 'Remind me later' button. * Default => 1 */ public func daysBeforeReminding() -> UInt { return Manager.defaultManager.daysBeforeReminding } public func daysBeforeReminding(_ daysBeforeReminding: UInt) { Manager.defaultManager.daysBeforeReminding = daysBeforeReminding } /* * By default, Armchair tracks all new bundle versions. * When it detects a new version, it resets the values saved for usage, * significant events, popup shown, user action etc... * By setting this to false, Armchair will ONLY track the version it * was initialized with. If this setting is set to true, Armchair * will reset after each new version detection. * Default => true */ public func tracksNewVersions() -> Bool { return Manager.defaultManager.tracksNewVersions } public func tracksNewVersions(_ tracksNewVersions: Bool) { Manager.defaultManager.tracksNewVersions = tracksNewVersions } /* * If the user has rated the app once before, and you don't want it to show on * a new version, set this to false. This is useful if you release small bugfix * versions and don't want to pester your users with popups for every minor * version. For example, you might set this to false for every minor build, then * when you push a major version upgrade, leave it as true to ask for a rating again. * Default => true */ public func shouldPromptIfRated() -> Bool { return Manager.defaultManager.shouldPromptIfRated } public func shouldPromptIfRated(_ shouldPromptIfRated: Bool) { Manager.defaultManager.shouldPromptIfRated = shouldPromptIfRated } /* * Return whether Armchair will try and present the Storekit review prompt (useful for custom dialog modification) */ public var shouldTryStoreKitReviewPrompt : Bool { return Manager.defaultManager.shouldTryStoreKitReviewPrompt } /* * If set to true, the main bundle will always be used to load localized strings. * Set this to true if you have provided your own custom localizations in * ArmchairLocalizable.strings in your main bundle * Default => false. */ public func useMainAppBundleForLocalizations() -> Bool { return Manager.defaultManager.useMainAppBundleForLocalizations } public func useMainAppBundleForLocalizations(_ useMainAppBundleForLocalizations: Bool) { Manager.defaultManager.useMainAppBundleForLocalizations = useMainAppBundleForLocalizations } /* * If you are an Apple Affiliate, enter your code here. * If none is set, the author's code will be used as it is better to be set as something * rather than nothing. If you want to thank me for making Armchair, feel free * to leave this value at it's default. */ public func affiliateCode() -> String { return Manager.defaultManager.affiliateCode } public func affiliateCode(_ affiliateCode: String) { Manager.defaultManager.affiliateCode = affiliateCode } /* * If you are an Apple Affiliate, enter your campaign code here. (DEPRECATED) * Default => "Armchair-<appID>" */ public func affiliateCampaignCode() -> String { return Manager.defaultManager.affiliateCampaignCode } public func affiliateCampaignCode(_ affiliateCampaignCode: String) { Manager.defaultManager.affiliateCampaignCode = affiliateCampaignCode } /* * If set to true, use SKStoreReviewController's requestReview() prompt instead of the default prompt. * If not on iOS 10.3+ or macOS 10.4+, resort to the default prompt. * Default => false. */ public func useStoreKitReviewPrompt() -> Bool { return Manager.defaultManager.useStoreKitReviewPrompt } public func useStoreKitReviewPrompt(_ useStoreKitReviewPrompt: Bool) { Manager.defaultManager.useStoreKitReviewPrompt = useStoreKitReviewPrompt } /* * 'true' will show the Armchair alert everytime. Useful for testing * how your message looks and making sure the link to your app's review page works. * Calling this method in a production build (DEBUG preprocessor macro is not defined) * has no effect. In app store builds, you don't have to worry about accidentally * leaving debugEnabled to true * Default => false */ public func debugEnabled() -> Bool { return Manager.defaultManager.debugEnabled } public func debugEnabled(_ debugEnabled: Bool) { #if Debug Manager.defaultManager.debugEnabled = debugEnabled #else print("[Armchair] Debug is disabled on release builds.") print("[Armchair] If you really want to enable debug mode,") print("[Armchair] add \"-DDebug\" to your Swift Compiler - Custom Flags") print("[Armchair] section in the target's build settings for release") #endif } /** Reset all counters manually. This resets UseCount, SignificantEventCount and FirstUseDate (daysUntilPrompt) */ public func resetUsageCounters() { StandardUserDefaults().setObject(NSNumber(value: Date().timeIntervalSince1970), forKey: keyForArmchairKeyType(ArmchairKey.FirstUseDate)) StandardUserDefaults().setObject(NSNumber(value: 1), forKey: keyForArmchairKeyType(ArmchairKey.UseCount)) StandardUserDefaults().setObject(NSNumber(value: 0), forKey: keyForArmchairKeyType(ArmchairKey.SignificantEventCount)) StandardUserDefaults().synchronize() } /** Reset all values tracked by Armchair to initial state. */ public func resetAllCounters() { let currentVersionKey = keyForArmchairKeyType(ArmchairKey.CurrentVersion) let trackingVersion: String? = StandardUserDefaults().stringForKey(currentVersionKey) let bundleVersionKey = kCFBundleVersionKey as String let currentVersion = Bundle.main.object(forInfoDictionaryKey: bundleVersionKey) as? String StandardUserDefaults().setObject(trackingVersion as AnyObject?, forKey: keyForArmchairKeyType(ArmchairKey.PreviousVersion)) StandardUserDefaults().setObject(StandardUserDefaults().objectForKey(keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)), forKey: keyForArmchairKeyType(ArmchairKey.PreviousVersionRated)) StandardUserDefaults().setObject(StandardUserDefaults().objectForKey(keyForArmchairKeyType(ArmchairKey.DeclinedToRate)), forKey: keyForArmchairKeyType(ArmchairKey.PreviousVersionDeclinedToRate)) StandardUserDefaults().setObject(currentVersion as AnyObject?, forKey: currentVersionKey) resetUsageCounters() StandardUserDefaults().setObject(NSNumber(value: false), forKey: keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) StandardUserDefaults().setObject(NSNumber(value: false), forKey: keyForArmchairKeyType(ArmchairKey.DeclinedToRate)) StandardUserDefaults().setObject(NSNumber(value: 0), forKey: keyForArmchairKeyType(ArmchairKey.ReminderRequestDate)) StandardUserDefaults().synchronize() } /* * * */ public func resetDefaults() { Manager.defaultManager.debugEnabled = false Manager.defaultManager.appName = Manager.defaultManager.defaultAppName() Manager.defaultManager.reviewTitle = Manager.defaultManager.defaultReviewTitle() Manager.defaultManager.reviewMessage = Manager.defaultManager.defaultReviewMessage() Manager.defaultManager.cancelButtonTitle = Manager.defaultManager.defaultCancelButtonTitle() Manager.defaultManager.rateButtonTitle = Manager.defaultManager.defaultRateButtonTitle() Manager.defaultManager.remindButtonTitle = Manager.defaultManager.defaultRemindButtonTitle() Manager.defaultManager.daysUntilPrompt = 30 Manager.defaultManager.daysBeforeReminding = 1 Manager.defaultManager.shouldPromptIfRated = true Manager.defaultManager.significantEventsUntilPrompt = 20 Manager.defaultManager.tracksNewVersions = true Manager.defaultManager.useMainAppBundleForLocalizations = false Manager.defaultManager.affiliateCode = Manager.defaultManager.defaultAffiliateCode() Manager.defaultManager.affiliateCampaignCode = Manager.defaultManager.defaultAffiliateCampaignCode() Manager.defaultManager.didDeclineToRateClosure = nil Manager.defaultManager.didDisplayAlertClosure = nil Manager.defaultManager.didOptToRateClosure = nil Manager.defaultManager.didOptToRemindLaterClosure = nil Manager.defaultManager.customAlertClosure = nil #if os(iOS) Manager.defaultManager.usesAnimation = true Manager.defaultManager.tintColor = nil Manager.defaultManager.usesAlertController = Manager.defaultManager.defaultUsesAlertController() Manager.defaultManager.opensInStoreKit = Manager.defaultManager.defaultOpensInStoreKit() Manager.defaultManager.willPresentModalViewClosure = nil Manager.defaultManager.didDismissModalViewClosure = nil #endif Manager.defaultManager.armchairKeyFirstUseDate = Manager.defaultManager.defaultArmchairKeyFirstUseDate() Manager.defaultManager.armchairKeyUseCount = Manager.defaultManager.defaultArmchairKeyUseCount() Manager.defaultManager.armchairKeySignificantEventCount = Manager.defaultManager.defaultArmchairKeySignificantEventCount() Manager.defaultManager.armchairKeyCurrentVersion = Manager.defaultManager.defaultArmchairKeyCurrentVersion() Manager.defaultManager.armchairKeyRatedCurrentVersion = Manager.defaultManager.defaultArmchairKeyRatedCurrentVersion() Manager.defaultManager.armchairKeyDeclinedToRate = Manager.defaultManager.defaultArmchairKeyDeclinedToRate() Manager.defaultManager.armchairKeyReminderRequestDate = Manager.defaultManager.defaultArmchairKeyReminderRequestDate() Manager.defaultManager.armchairKeyPreviousVersion = Manager.defaultManager.defaultArmchairKeyPreviousVersion() Manager.defaultManager.armchairKeyPreviousVersionRated = Manager.defaultManager.defaultArmchairKeyPreviousVersionRated() Manager.defaultManager.armchairKeyPreviousVersionDeclinedToRate = Manager.defaultManager.defaultArmchairKeyDeclinedToRate() Manager.defaultManager.armchairKeyRatedAnyVersion = Manager.defaultManager.defaultArmchairKeyRatedAnyVersion() Manager.defaultManager.armchairKeyAppiraterMigrationCompleted = Manager.defaultManager.defaultArmchairKeyAppiraterMigrationCompleted() Manager.defaultManager.armchairKeyUAAppReviewManagerMigrationCompleted = Manager.defaultManager.defaultArmchairKeyUAAppReviewManagerMigrationCompleted() Manager.defaultManager.keyPrefix = Manager.defaultManager.defaultKeyPrefix() } #if os(iOS) /* * Set whether or not Armchair uses animation when pushing modal StoreKit * view controllers for the app. * Default => true */ public func usesAnimation() -> Bool { return Manager.defaultManager.usesAnimation } public func usesAnimation(_ usesAnimation: Bool) { Manager.defaultManager.usesAnimation = usesAnimation } /* * Set a tint color to apply to UIAlertController * Default => nil (the default tint color is used) */ public func tintColor() -> UIColor? { return Manager.defaultManager.tintColor } public func tintColor(tintColor: UIColor?) { Manager.defaultManager.tintColor = tintColor } /* * Set whether or not Armchair uses a UIAlertController when presenting on iOS 8 * We prefer not to use it so that the Rate button can be on the bottom and the cancel button on the top, * Something not possible as of iOS 8.0 * Default => false */ public func usesAlertController() -> Bool { return Manager.defaultManager.usesAlertController } public func usesAlertController(_ usesAlertController: Bool) { Manager.defaultManager.usesAlertController = usesAlertController } /* * If set to true, Armchair will open App Store link inside the app using * SKStoreProductViewController. * - itunes affiliate codes DO NOT work on iOS 7 inside StoreKit, * - itunes affiliate codes DO work on iOS 8 inside StoreKit, * Default => false on iOS 7, true on iOS 8+ */ public func opensInStoreKit() -> Bool { return Manager.defaultManager.opensInStoreKit } public func opensInStoreKit(_ opensInStoreKit: Bool) { Manager.defaultManager.opensInStoreKit = opensInStoreKit } #endif // MARK: Events /* * Tells Armchair that the user performed a significant event. * A significant event is whatever you want it to be. If you're app is used * to make VoIP calls, then you might want to call this method whenever the * user places a call. If it's a game, you might want to call this whenever * the user beats a level boss. * * If the user has performed enough significant events and used the app enough, * you can suppress the rating alert by passing false for canPromptForRating. The * rating alert will simply be postponed until it is called again with true for * canPromptForRating. */ public func userDidSignificantEvent(_ canPromptForRating: Bool) { Manager.defaultManager.userDidSignificantEvent(canPromptForRating) } /* * Tells Armchair that the user performed a significant event. * A significant event is whatever you want it to be. If you're app is used * to make VoIP calls, then you might want to call this method whenever the * user places a call. If it's a game, you might want to call this whenever * the user beats a level boss. * * This is similar to the userDidSignificantEvent method, but allows the passing of a * ArmchairShouldPromptClosure that will be executed before prompting. * The closure passes all the keys and values that Armchair uses to * determine if it the prompt conditions have been met, and it is up to you * to use this info and return a Bool on whether or not the prompt should be shown. * The closure is run synchronous and on the main queue, so be sure to handle it appropriately. * Return true to proceed and show the prompt, return false to kill the pending presentation. */ public func userDidSignificantEvent(_ shouldPrompt: @escaping ArmchairShouldPromptClosure) { Manager.defaultManager.userDidSignificantEvent(shouldPrompt) } // MARK: Prompts /* * Tells Armchair to show the prompt (a rating alert). The prompt * will be showed if there is an internet connection available, the user hasn't * declined to rate, hasn't rated current version and you are tracking new versions. * * You could call to show the prompt regardless of Armchair settings, * for instance, in the case of some special event in your app. */ public func showPrompt() { Manager.defaultManager.showPrompt() } /* * Tells Armchair to show the review prompt alert if all restrictions have been met. * The prompt will be shown if all restrictions are met, there is an internet connection available, * the user hasn't declined to rate, hasn't rated current version, and you are tracking new versions. * * You could call to show the prompt, for instance, in the case of some special event in your app, * like a user login. */ public func showPromptIfNecessary() { Manager.defaultManager.showPrompt(ifNecessary: true) } /* * Tells Armchair to show the review prompt alert. * * This is similar to the showPromptIfNecessary method, but allows the passing of a * ArmchairShouldPromptClosure that will be executed before prompting. * The closure passes all the keys and values that Armchair uses to * determine if it the prompt conditions have been met, and it is up to you * to use this info and return a Bool on whether or not the prompt should be shown. * The closure is run synchronous and on the main queue, so be sure to handle it appropriately. * Return true to proceed and show the prompt, return false to kill the pending presentation. */ public func showPrompt(_ shouldPrompt: ArmchairShouldPromptClosure) { Manager.defaultManager.showPrompt(shouldPrompt) } /** Returns true if rating conditions have been met already and rating prompt is likely to be shown. */ public func ratingConditionsHaveBeenMet() -> Bool { return Manager.defaultManager.ratingConditionsHaveBeenMet() } // MARK: Misc /* * This is the review URL string, generated by substituting the appID, affiliate code * and affilitate campaign code into the template URL. */ public func reviewURLString() -> String { return Manager.defaultManager.reviewURLString() } /* * Tells Armchair to open the App Store page where the user can specify a * rating for the app. Also records the fact that this has happened, so the * user won't be prompted again to rate the app. * * The only case where you should call this directly is if your app has an * explicit "Rate this app" command somewhere. In all other cases, don't worry * about calling this -- instead, just call the other functions listed above, * and let Armchair handle the bookkeeping of deciding when to ask the user * whether to rate the app. */ public func rateApp() { Manager.defaultManager.rateApp() } #if os(iOS) /* * Tells Armchair to immediately close any open rating modals * for instance, a StoreKit rating View Controller. */ public func closeModalPanel() { Manager.defaultManager.closeModalPanel() } #endif // MARK: Closures /* * Armchair uses closures instead of delegate methods for callbacks. * Default is nil for all of them. */ public typealias ArmchairClosure = () -> () public typealias ArmchairClosureCustomAlert = (_ rateAppClosure: @escaping ArmchairClosure, _ remindLaterClosure: @escaping ArmchairClosure, _ noThanksClosure: @escaping ArmchairClosure) -> () public typealias ArmchairAnimateClosure = (Bool) -> () public typealias ArmchairShouldPromptClosure = (ArmchairTrackingInfo) -> Bool public typealias ArmchairShouldIncrementClosure = () -> Bool public func onDidDisplayAlert(_ didDisplayAlertClosure: ArmchairClosure?) { Manager.defaultManager.didDisplayAlertClosure = didDisplayAlertClosure } public func customAlertClosure(_ customAlertClosure: ArmchairClosureCustomAlert?) { Manager.defaultManager.customAlertClosure = customAlertClosure } public func onDidDeclineToRate(_ didDeclineToRateClosure: ArmchairClosure?) { Manager.defaultManager.didDeclineToRateClosure = didDeclineToRateClosure } public func onDidOptToRate(_ didOptToRateClosure: ArmchairClosure?) { Manager.defaultManager.didOptToRateClosure = didOptToRateClosure } public func onDidOptToRemindLater(_ didOptToRemindLaterClosure: ArmchairClosure?) { Manager.defaultManager.didOptToRemindLaterClosure = didOptToRemindLaterClosure } #if os(iOS) public func onWillPresentModalView(_ willPresentModalViewClosure: ArmchairAnimateClosure?) { Manager.defaultManager.willPresentModalViewClosure = willPresentModalViewClosure } public func onDidDismissModalView(_ didDismissModalViewClosure: ArmchairAnimateClosure?) { Manager.defaultManager.didDismissModalViewClosure = didDismissModalViewClosure } #endif /* * The setShouldPromptClosure is called just after all the rating coditions * have been met and Armchair has decided it should display a prompt, * but just before the prompt actually displays. * * The closure passes all the keys and values that Armchair used to * determine that the prompt conditions had been met, but it is up to you * to use this info and return a Bool on whether or not the prompt should be shown. * Return true to proceed and show the prompt, return false to kill the pending presentation. */ public func shouldPromptClosure(_ shouldPromptClosure: ArmchairShouldPromptClosure?) { Manager.defaultManager.shouldPromptClosure = shouldPromptClosure } /* * The setShouldIncrementUseClosure, if valid, is called before incrementing the use count. * Returning false allows you to ignore a use. This may be usefull in cases such as Facebook login * where the app is backgrounded momentarily and the resultant enter foreground event should * not be considered another use. */ public func shouldIncrementUseCountClosure(_ shouldIncrementUseCountClosure: ArmchairShouldIncrementClosure?) { Manager.defaultManager.shouldIncrementUseCountClosure = shouldIncrementUseCountClosure } // MARK: Armchair Logger Protocol public typealias ArmchairLogger = (Manager, _ log: String, _ file: StaticString, _ function: StaticString, _ line: UInt) -> Void /* * Set a closure to capture debug log and to plug in the desired logging framework. */ public func logger(_ logger: @escaping ArmchairLogger) { Manager.defaultManager.logger = logger } // MARK: - // MARK: Armchair Defaults Protocol @objc public protocol ArmchairDefaultsObject { func objectForKey(_ defaultName: String) -> AnyObject? func setObject(_ value: AnyObject?, forKey defaultName: String) func removeObjectForKey(_ defaultName: String) func stringForKey(_ defaultName: String) -> String? func integerForKey(_ defaultName: String) -> Int func doubleForKey(_ defaultName: String) -> Double func boolForKey(_ defaultName: String) -> Bool func setInteger(_ value: Int, forKey defaultName: String) func setDouble(_ value: Double, forKey defaultName: String) func setBool(_ value: Bool, forKey defaultName: String) @discardableResult func synchronize() -> Bool } open class StandardUserDefaults: ArmchairDefaultsObject { let defaults = UserDefaults.standard @objc open func objectForKey(_ defaultName: String) -> AnyObject? { return defaults.object(forKey: defaultName) as AnyObject? } @objc open func setObject(_ value: AnyObject?, forKey defaultName: String) { defaults.set(value, forKey: defaultName) } @objc open func removeObjectForKey(_ defaultName: String) { defaults.removeObject(forKey: defaultName) } @objc open func stringForKey(_ defaultName: String) -> String? { return defaults.string(forKey: defaultName) } @objc open func integerForKey(_ defaultName: String) -> Int { return defaults.integer(forKey: defaultName) } @objc open func doubleForKey(_ defaultName: String) -> Double { return defaults.double(forKey: defaultName) } @objc open func boolForKey(_ defaultName: String) -> Bool { return defaults.bool(forKey: defaultName) } @objc open func setInteger(_ value: Int, forKey defaultName: String) { defaults.set(value, forKey: defaultName) } @objc open func setDouble(_ value: Double, forKey defaultName: String) { defaults.set(value, forKey: defaultName) } @objc open func setBool(_ value: Bool, forKey defaultName: String) { defaults.set(value, forKey: defaultName) } @discardableResult @objc open func synchronize() -> Bool { return defaults.synchronize() } } public enum ArmchairKey: String, CustomStringConvertible { case FirstUseDate = "First Use Date" case UseCount = "Use Count" case SignificantEventCount = "Significant Event Count" case CurrentVersion = "Current Version" case RatedCurrentVersion = "Rated Current Version" case DeclinedToRate = "Declined To Rate" case ReminderRequestDate = "Reminder Request Date" case PreviousVersion = "Previous Version" case PreviousVersionRated = "Previous Version Rated" case PreviousVersionDeclinedToRate = "Previous Version Declined To Rate" case RatedAnyVersion = "Rated Any Version" case AppiraterMigrationCompleted = "Appirater Migration Completed" case UAAppReviewManagerMigrationCompleted = "UAAppReviewManager Migration Completed" static let allValues = [FirstUseDate, UseCount, SignificantEventCount, CurrentVersion, RatedCurrentVersion, DeclinedToRate, ReminderRequestDate, PreviousVersion, PreviousVersionRated, PreviousVersionDeclinedToRate, RatedAnyVersion, AppiraterMigrationCompleted, UAAppReviewManagerMigrationCompleted] public var description : String { get { return self.rawValue } } } open class ArmchairTrackingInfo: CustomStringConvertible { public let info: Dictionary<ArmchairKey, AnyObject> init(info: Dictionary<ArmchairKey, AnyObject>) { self.info = info } open var description: String { get { var description = "ArmchairTrackingInfo\r" for (key, val) in info { description += " - \(key): \(val)\r" } return description } } } public struct AppiraterKey { static var FirstUseDate = "kAppiraterFirstUseDate" static var UseCount = "kAppiraterUseCount" static var SignificantEventCount = "kAppiraterSignificantEventCount" static var CurrentVersion = "kAppiraterCurrentVersion" static var RatedCurrentVersion = "kAppiraterRatedCurrentVersion" static var RatedAnyVersion = "kAppiraterRatedAnyVersion" static var DeclinedToRate = "kAppiraterDeclinedToRate" static var ReminderRequestDate = "kAppiraterReminderRequestDate" } // MARK: - // MARK: PRIVATE Interface #if os(iOS) open class ArmchairManager : NSObject, SKStoreProductViewControllerDelegate { } #elseif os(OSX) open class ArmchairManager : NSObject, NSAlertDelegate { } #else // Untested, and currently unsupported #endif open class Manager : ArmchairManager { #if os(iOS) fileprivate var operatingSystemVersion = NSString(string: UIDevice.current.systemVersion).doubleValue #elseif os(OSX) private var operatingSystemVersion = Double(ProcessInfo.processInfo.operatingSystemVersion.majorVersion) #else #endif // MARK: - // MARK: Review Alert & Properties #if os(iOS) fileprivate var ratingAlert: UIAlertController? = nil fileprivate let reviewURLTemplate = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&id=APP_ID&at=AFFILIATE_CODE&ct=AFFILIATE_CAMPAIGN_CODE&action=write-review" fileprivate let reviewURLTemplateiOS11 = "https://itunes.apple.com/us/app/idAPP_ID?ls=1&mt=8&at=AFFILIATE_CODE&action=write-review" #elseif os(OSX) private var ratingAlert: NSAlert? = nil private let reviewURLTemplate = "macappstore://itunes.apple.com/us/app/idAPP_ID?ls=1&mt=12&at=AFFILIATE_CODE" #else #endif fileprivate lazy var appName: String = self.defaultAppName() fileprivate func defaultAppName() -> String { let mainBundle = Bundle.main let displayName = mainBundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String let bundleNameKey = kCFBundleNameKey as String let name = mainBundle.object(forInfoDictionaryKey: bundleNameKey) as? String return displayName ?? name ?? "This App" } fileprivate lazy var reviewTitle: String = self.defaultReviewTitle() fileprivate func defaultReviewTitle() -> String { var template = "Rate %@" // Check for a localized version of the default title if let bundle = self.bundle() { template = bundle.localizedString(forKey: template, value: bundle.localizedString(forKey: template, value:"", table: nil), table: "ArmchairLocalizable") } return template.replacingOccurrences(of: "%@", with: "\(self.appName)", options: NSString.CompareOptions(rawValue: 0), range: nil) } fileprivate lazy var reviewMessage: String = self.defaultReviewMessage() fileprivate func defaultReviewMessage() -> String { var template = "If you enjoy using %@, would you mind taking a moment to rate it? It won't take more than a minute. Thanks for your support!" // Check for a localized version of the default title if let bundle = self.bundle() { template = bundle.localizedString(forKey: template, value: bundle.localizedString(forKey: template, value:"", table: nil), table: "ArmchairLocalizable") } return template.replacingOccurrences(of: "%@", with: "\(self.appName)", options: NSString.CompareOptions(rawValue: 0), range: nil) } fileprivate lazy var cancelButtonTitle: String = self.defaultCancelButtonTitle() fileprivate func defaultCancelButtonTitle() -> String { var title = "No, Thanks" // Check for a localized version of the default title if let bundle = self.bundle() { title = bundle.localizedString(forKey: title, value: bundle.localizedString(forKey: title, value:"", table: nil), table: "ArmchairLocalizable") } return title } fileprivate lazy var rateButtonTitle: String = self.defaultRateButtonTitle() fileprivate func defaultRateButtonTitle() -> String { var template = "Rate %@" // Check for a localized version of the default title if let bundle = self.bundle() { template = bundle.localizedString(forKey: template, value: bundle.localizedString(forKey: template, value:"", table: nil), table: "ArmchairLocalizable") } return template.replacingOccurrences(of: "%@", with: "\(self.appName)", options: NSString.CompareOptions(rawValue: 0), range: nil) } fileprivate lazy var remindButtonTitle: String? = self.defaultRemindButtonTitle() fileprivate func defaultRemindButtonTitle() -> String? { //if reminders are disabled, return a nil title to supress the button if self.daysBeforeReminding == 0 { return nil } var title = "Remind me later" // Check for a localized version of the default title if let bundle = self.bundle() { title = bundle.localizedString(forKey: title, value: bundle.localizedString(forKey: title, value:"", table: nil), table: "ArmchairLocalizable") } return title } // Tracking Logic / Configuration fileprivate var appID: String = "" { didSet { keyPrefix = defaultKeyPrefix() if affiliateCampaignCode == defaultAffiliateCampaignCode() { affiliateCampaignCode = affiliateCampaignCode + "-\(appID)" } } } // MARK: Properties with sensible defaults fileprivate var daysUntilPrompt: UInt = 30 fileprivate var usesUntilPrompt: UInt = 20 fileprivate var significantEventsUntilPrompt: UInt = 0 fileprivate var daysBeforeReminding: UInt = 1 fileprivate var tracksNewVersions: Bool = true fileprivate var shouldPromptIfRated: Bool = true fileprivate var useMainAppBundleForLocalizations: Bool = false fileprivate var debugEnabled: Bool = false { didSet { if self.debugEnabled { debugLog("Debug enabled for app: \(appID)") } } } // If you aren't going to set an affiliate code yourself, please leave this as is. // It is my affiliate code. It is better that somebody's code is used rather than nobody's. fileprivate var affiliateCode: String = "11l7j9" fileprivate var affiliateCampaignCode: String = "Armchair" fileprivate var useStoreKitReviewPrompt: Bool = false #if os(iOS) fileprivate var usesAnimation: Bool = true fileprivate var tintColor: UIColor? = nil fileprivate lazy var usesAlertController: Bool = self.defaultUsesAlertController() fileprivate lazy var opensInStoreKit: Bool = self.defaultOpensInStoreKit() fileprivate func defaultOpensInStoreKit() -> Bool { return operatingSystemVersion >= 8 } fileprivate func defaultUsesAlertController() -> Bool { return operatingSystemVersion >= 9 } #endif // MARK: Tracking Keys with sensible defaults fileprivate lazy var armchairKeyFirstUseDate: String = self.defaultArmchairKeyFirstUseDate() fileprivate lazy var armchairKeyUseCount: String = self.defaultArmchairKeyUseCount() fileprivate lazy var armchairKeySignificantEventCount: String = self.defaultArmchairKeySignificantEventCount() fileprivate lazy var armchairKeyCurrentVersion: String = self.defaultArmchairKeyCurrentVersion() fileprivate lazy var armchairKeyRatedCurrentVersion: String = self.defaultArmchairKeyRatedCurrentVersion() fileprivate lazy var armchairKeyDeclinedToRate: String = self.defaultArmchairKeyDeclinedToRate() fileprivate lazy var armchairKeyReminderRequestDate: String = self.defaultArmchairKeyReminderRequestDate() fileprivate lazy var armchairKeyPreviousVersion: String = self.defaultArmchairKeyPreviousVersion() fileprivate lazy var armchairKeyPreviousVersionRated: String = self.defaultArmchairKeyPreviousVersionRated() fileprivate lazy var armchairKeyPreviousVersionDeclinedToRate: String = self.defaultArmchairKeyPreviousVersionDeclinedToRate() fileprivate lazy var armchairKeyRatedAnyVersion: String = self.defaultArmchairKeyRatedAnyVersion() fileprivate lazy var armchairKeyAppiraterMigrationCompleted: String = self.defaultArmchairKeyAppiraterMigrationCompleted() fileprivate lazy var armchairKeyUAAppReviewManagerMigrationCompleted: String = self.defaultArmchairKeyUAAppReviewManagerMigrationCompleted() fileprivate func defaultArmchairKeyFirstUseDate() -> String { return "ArmchairFirstUseDate" } fileprivate func defaultArmchairKeyUseCount() -> String { return "ArmchairUseCount" } fileprivate func defaultArmchairKeySignificantEventCount() -> String { return "ArmchairSignificantEventCount" } fileprivate func defaultArmchairKeyCurrentVersion() -> String { return "ArmchairKeyCurrentVersion" } fileprivate func defaultArmchairKeyRatedCurrentVersion() -> String { return "ArmchairRatedCurrentVersion" } fileprivate func defaultArmchairKeyDeclinedToRate() -> String { return "ArmchairKeyDeclinedToRate" } fileprivate func defaultArmchairKeyReminderRequestDate() -> String { return "ArmchairReminderRequestDate" } fileprivate func defaultArmchairKeyPreviousVersion() -> String { return "ArmchairPreviousVersion" } fileprivate func defaultArmchairKeyPreviousVersionRated() -> String { return "ArmchairPreviousVersionRated" } fileprivate func defaultArmchairKeyPreviousVersionDeclinedToRate() -> String { return "ArmchairPreviousVersionDeclinedToRate" } fileprivate func defaultArmchairKeyRatedAnyVersion() -> String { return "ArmchairKeyRatedAnyVersion" } fileprivate func defaultArmchairKeyAppiraterMigrationCompleted() -> String { return "ArmchairAppiraterMigrationCompleted" } fileprivate func defaultArmchairKeyUAAppReviewManagerMigrationCompleted() -> String { return "ArmchairUAAppReviewManagerMigrationCompleted" } fileprivate lazy var keyPrefix: String = self.defaultKeyPrefix() fileprivate func defaultKeyPrefix() -> String { if !self.appID.isEmpty { return self.appID + "_" } else { return "_" } } fileprivate var userDefaultsObject:ArmchairDefaultsObject? = StandardUserDefaults() // MARK: Optional Closures var didDisplayAlertClosure: ArmchairClosure? var didDeclineToRateClosure: ArmchairClosure? var didOptToRateClosure: ArmchairClosure? var didOptToRemindLaterClosure: ArmchairClosure? var customAlertClosure: ArmchairClosureCustomAlert? #if os(iOS) var willPresentModalViewClosure: ArmchairAnimateClosure? var didDismissModalViewClosure: ArmchairAnimateClosure? #endif var shouldPromptClosure: ArmchairShouldPromptClosure? var shouldIncrementUseCountClosure: ArmchairShouldIncrementClosure? // MARK: State Vars fileprivate var modalPanelOpen: Bool = false #if os(iOS) fileprivate lazy var currentStatusBarStyle: UIStatusBarStyle = { return UIApplication.shared.statusBarStyle }() #endif // MARK: - // MARK: PRIVATE Methods fileprivate func userDidSignificantEvent(_ canPromptForRating: Bool) { DispatchQueue.global(qos: .background).async { self.incrementSignificantEventAndRate(canPromptForRating) } } fileprivate func userDidSignificantEvent(_ shouldPrompt: @escaping ArmchairShouldPromptClosure) { DispatchQueue.global(qos: .background).async { self.incrementSignificantEventAndRate(shouldPrompt) } } // MARK: - // MARK: PRIVATE Rating Helpers fileprivate func incrementAndRate(_ canPromptForRating: Bool) { migrateKeysIfNecessary() incrementUseCount() showPrompt(ifNecessary: canPromptForRating) } fileprivate func incrementAndRate(_ shouldPrompt: ArmchairShouldPromptClosure) { migrateKeysIfNecessary() incrementUseCount() showPrompt(shouldPrompt) } fileprivate func incrementSignificantEventAndRate(_ canPromptForRating: Bool) { migrateKeysIfNecessary() incrementSignificantEventCount() showPrompt(ifNecessary: canPromptForRating) } fileprivate func incrementSignificantEventAndRate(_ shouldPrompt: ArmchairShouldPromptClosure) { migrateKeysIfNecessary() incrementSignificantEventCount() showPrompt(shouldPrompt) } fileprivate func incrementUseCount() { var shouldIncrement = true if let closure = shouldIncrementUseCountClosure { shouldIncrement = closure() } if shouldIncrement { _incrementCountForKeyType(ArmchairKey.UseCount) } } fileprivate func incrementSignificantEventCount() { _incrementCountForKeyType(ArmchairKey.SignificantEventCount) } fileprivate func _incrementCountForKeyType(_ incrementKeyType: ArmchairKey) { let incrementKey = keyForArmchairKeyType(incrementKeyType) let bundleVersionKey = kCFBundleVersionKey as String // App's version. Not settable as the other ivars because that would be crazy. let currentVersion = Bundle.main.object(forInfoDictionaryKey: bundleVersionKey) as? String if currentVersion == nil { assertionFailure("Could not read kCFBundleVersionKey from InfoDictionary") return } // Get the version number that we've been tracking thus far let currentVersionKey = keyForArmchairKeyType(ArmchairKey.CurrentVersion) var trackingVersion: String? = userDefaultsObject?.stringForKey(currentVersionKey) // New install, or changed keys if trackingVersion == nil { trackingVersion = currentVersion userDefaultsObject?.setObject(currentVersion as AnyObject?, forKey: currentVersionKey) } debugLog("Tracking version: \(trackingVersion!)") if trackingVersion == currentVersion { // Check if the first use date has been set. if not, set it. let firstUseDateKey = keyForArmchairKeyType(ArmchairKey.FirstUseDate) var timeInterval: Double? = userDefaultsObject?.doubleForKey(firstUseDateKey) if 0 == timeInterval { timeInterval = Date().timeIntervalSince1970 userDefaultsObject?.setObject(NSNumber(value: timeInterval!), forKey: firstUseDateKey) } // Increment the key's count var incrementKeyCount = userDefaultsObject!.integerForKey(incrementKey) incrementKeyCount += 1 userDefaultsObject?.setInteger(incrementKeyCount, forKey:incrementKey) debugLog("Incremented \(incrementKeyType): \(incrementKeyCount)") } else if tracksNewVersions { // it's a new version of the app, so restart tracking resetAllCounters() debugLog("Reset Tracking Version to: \(trackingVersion!)") } userDefaultsObject?.synchronize() } fileprivate func showPrompt(ifNecessary canPromptForRating: Bool) { if canPromptForRating && connectedToNetwork() && ratingConditionsHaveBeenMet() { var shouldPrompt: Bool = true if let closure = shouldPromptClosure { if Thread.isMainThread { shouldPrompt = closure(trackingInfo()) } else { DispatchQueue.main.sync { shouldPrompt = closure(self.trackingInfo()) } } } if shouldPrompt { DispatchQueue.main.async { self.showRatingAlert() } } } } fileprivate func showPrompt(_ shouldPrompt: ArmchairShouldPromptClosure) { var shouldPromptVal = false if Thread.isMainThread { shouldPromptVal = shouldPrompt(trackingInfo()) } else { DispatchQueue.main.sync { shouldPromptVal = shouldPrompt(self.trackingInfo()) } } if (shouldPromptVal) { DispatchQueue.main.async { self.showRatingAlert() } } } fileprivate func showPrompt() { if !appID.isEmpty && connectedToNetwork() && !userHasDeclinedToRate() && !userHasRatedCurrentVersion() { showRatingAlert() } } fileprivate func ratingConditionsHaveBeenMet() -> Bool { if debugEnabled { return true } if appID.isEmpty { return false } // check if the app has been used long enough let timeIntervalOfFirstLaunch = userDefaultsObject?.doubleForKey(keyForArmchairKeyType(ArmchairKey.FirstUseDate)) if let timeInterval = timeIntervalOfFirstLaunch { let dateOfFirstLaunch = Date(timeIntervalSince1970: timeInterval) let timeSinceFirstLaunch = Date().timeIntervalSince(dateOfFirstLaunch) let timeUntilRate: TimeInterval = 60 * 60 * 24 * Double(daysUntilPrompt) if timeSinceFirstLaunch < timeUntilRate { return false } } else { return false } // check if the app has been used enough times let useCount = userDefaultsObject?.integerForKey(keyForArmchairKeyType(ArmchairKey.UseCount)) if let count = useCount { if UInt(count) <= usesUntilPrompt { return false } } else { return false } // check if the user has done enough significant events let significantEventCount = userDefaultsObject?.integerForKey(keyForArmchairKeyType(ArmchairKey.SignificantEventCount)) if let count = significantEventCount { if UInt(count) < significantEventsUntilPrompt { return false } } else { return false } // Check if the user previously has declined to rate this version of the app if userHasDeclinedToRate() { return false } // Check if the user has already rated the app? if userHasRatedCurrentVersion() { return false } // If the user wanted to be reminded later, has enough time passed? let timeIntervalOfReminder = userDefaultsObject?.doubleForKey(keyForArmchairKeyType(ArmchairKey.ReminderRequestDate)) if let timeInterval = timeIntervalOfReminder { let reminderRequestDate = Date(timeIntervalSince1970: timeInterval) let timeSinceReminderRequest = Date().timeIntervalSince(reminderRequestDate) let timeUntilReminder: TimeInterval = 60 * 60 * 24 * Double(daysBeforeReminding) if timeSinceReminderRequest < timeUntilReminder { return false } } else { return false } // if we have a global set to not show if the end-user has already rated once, and the developer has not opted out of displaying on minor updates let ratedAnyVersion = userDefaultsObject?.boolForKey(keyForArmchairKeyType(ArmchairKey.RatedAnyVersion)) if let ratedAlready = ratedAnyVersion { if (!shouldPromptIfRated && ratedAlready) { return false } } return true } fileprivate func userHasDeclinedToRate() -> Bool { if let declined = userDefaultsObject?.boolForKey(keyForArmchairKeyType(ArmchairKey.DeclinedToRate)) { return declined } else { return false } } fileprivate func userHasRatedCurrentVersion() -> Bool { if let ratedCurrentVersion = userDefaultsObject?.boolForKey(keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) { return ratedCurrentVersion } else { return false } } fileprivate func showsRemindButton() -> Bool { return (daysBeforeReminding > 0 && remindButtonTitle != nil) } public var shouldTryStoreKitReviewPrompt : Bool { #if os(iOS) if #available(iOS 10.3, *), useStoreKitReviewPrompt { return true } #endif return false } fileprivate func requestStoreKitReviewPrompt() -> Bool { if #available(iOS 10.3, OSX 10.14, *), useStoreKitReviewPrompt { SKStoreReviewController.requestReview() // Assume this version is rated. There is no API to tell if the user actaully rated. userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.RatedAnyVersion)) userDefaultsObject?.synchronize() #if os(iOS) closeModalPanel() #endif return true } return false } fileprivate func showRatingAlert() { if let customClosure = customAlertClosure { customClosure({[weak self] in if let result = self?.requestStoreKitReviewPrompt(), result { ///Showed storekit prompt, all done } else { /// Didn't show storekit prompt, present app store manually self?._rateApp() } }, {[weak self] in self?.remindMeLater()}, {[weak self] in self?.dontRate()}) if let closure = self.didDisplayAlertClosure { closure() } } else { if requestStoreKitReviewPrompt() { ///Showed storekit prompt, all done return } #if os(iOS) /// Didn't show storekit prompt, present app store manually let alertView : UIAlertController = UIAlertController(title: reviewTitle, message: reviewMessage, preferredStyle: .alert) alertView.addAction(UIAlertAction(title: rateButtonTitle, style: .default, handler: { (alert: UIAlertAction!) in self._rateApp() })) if (showsRemindButton()) { alertView.addAction(UIAlertAction(title: remindButtonTitle!, style: .default, handler: { (alert: UIAlertAction!) in self.remindMeLater() })) } alertView.addAction(UIAlertAction(title: cancelButtonTitle, style: .cancel, handler: { (alert: UIAlertAction!) in self.dontRate() })) ratingAlert = alertView // get the top most controller (= the StoreKit Controller) and dismiss it if let presentingController = UIApplication.shared.keyWindow?.rootViewController { if let topController = Manager.topMostViewController(presentingController) { topController.present(alertView, animated: usesAnimation) { [weak self] in if let closure = self?.didDisplayAlertClosure { closure() } print("presentViewController() completed") } } // note that tint color has to be set after the controller is presented in order to take effect (last checked in iOS 9.3) alertView.view.tintColor = tintColor } #elseif os(OSX) let alert: NSAlert = NSAlert() alert.messageText = reviewTitle alert.informativeText = reviewMessage alert.addButton(withTitle: rateButtonTitle) if showsRemindButton() { alert.addButton(withTitle: remindButtonTitle!) } alert.addButton(withTitle: cancelButtonTitle) ratingAlert = alert if let window = NSApplication.shared.keyWindow { alert.beginSheetModal(for: window) { (response: NSApplication.ModalResponse) in self.handleNSAlertResponse(response) } } else { let response = alert.runModal() handleNSAlertResponse(response) } if let closure = self.didDisplayAlertClosure { closure() } #else #endif } } // MARK: - // MARK: PRIVATE Alert View / StoreKit Delegate Methods #if os(iOS) //Delegate call from the StoreKit view. open func productViewControllerDidFinish(_ viewController: SKStoreProductViewController!) { closeModalPanel() } //Close the in-app rating (StoreKit) view and restore the previous status bar style. fileprivate func closeModalPanel() { let usedAnimation = usesAnimation if modalPanelOpen { UIApplication.shared.setStatusBarStyle(currentStatusBarStyle, animated:usesAnimation) modalPanelOpen = false // get the top most controller (= the StoreKit Controller) and dismiss it if let presentingController = UIApplication.shared.keyWindow?.rootViewController { if let topController = Manager.topMostViewController(presentingController) { topController.dismiss(animated: usesAnimation) {} currentStatusBarStyle = UIStatusBarStyle.default } } } if let closure = self.didDismissModalViewClosure { closure(usedAnimation) } } #elseif os(OSX) private func handleNSAlertResponse(_ response: NSApplication.ModalResponse) { switch (response) { case .alertFirstButtonReturn: // they want to rate it _rateApp() case .alertSecondButtonReturn: // remind them later or cancel if showsRemindButton() { remindMeLater() } else { dontRate() } case .alertThirdButtonReturn: // they don't want to rate it dontRate() default: return } } #else #endif private func dontRate() { userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.DeclinedToRate)) userDefaultsObject?.synchronize() if let closure = didDeclineToRateClosure { closure() } } private func remindMeLater() { userDefaultsObject?.setDouble(Date().timeIntervalSince1970, forKey: keyForArmchairKeyType(ArmchairKey.ReminderRequestDate)) userDefaultsObject?.synchronize() if let closure = didOptToRemindLaterClosure { closure() } } private func _rateApp() { rateApp() if let closure = didOptToRateClosure { closure() } } fileprivate func rateApp() { userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.RatedAnyVersion)) userDefaultsObject?.synchronize() #if os(iOS) // Use the in-app StoreKit view if set, available (iOS 7+) and imported. This works in the simulator. if opensInStoreKit { let storeViewController = SKStoreProductViewController() var productParameters: [String:AnyObject]! = [SKStoreProductParameterITunesItemIdentifier : appID as AnyObject] if (operatingSystemVersion >= 8) { productParameters[SKStoreProductParameterAffiliateToken] = affiliateCode as AnyObject? productParameters[SKStoreProductParameterCampaignToken] = affiliateCampaignCode as AnyObject? } storeViewController.loadProduct(withParameters: productParameters, completionBlock: nil) storeViewController.delegate = self if let closure = willPresentModalViewClosure { closure(usesAnimation) } if let rootController = Manager.getRootViewController() { rootController.present(storeViewController, animated: usesAnimation) { self.modalPanelOpen = true //Temporarily use a status bar to match the StoreKit view. self.currentStatusBarStyle = UIApplication.shared.statusBarStyle UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.default, animated: self.usesAnimation) } } //Use the standard openUrl method } else { if let url = URL(string: reviewURLString()) { UIApplication.shared.openURL(url) } } #if targetEnvironment(simulator) debugLog("iTunes App Store is not supported on the iOS simulator.") debugLog(" - We would have went to \(reviewURLString()).") debugLog(" - Try running on a test-device") let fakeURL = reviewURLString().replacingOccurrences(of: "itms-apps", with:"http") debugLog(" - Or try copy/pasting \(fakeURL) into a browser on your computer.") #endif #elseif os(OSX) if let url = URL(string: reviewURLString()) { let opened = NSWorkspace.shared.open(url) if !opened { debugLog("Failed to open \(url)") } } #else #endif } fileprivate func reviewURLString() -> String { #if os(iOS) let template = operatingSystemVersion >= 11 ? reviewURLTemplateiOS11 : reviewURLTemplate #elseif os(OSX) let template = reviewURLTemplate #else #endif var reviewURL = template.replacingOccurrences(of: "APP_ID", with: "\(appID)") reviewURL = reviewURL.replacingOccurrences(of: "AFFILIATE_CODE", with: "\(affiliateCode)") return reviewURL } // Mark: - // Mark: PRIVATE Key Helpers private func trackingInfo() -> ArmchairTrackingInfo { var trackingInfo: Dictionary<ArmchairKey, AnyObject> = [:] for keyType in ArmchairKey.allValues { let obj: AnyObject? = userDefaultsObject?.objectForKey(keyForArmchairKeyType(keyType)) if let val = obj as? NSObject { trackingInfo[keyType] = val } else { trackingInfo[keyType] = NSNull() } } return ArmchairTrackingInfo(info: trackingInfo) } fileprivate func keyForArmchairKeyType(_ keyType: ArmchairKey) -> String { switch (keyType) { case .FirstUseDate: return keyPrefix + armchairKeyFirstUseDate case .UseCount: return keyPrefix + armchairKeyUseCount case .SignificantEventCount: return keyPrefix + armchairKeySignificantEventCount case .CurrentVersion: return keyPrefix + armchairKeyCurrentVersion case .RatedCurrentVersion: return keyPrefix + armchairKeyRatedCurrentVersion case .DeclinedToRate: return keyPrefix + armchairKeyDeclinedToRate case .ReminderRequestDate: return keyPrefix + armchairKeyReminderRequestDate case .PreviousVersion: return keyPrefix + armchairKeyPreviousVersion case .PreviousVersionRated: return keyPrefix + armchairKeyPreviousVersionRated case .PreviousVersionDeclinedToRate: return keyPrefix + armchairKeyPreviousVersionDeclinedToRate case .RatedAnyVersion: return keyPrefix + armchairKeyRatedAnyVersion case .AppiraterMigrationCompleted: return keyPrefix + armchairKeyAppiraterMigrationCompleted case .UAAppReviewManagerMigrationCompleted: return keyPrefix + armchairKeyUAAppReviewManagerMigrationCompleted } } fileprivate func setKey(_ key: NSString, armchairKeyType: ArmchairKey) { switch armchairKeyType { case .FirstUseDate: armchairKeyFirstUseDate = key as String case .UseCount: armchairKeyUseCount = key as String case .SignificantEventCount: armchairKeySignificantEventCount = key as String case .CurrentVersion: armchairKeyCurrentVersion = key as String case .RatedCurrentVersion: armchairKeyRatedCurrentVersion = key as String case .DeclinedToRate: armchairKeyDeclinedToRate = key as String case .ReminderRequestDate: armchairKeyReminderRequestDate = key as String case .PreviousVersion: armchairKeyPreviousVersion = key as String case .PreviousVersionRated: armchairKeyPreviousVersionRated = key as String case .PreviousVersionDeclinedToRate: armchairKeyPreviousVersionDeclinedToRate = key as String case .RatedAnyVersion: armchairKeyRatedAnyVersion = key as String case .AppiraterMigrationCompleted: armchairKeyAppiraterMigrationCompleted = key as String case .UAAppReviewManagerMigrationCompleted: armchairKeyUAAppReviewManagerMigrationCompleted = key as String } } private func armchairKeyForAppiraterKey(_ appiraterKey: String) -> String { switch appiraterKey { case AppiraterKey.FirstUseDate: return keyForArmchairKeyType(ArmchairKey.FirstUseDate) case AppiraterKey.UseCount: return keyForArmchairKeyType(ArmchairKey.UseCount) case AppiraterKey.SignificantEventCount: return keyForArmchairKeyType(ArmchairKey.SignificantEventCount) case AppiraterKey.CurrentVersion: return keyForArmchairKeyType(ArmchairKey.CurrentVersion) case AppiraterKey.RatedCurrentVersion: return keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion) case AppiraterKey.DeclinedToRate: return keyForArmchairKeyType(ArmchairKey.DeclinedToRate) case AppiraterKey.ReminderRequestDate: return keyForArmchairKeyType(ArmchairKey.ReminderRequestDate) case AppiraterKey.RatedAnyVersion: return keyForArmchairKeyType(ArmchairKey.RatedAnyVersion) default: return "" } } private func migrateAppiraterKeysIfNecessary() { let appiraterAlreadyCompletedKey: NSString = keyForArmchairKeyType(.AppiraterMigrationCompleted) as NSString let appiraterMigrationAlreadyCompleted = userDefaultsObject?.boolForKey(appiraterAlreadyCompletedKey as String) if let completed = appiraterMigrationAlreadyCompleted { if completed { return } } let oldKeys: [String] = [AppiraterKey.FirstUseDate, AppiraterKey.UseCount, AppiraterKey.SignificantEventCount, AppiraterKey.CurrentVersion, AppiraterKey.RatedCurrentVersion, AppiraterKey.RatedAnyVersion, AppiraterKey.DeclinedToRate, AppiraterKey.ReminderRequestDate] for oldKey in oldKeys { let oldValue: NSObject? = userDefaultsObject?.objectForKey(oldKey) as? NSObject if let val = oldValue { let newKey = armchairKeyForAppiraterKey(oldKey) userDefaultsObject?.setObject(val, forKey: newKey) userDefaultsObject?.removeObjectForKey(oldKey) } } userDefaultsObject?.setObject(NSNumber(value: true), forKey: appiraterAlreadyCompletedKey as String) userDefaultsObject?.synchronize() } // This only supports the default UAAppReviewManager keys. If you customized them, you will have to manually migrate your values over. private func migrateUAAppReviewManagerKeysIfNecessary() { let appReviewManagerAlreadyCompletedKey: NSString = keyForArmchairKeyType(.UAAppReviewManagerMigrationCompleted) as NSString let appReviewManagerMigrationAlreadyCompleted = userDefaultsObject?.boolForKey(appReviewManagerAlreadyCompletedKey as String) if let completed = appReviewManagerMigrationAlreadyCompleted { if completed { return } } // By default, UAAppReviewManager keys are in the format <appID>_UAAppReviewManagerKey<keyType> let oldKeys: [String:ArmchairKey] = ["\(appID)_UAAppReviewManagerKeyFirstUseDate" : ArmchairKey.FirstUseDate, "\(appID)_UAAppReviewManagerKeyUseCount" : ArmchairKey.UseCount, "\(appID)_UAAppReviewManagerKeySignificantEventCount" : ArmchairKey.SignificantEventCount, "\(appID)_UAAppReviewManagerKeyCurrentVersion" : ArmchairKey.CurrentVersion, "\(appID)_UAAppReviewManagerKeyRatedCurrentVersion" : ArmchairKey.RatedCurrentVersion, "\(appID)_UAAppReviewManagerKeyDeclinedToRate" : ArmchairKey.DeclinedToRate, "\(appID)_UAAppReviewManagerKeyReminderRequestDate" : ArmchairKey.ReminderRequestDate, "\(appID)_UAAppReviewManagerKeyPreviousVersion" : ArmchairKey.PreviousVersion, "\(appID)_UAAppReviewManagerKeyPreviousVersionRated" : ArmchairKey.PreviousVersionRated, "\(appID)_UAAppReviewManagerKeyPreviousVersionDeclinedToRate" : ArmchairKey.PreviousVersionDeclinedToRate, "\(appID)_UAAppReviewManagerKeyRatedAnyVersion" : ArmchairKey.RatedAnyVersion] for (oldKey, newKeyType) in oldKeys { let oldValue: NSObject? = userDefaultsObject?.objectForKey(oldKey) as? NSObject if let val = oldValue { userDefaultsObject?.setObject(val, forKey: keyForArmchairKeyType(newKeyType)) userDefaultsObject?.removeObjectForKey(oldKey) } } userDefaultsObject?.setObject(NSNumber(value: true), forKey: appReviewManagerAlreadyCompletedKey as String) userDefaultsObject?.synchronize() } private func migrateKeysIfNecessary() { migrateAppiraterKeysIfNecessary() migrateUAAppReviewManagerKeysIfNecessary() } // MARK: - // MARK: Internet Connectivity private func connectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return false } var flags : SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return false } let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) return (isReachable && !needsConnection) } // MARK: - // MARK: PRIVATE Misc Helpers private func bundle() -> Bundle? { var bundle: Bundle? = nil if useMainAppBundleForLocalizations { bundle = Bundle.main } else { let armchairBundleURL: URL? = Bundle.main.url(forResource: "Armchair", withExtension: "bundle") if let url = armchairBundleURL { bundle = Bundle(url: url) } else { bundle = Bundle(for: type(of: self)) } } return bundle } #if os(iOS) private static func topMostViewController(_ controller: UIViewController?) -> UIViewController? { var isPresenting: Bool = false var topController: UIViewController? = controller repeat { // this path is called only on iOS 6+, so -presentedViewController is fine here. if let controller = topController { if let presented = controller.presentedViewController { isPresenting = true topController = presented } else { isPresenting = false } } } while isPresenting return topController } private static func getRootViewController() -> UIViewController? { if var window = UIApplication.shared.keyWindow { if window.windowLevel != UIWindow.Level.normal { let windows: NSArray = UIApplication.shared.windows as NSArray for candidateWindow in windows { if let candidateWindow = candidateWindow as? UIWindow { if candidateWindow.windowLevel == UIWindow.Level.normal { window = candidateWindow break } } } } return iterateSubViewsForViewController(window) } return nil } private static func iterateSubViewsForViewController(_ parentView: UIView) -> UIViewController? { for subView in parentView.subviews { if let responder = subView.next { if responder.isKind(of: UIViewController.self) { return topMostViewController(responder as? UIViewController) } } if let found = iterateSubViewsForViewController(subView) { return found } } return nil } #endif private func hideRatingAlert() { if let alert = ratingAlert { debugLog("Hiding Alert") #if os(iOS) let isAlertVisible = alert.isViewLoaded && alert.view.window != nil if isAlertVisible { alert.dismiss(animated: false, completion: { self.dontRate() }) } #elseif os(OSX) if let window = NSApplication.shared.keyWindow { if let parent = window.sheetParent { parent.endSheet(window) } } #else #endif ratingAlert = nil } } fileprivate func defaultAffiliateCode() -> String { return "11l7j9" } fileprivate func defaultAffiliateCampaignCode() -> String { return "Armchair" } // MARK: - // MARK: Notification Handlers @objc public func appWillResignActive(_ notification: Notification) { debugLog("appWillResignActive:") hideRatingAlert() } @objc public func applicationDidFinishLaunching(_ notification: Notification) { DispatchQueue.global(qos: .background).async { self.debugLog("applicationDidFinishLaunching:") self.migrateKeysIfNecessary() self.incrementUseCount() } } @objc public func applicationWillEnterForeground(_ notification: Notification) { DispatchQueue.global(qos: .background).async { self.debugLog("applicationWillEnterForeground:") self.migrateKeysIfNecessary() self.incrementUseCount() } } // MARK: - // MARK: Singleton public class var defaultManager: Manager { assert(Armchair.appID != "", "Armchair.appID(appID: String) has to be the first Armchair call made.") struct Singleton { static let instance: Manager = Manager(appID: Armchair.appID) } return Singleton.instance } init(appID: String) { super.init() setupNotifications() } // MARK: Singleton Instance Setup fileprivate func setupNotifications() { #if os(iOS) NotificationCenter.default.addObserver(self, selector: #selector(Manager.appWillResignActive(_:)), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Manager.applicationDidFinishLaunching(_:)), name: UIApplication.didFinishLaunchingNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Manager.applicationWillEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil) #elseif os(OSX) NotificationCenter.default.addObserver(self, selector: #selector(Manager.appWillResignActive(_:)), name: NSApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Manager.applicationDidFinishLaunching(_:)), name: NSApplication.didFinishLaunchingNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Manager.applicationWillEnterForeground(_:)), name: NSApplication.willBecomeActiveNotification, object: nil) #else #endif } // MARK: - // MARK: Printable override open var debugDescription: String { get { return "Armchair: appID=\(Armchair.appID)" } } // MARK: - // MARK: Debug let lockQueue = DispatchQueue(label: "com.armchair.lockqueue") public var logger: ArmchairLogger = { manager, log, file, function, line in if manager.debugEnabled { manager.lockQueue.sync(execute: { print("[Armchair] \(log)") }) } } fileprivate func debugLog(_ log: String, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) { logger(self, log, file, function, line) } }
mit
f7c362d359ace59e464793a4f6722345
42.288996
302
0.661957
5.196678
false
false
false
false
myfreeweb/SwiftCBOR
Sources/SwiftCBOR/Decoder/CodableCBORDecoder.swift
2
3231
import Foundation /** */ final public class CodableCBORDecoder { public init() {} public var userInfo: [CodingUserInfoKey : Any] = [:] public func decode<T: Decodable>(_ type: T.Type, from data: Data) throws -> T { let decoder = _CBORDecoder(data: data) decoder.userInfo = self.userInfo if type == Date.self { guard let cbor = try? CBORDecoder(input: [UInt8](data)).decodeItem(), case .date(let date) = cbor else { let context = DecodingError.Context(codingPath: [], debugDescription: "Unable to decode data for Date") throw DecodingError.dataCorrupted(context) } return date as! T } else if type == Data.self { guard let cbor = try? CBORDecoder(input: [UInt8](data)).decodeItem(), case .byteString(let data) = cbor else { let context = DecodingError.Context(codingPath: [], debugDescription: "Unable to decode data for Data") throw DecodingError.dataCorrupted(context) } return Data(data) as! T } return try T(from: decoder) } } final class _CBORDecoder { var codingPath: [CodingKey] = [] var userInfo: [CodingUserInfoKey : Any] = [:] var container: CBORDecodingContainer? fileprivate var data: Data init(data: Data) { self.data = data } } extension _CBORDecoder: Decoder { func container<Key: CodingKey>(keyedBy type: Key.Type) -> KeyedDecodingContainer<Key> { let container = KeyedContainer<Key>(data: self.data, codingPath: self.codingPath, userInfo: self.userInfo) self.container = container return KeyedDecodingContainer(container) } func unkeyedContainer() -> UnkeyedDecodingContainer { let container = UnkeyedContainer(data: self.data, codingPath: self.codingPath, userInfo: self.userInfo) self.container = container return container } func singleValueContainer() -> SingleValueDecodingContainer { let container = SingleValueContainer(data: self.data, codingPath: self.codingPath, userInfo: self.userInfo) self.container = container return container } } protocol CBORDecodingContainer: class { var codingPath: [CodingKey] { get set } var userInfo: [CodingUserInfoKey : Any] { get } var data: Data { get set } var index: Data.Index { get set } } extension CBORDecodingContainer { func readByte() throws -> UInt8 { return try read(1).first! } func read(_ length: Int) throws -> Data { let nextIndex = self.index.advanced(by: length) guard nextIndex <= self.data.endIndex else { let context = DecodingError.Context(codingPath: self.codingPath, debugDescription: "Unexpected end of data") throw DecodingError.dataCorrupted(context) } defer { self.index = nextIndex } return self.data.subdata(in: self.index..<nextIndex) } func read<T: FixedWidthInteger>(_ type: T.Type) throws -> T { let stride = MemoryLayout<T>.stride let bytes = [UInt8](try read(stride)) return T(bytes: bytes) } }
unlicense
9834000e8d5d2fbeb6c6e1ffa86d273e
30.990099
120
0.626431
4.582979
false
false
false
false
ihomam/Karatsuba-implementation
Karatsuba.playground/Contents.swift
1
1051
import UIKit import Foundation //: implementation of Karatsuba multiplication algorithm //: x.y = 10ᴺ ac + 10ⁿ⁰⁵ (ad+bc) + bd func calc(num1 num1:Int,num2:Int) -> Int { var aPart = String(num1) var bPart = String(num1) var cPart = String(num2) var dPart = String(num2) let n:Int = aPart.characters.count aPart.removeRange(aPart.startIndex.advancedBy(aPart.characters.count/2)..<aPart.endIndex) bPart.removeRange(bPart.startIndex..<bPart.endIndex.advancedBy(-bPart.characters.count/2)) cPart.removeRange(cPart.startIndex.advancedBy(cPart.characters.count/2)..<cPart.endIndex) dPart.removeRange(dPart.startIndex..<dPart.endIndex.advancedBy(-dPart.characters.count/2)) let a:Int = Int(aPart)! let b:Int = Int(bPart)! let c:Int = Int(cPart)! let d:Int = Int(dPart)! let ac = (Int(pow(Double(10),Double(n)))*a*c) let adbc = (Int(pow(Double(10),Double(n/2)))*((a*d)+(b*c))) let result = ac + adbc + (b*d) return result } calc(num1: 1234, num2: 5678)
gpl-3.0
a025e64d244c8c703a14a2679fed89f5
31.59375
94
0.662512
2.897222
false
false
false
false
tjw/swift
test/decl/protocol/conforms/nscoding.swift
2
7529
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -swift-version 4 %s -verify // RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -swift-version 4 %s -disable-nskeyedarchiver-diagnostics 2>&1 | %FileCheck -check-prefix CHECK-NO-DIAGS %s // RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -swift-version 4 %s -dump-ast 2> %t.ast // RUN: %FileCheck %s < %t.ast // REQUIRES: objc_interop // CHECK-NO-DIAGS-NOT: NSCoding // CHECK-NO-DIAGS-NOT: unstable import Foundation // Top-level classes // CHECK-NOT: class_decl "CodingA"{{.*}}@_staticInitializeObjCMetadata class CodingA : NSObject, NSCoding { required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } // okay // Nested classes extension CodingA { // CHECK-NOT: class_decl "NestedA"{{.*}}@_staticInitializeObjCMetadata class NestedA : NSObject, NSCoding { // expected-error{{nested class 'CodingA.NestedA' has an unstable name when archiving via 'NSCoding'}} // expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{3-3=@objc(_TtCC8nscoding7CodingA7NestedA)}} // expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{3-3=@objc(<#prefixed Objective-C class name#>)}} required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } class NestedB : NSObject { // expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{3-3=@objc(_TtCC8nscoding7CodingA7NestedB)}} // expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{3-3=@objc(<#prefixed Objective-C class name#>)}} required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } // CHECK-NOT: class_decl "NestedC"{{.*}}@_staticInitializeObjCMetadata @objc(CodingA_NestedC) class NestedC : NSObject, NSCoding { required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } // CHECK-NOT: class_decl "NestedD"{{.*}}@_staticInitializeObjCMetadata @objc(CodingA_NestedD) class NestedD : NSObject { required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } } extension CodingA.NestedB: NSCoding { // expected-error{{nested class 'CodingA.NestedB' has an unstable name when archiving via 'NSCoding'}} } extension CodingA.NestedD: NSCoding { // okay } // Generic classes // CHECK-NOT: class_decl "CodingB"{{.*}}@_staticInitializeObjCMetadata class CodingB<T> : NSObject, NSCoding { required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } extension CodingB { class NestedA : NSObject, NSCoding { required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } } // Fileprivate classes. // CHECK-NOT: class_decl "CodingC"{{.*}}@_staticInitializeObjCMetadata fileprivate class CodingC : NSObject, NSCoding { // expected-error{{fileprivate class 'CodingC' has an unstable name when archiving via 'NSCoding'}} // expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{1-1=@objc(_TtC8nscodingP33_0B4E7641C0BD1F170280EEDD0D0C1F6C7CodingC)}} // expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{1-1=@objc(<#prefixed Objective-C class name#>)}} required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } // Private classes private class CodingD : NSObject, NSCoding { // expected-error{{private class 'CodingD' has an unstable name when archiving via 'NSCoding'}} // expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{1-1=@objc(_TtC8nscodingP33_0B4E7641C0BD1F170280EEDD0D0C1F6C7CodingD)}} // expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{1-1=@objc(<#prefixed Objective-C class name#>)}} required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } // Local classes. func someFunction() { class LocalCoding : NSObject, NSCoding { // expected-error{{local class 'LocalCoding' has an unstable name when archiving via 'NSCoding'}} // expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{3-3=@objc(_TtCF8nscoding12someFunctionFT_T_L_11LocalCoding)}} // expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{3-3=@objc(<#prefixed Objective-C class name#>)}} required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } } // Inherited conformances. // CHECK-NOT: class_decl "CodingE"{{.*}}@_staticInitializeObjCMetadata class CodingE<T> : CodingB<T> { required init(coder: NSCoder) { super.init(coder: coder) } override func encode(coder: NSCoder) { } } // @objc suppressions @objc(TheCodingF) fileprivate class CodingF : NSObject, NSCoding { required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } @objc(TheCodingG) private class CodingG : NSObject, NSCoding { required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } extension CodingB { // CHECK-NOT: class_decl "GenericViaScope"{{.*}}@_staticInitializeObjCMetadata @objc(GenericViaScope) // expected-error {{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} class GenericViaScope : NSObject { } } // Inference of @_staticInitializeObjCMetadata. // CHECK-NOT: class_decl "SubclassOfCodingA"{{.*}}@_staticInitializeObjCMetadata class SubclassOfCodingA : CodingA { } // CHECK: class_decl "SubclassOfCodingE"{{.*}}@_staticInitializeObjCMetadata class SubclassOfCodingE : CodingE<Int> { } // Do not warn when simply inheriting from classes that conform to NSCoding. // The subclass may never be serialized. But do still infer static // initialization, just in case. // CHECK-NOT: class_decl "PrivateSubclassOfCodingA"{{.*}}@_staticInitializeObjCMetadata private class PrivateSubclassOfCodingA : CodingA { } // CHECK: class_decl "PrivateSubclassOfCodingE"{{.*}}@_staticInitializeObjCMetadata private class PrivateSubclassOfCodingE : CodingE<Int> { } // But do warn when inherited through a protocol. protocol AlsoNSCoding : NSCoding {} private class CodingH : NSObject, AlsoNSCoding { // expected-error{{private class 'CodingH' has an unstable name when archiving via 'NSCoding'}} // expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{1-1=@objc(_TtC8nscodingP33_0B4E7641C0BD1F170280EEDD0D0C1F6C7CodingH)}} // expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{1-1=@objc(<#prefixed Objective-C class name#>)}} required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } @NSKeyedArchiverClassName( "abc" ) // expected-error {{@NSKeyedArchiverClassName has been removed; use @objc instead}} {{2-26=objc}} {{28-29=}} {{32-33=}} class OldArchiverAttribute: NSObject {} @NSKeyedArchiverEncodeNonGenericSubclassesOnly // expected-error {{@NSKeyedArchiverEncodeNonGenericSubclassesOnly is no longer necessary}} {{1-48=}} class OldArchiverAttributeGeneric<T>: NSObject {} // Don't allow one to write @_staticInitializeObjCMetadata! @_staticInitializeObjCMetadata // expected-error{{unknown attribute '_staticInitializeObjCMetadata'}} class DontAllowStaticInits { }
apache-2.0
420ed572fecdc46b85bf49407bf0e1a9
46.352201
201
0.726923
3.683464
false
false
false
false
FearfulFox/sacred-tiles
Sacred Tiles/MainMenuView.swift
1
13272
// // MainMenuView.swift // Sacred Tiles // // Created by Fox on 2/16/15. // Copyright (c) 2015 eCrow. All rights reserved. // import UIKit; import SpriteKit; class MainMenuView: CommonSKView { // /*============================================================ // Main Menu Scene class MyScene: CommonSKScene { // SPRITES ----- // monk var monkSprite: CommonSKSpriteNode = CommonSKSpriteNode(imageNamed: "Monk", size: CGSize(width:0.285, height: 0.522)); // Symbols var symbolSprites: [CommonSKSpriteNode] = [CommonSKSpriteNode](); // background var backgroundSprite: CommonSKSpriteNode = CommonSKSpriteNode(imageNamed: "MainMenuLayer", size: CGSize(width: 1.0, height: 1.0)); // Play BUTTON var playButton: ButtonSprite = ButtonSprite(text: "Play", type: ButtonSprite.TYPE.Large); var optionsButton: ButtonSprite = ButtonSprite(text: "Options", type: ButtonSprite.TYPE.Small); var aboutButton: ButtonSprite = ButtonSprite(text: "About", type: ButtonSprite.TYPE.Small); var standardModeButton: ButtonSprite = ButtonSprite(text: "Standard", type: ButtonSprite.TYPE.Square); var hardcoreModeButton: ButtonSprite = ButtonSprite(text: "Hardcore", type: ButtonSprite.TYPE.Square); // Mode switching state var isModeSwitching:Bool = false; // Common button closures var pressClosure: (SKNode)->() = ({(selfNode: SKNode)->() in }); var releaseClosure: (SKNode)->() = ({(selfNode: SKNode)->() in }); // Tiles var tiles: [TileSprite] = [TileSprite](); // Particle Test var dustEmitter: SKEmitterNode = Particle.getParticle("MyParticle"); // ACTIONS var floatUp: SKAction; var floatDown: SKAction; var floatingAction: SKAction; override init(){ // Init the actions self.floatUp = SKAction.moveByX(0, y: CommonSKSpriteNode.iPadYAspect(20.0), duration: 3.5); self.floatUp.timingMode = SKActionTimingMode.EaseInEaseOut; self.floatDown = SKAction.moveByX(0, y: CommonSKSpriteNode.iPadYAspect(-20.0), duration: 3.5); self.floatDown.timingMode = SKActionTimingMode.EaseInEaseOut; self.floatingAction = SKAction.sequence([floatUp, floatDown]); let symbolNames = ["SymbolBlue","SymbolGreen","SymbolPurple","SymbolRed","SymbolYellow"]; for name in symbolNames { self.symbolSprites.append(CommonSKSpriteNode(imageNamed: name, size: CGSize(width:0.05, height: 0.095))); } super.init(); } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToView(view: SKView) { self.backgroundColor = SKColor(red: 0.62, green: 0.52, blue: 0.36, alpha: 1.0); self.dustEmitter.position = CommonSKSpriteNode.makePosition(0.5, y: 0.36); self.dustEmitter.particlePositionRange.dx = POINT_SIZE.width; // Initial normal properties for each object. self.initObjects(); // self.initClosures(); // Add all sprites the the scene. self.addChild(self.dustEmitter); self.addChild(self.monkSprite); for symbol in self.symbolSprites { self.addChild(symbol); } self.addChild(self.backgroundSprite); self.addChild(self.playButton); self.addChild(self.optionsButton); self.addChild(self.aboutButton); self.addChild(self.standardModeButton); self.addChild(self.hardcoreModeButton); for tile in self.tiles { self.addChild(tile); } } func initObjects(){ // Monk Sprite self.monkSprite.anchorPoint = CGPoint(x: 0.5, y: 0.5); self.monkSprite.setPosition(x: 0.5, y: 0.63); self.monkSprite.runAction(SKAction.repeatActionForever(self.floatingAction)); // Symbols self.symbolSprites[0].setPosition(x: 0.6, y: 0.8); self.symbolSprites[1].setPosition(x: 0.57, y: 0.92); self.symbolSprites[2].setPosition(x: 0.5, y: 0.97); self.symbolSprites[3].setPosition(x: 0.43, y: 0.92); self.symbolSprites[4].setPosition(x: 0.40, y: 0.8); let symbolAction: SKAction = SKAction.sequence([SKAction.waitForDuration(2.0, withRange: 4.0), SKAction.group([SKAction.fadeInWithDuration(2.0), SKAction.repeatActionForever(self.floatingAction)])]); for symbol in self.symbolSprites { symbol.alpha = 0.0; symbol.runAction(symbolAction); } // Background Sprite self.backgroundSprite.anchorPoint = CGPoint(x: 0.0, y: 0.0); self.backgroundSprite.position = CGPoint(x: 0, y: 0); // Play Button self.playButton.setPosition(x: 0.5, y: 0.40); // Options Button self.optionsButton.setPosition(x: 0.2, y: 0.39); self.optionsButton.label.fontSize = 26; self.optionsButton.label.position = CGPoint(x: 0, y: -7); // About Button self.aboutButton.setPosition(x: 0.8, y: 0.39); // Mode buttons self.standardModeButton.setPosition(x: 0.5, y: 0.24); self.standardModeButton.setFrame(1); self.standardModeButton.label.fontColor = self.standardModeButton.hoverFontColor; self.hardcoreModeButton.setPosition(x: 0.5, y: 0.09); // Tiles //self.tileTest.setPosition(x: 0.05, y: 0.26); // initialize for index in 1...16 { if(index <= 8){ self.tiles.append(TileSprite(type: Tile.TYPE(rawValue: Int(arc4random_uniform(UInt32(Tile.TYPE.allValues.count)-3)))!, isFlipped: false)); }else{ self.tiles.append(TileSprite(type: Tile.TYPE.BOMB, isFlipped: true)); } } // position for var i = 0; i < self.tiles.count; i++ { var mult = i; var x: CGFloat = 0.0; var y: CGFloat = 0.24; if(i >= 8){ y = 0.09; mult = (i - 8); } if(i < 4){ x = 0.1 * CGFloat(mult) + 0.05; } else if(i < 8){ x = 0.1 * CGFloat(mult) + 0.25; } else if(i < 12){ x = 0.1 * CGFloat(mult) + 0.05; } else if(i < 16){ x = 0.1 * CGFloat(mult) + 0.25; } self.tiles[i].setPosition(x: x, y: y); if(i >= 8){ self.tiles[i].alpha = 0.5; } } } // Initialize closure functions. private func initClosures(){ // COMMON CLOSURES self.pressClosure = ({(selfNode: SKNode)->() in if(selfNode is ButtonSprite){ let button: ButtonSprite = selfNode as! ButtonSprite; button.setFrame(1); button.label.fontColor = button.hoverFontColor; } }); self.releaseClosure = ({(selfNode: SKNode)->() in if(selfNode is ButtonSprite){ let button: ButtonSprite = selfNode as! ButtonSprite; button.setFrame(0); button.label.fontColor = button.fontColor; } }); // Actions var standardActions: [SKAction] = []; for var i = 4; i < 8; i++ { let delayAct = SKAction.waitForDuration(0.05); let flipAct1 = SKAction.runBlock(self.tiles[7-i].flip); let flipAct2 = SKAction.runBlock(self.tiles[i].flip); standardActions.append(SKAction.group([flipAct1,flipAct2])); standardActions.append(delayAct); } var harcoreActions: [SKAction] = []; for var i = 12; i < 16; i++ { let delayAct = SKAction.waitForDuration(0.05); let flipAct1 = SKAction.runBlock(self.tiles[23-i].flip); let flipAct2 = SKAction.runBlock(self.tiles[i].flip); harcoreActions.append(SKAction.group([flipAct1,flipAct2])); harcoreActions.append(delayAct); } let modeSwitchComplete:()->() = {()->() in self.isModeSwitching = false; if(Settings.mode == 1){ for i in 0...7 { self.tiles[i].setType(Tile.TYPE(rawValue: Int(arc4random_uniform(UInt32(Tile.TYPE.allValues.count)-3)))!); } }else{ for i in 8...15 { self.tiles[i].setType(Tile.TYPE.BOMB); } } }; let standardFlipDownAction = SKAction.sequence(standardActions.reverse()); let standardFlipUpAction = SKAction.sequence(standardActions); let hardcoreFlipDownAction = SKAction.sequence(harcoreActions.reverse()); let hardcoreFlipUpAction = SKAction.sequence(harcoreActions); // MODE SELECTION CLOSURES let standardClick:(SKNode)->() = {(selfNode: SKNode)->() in if(Settings.mode == 1 && self.isModeSwitching == false){ Settings.mode = 0; self.isModeSwitching = true; self.standardModeButton.setFrame(1); self.standardModeButton.label.fontColor = self.standardModeButton.hoverFontColor; self.hardcoreModeButton.setFrame(0); self.hardcoreModeButton.label.fontColor = self.hardcoreModeButton.fontColor; for i in 0...15 { if(i < 8){ self.tiles[i].alpha = 1.0; } else{ self.tiles[i].alpha = 0.5; } } self.runAction(SKAction.group([standardFlipUpAction,hardcoreFlipDownAction])); self.runAction(SKAction.waitForDuration(0.8), completion: modeSwitchComplete); } }; let hardcoreClick:(SKNode)->() = {(selfNode: SKNode)->() in if(Settings.mode == 0 && self.isModeSwitching == false){ Settings.mode = 1; self.isModeSwitching = true; self.standardModeButton.setFrame(0); self.standardModeButton.label.fontColor = self.standardModeButton.fontColor; self.hardcoreModeButton.setFrame(1); self.hardcoreModeButton.label.fontColor = self.hardcoreModeButton.hoverFontColor; for i in 0...15 { if(i < 8){ self.tiles[i].alpha = 0.5; } else{ self.tiles[i].alpha = 1.0; } } self.runAction(SKAction.group([hardcoreFlipUpAction,standardFlipDownAction])); self.runAction(SKAction.waitForDuration(0.8), completion: modeSwitchComplete); } }; // Add closures to objets self.playButton.onPress(self.pressClosure); self.playButton.onRelease(self.releaseClosure); self.playButton.onClick({(selfNode: SKNode)->() in // Recache the view controller elements so we don't have to handle the main // menu stuff anymore. VC_CACHE = [GameVC(),GameOverVC()]; NAV_CONTROLLER.rippleIn(VC_CACHE[0]); }); self.optionsButton.onPress(self.pressClosure); self.optionsButton.onRelease(self.releaseClosure); self.aboutButton.onPress(self.pressClosure); self.aboutButton.onRelease(self.releaseClosure); self.aboutButton.onClick({(selfNode: SKNode)->() in NAV_CONTROLLER.pushWithFade(VC_CACHE[1], direction: kCATransitionFromLeft); }); // Mode buttons self.standardModeButton.onClick(standardClick); self.hardcoreModeButton.onClick(hardcoreClick); } } // ============================================================*/ let myScene: SKScene = MyScene(); override init(){ super.init(); //super.showDebug(); self.presentScene(self.myScene); } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
664a8bda91c8d153a9265462df2a8725
42.94702
211
0.523508
4.587625
false
false
false
false
nathawes/swift
test/IRGen/prespecialized-metadata/struct-fileprivate-inmodule-1argument-1distinct_use.swift
2
2382
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main5Value[[UNIQUE_ID_1:[0-9A-Z_]+]]VySiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sB[[INT]]_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5Value33_BD97D79156BC586FAA2AE8FB32F3D812LLVySiGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5Value[[UNIQUE_ID_1:[0-9A-Z_]+]]VMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] fileprivate struct Value<First> { let first: First } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5Value[[UNIQUE_ID_1]]VySiGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: } func doit() { consume( Value(first: 13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]VMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE]], i8* undef, i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main5Value[[UNIQUE_ID_1]]VMn{{.+}} to %swift.type_descriptor*)) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
b412ffeb03ba07bc84ba421f04a18762
47.612245
347
0.620067
2.981227
false
false
false
false
crazypoo/PTools
PooToolsSource/SearchBar/PTSearchBar.swift
1
3964
// // PTSearchBar.swift // PooTools_Example // // Created by ken lam on 2021/10/27. // Copyright © 2021 crazypoo. All rights reserved. // import UIKit @objcMembers public class PTSearchBar: UISearchBar { public var searchPlaceholder : String? = "请输入文字" public var searchPlaceholderFont : UIFont? = .systemFont(ofSize: 16) public var searchBarTextFieldBorderColor : UIColor? = UIColor.random public var searchBarImage : UIImage? = UIColor.clear.createImageWithColor() public var cursorColor : UIColor? = .lightGray public var searchPlaceholderColor : UIColor? = UIColor.random public var searchTextColor : UIColor? = UIColor.random public var searchBarOutViewColor : UIColor? = UIColor.random public var searchBarTextFieldCornerRadius : NSDecimalNumber? = 5 public var searchBarTextFieldBorderWidth : NSDecimalNumber? = 0.5 public var searchTextFieldBackgroundColor : UIColor? = UIColor.random public override func layoutSubviews() { super.layoutSubviews() if #available(iOS 13.0, *) { searchTextField.backgroundColor = searchTextFieldBackgroundColor! searchTextField.tintColor = cursorColor! searchTextField.textColor = searchTextColor! searchTextField.font = searchPlaceholderFont! searchTextField.attributedPlaceholder = NSAttributedString(string: searchPlaceholder!, attributes: [NSAttributedString.Key.font:searchPlaceholderFont!,NSAttributedString.Key.foregroundColor:searchPlaceholderColor!]) backgroundImage = searchBarOutViewColor!.createImageWithColor() setImage(searchBarImage!, for: .search, state: .normal) searchTextField.viewCorner(radius: (searchBarTextFieldCornerRadius as! CGFloat), borderWidth: (searchBarTextFieldBorderWidth as! CGFloat), borderColor: searchBarTextFieldBorderColor!) } else { var searchField : UITextField? let subviewArr = self.subviews for i in 0..<subviewArr.count { let viewSub = subviewArr[i] let arrSub = viewSub.subviews for j in 0..<arrSub.count { let tempID = arrSub[j] if tempID is UITextField { searchField = (tempID as! UITextField) } } } if searchField != nil { searchField?.placeholder = searchPlaceholder! searchField?.borderStyle = .roundedRect searchField?.backgroundColor = searchTextFieldBackgroundColor! searchField?.attributedPlaceholder = NSAttributedString(string: searchPlaceholder!, attributes: [NSAttributedString.Key.font:searchPlaceholderFont!,NSAttributedString.Key.foregroundColor:searchPlaceholderColor!]) searchField?.textColor = searchTextColor! searchField?.font = searchPlaceholderFont! searchField?.viewCorner(radius: (searchBarTextFieldCornerRadius as! CGFloat), borderWidth: (searchBarTextFieldBorderWidth as! CGFloat), borderColor: searchBarTextFieldBorderColor!) if searchBarImage == UIColor.clear.createImageWithColor() { searchField?.leftView = nil } else { let view = UIImageView(image: searchBarImage!) view.frame = CGRect.init(x: 0, y: 0, width: 16, height: 16) searchField?.leftView = view } (self.subviews[0].subviews[1] as! UITextField).tintColor = cursorColor! let outView = UIView.init(frame: self.bounds) outView.backgroundColor = searchBarOutViewColor! insertSubview(outView, at: 1) } } } }
mit
0fe5e0797cfec850f2f2cbda018ba905
41.967391
228
0.630154
5.679598
false
false
false
false
zxpLearnios/MyProject
test_projectDemo1/NetWorkRequest/MySystemRequest.swift
1
15663
// // MySystemRequest.swift // test_projectDemo1 // // Created by Jingnan Zhang on 16/8/15. // Copyright © 2016年 Jingnan Zhang. All rights reserved. /* 1. 当operation有多个任务的时候会自动分配多个线程并发执行, 如果只有一个任务,会自动在主线程同步执行 2. iOS开发之网络错误分层处理,参考http://blog.csdn.net/moxi_wang/article/details/52638752 3. 使用URLSession的对象,调用其对象方法使用URLRequest来进行请求、上传、下载 4. URLSession的设置: 4.1 默认会话(Default Sessions)使用了持久的磁盘缓存,并且将证书存入用户的钥匙串中。 4.2 临时会话(Ephemeral Session)没有向磁盘中存入任何数据,与该会话相关的证书、缓存等都会存在RAM中。因此当你的App临时会话无效时,证书以及缓存等数据就会被清除掉。 4.3 后台会话(Background sessions)除了使用一个单独的线程来处理会话之外,与默认会话类似。不过要使用后台会话要有一些限制条件,比如会话必须提供事件交付的代理方法、只有HTTP和HTTPS协议支持后台会话、总是伴随着重定向。 【仅仅在上传文件时才支持后台会话,当你上传二进制对象或者数据流时是不支持后台会话的。】 当App进入后台时,后台传输就会被初始化。(需要注意的是iOS8和OS X 10.10之前的版本中后台会话是不支持数据任务(data task)的)。 */ /** 在使用iOS的URL加载系统时,手机端和服务器端端连接可能会出现各种各样的错误,大致可以分为3种: 1、操作系统错误:数据包没有到达指定的目标导致。这类错误iOS中用NSError对象包装起来了,这类错误可以用Apple 提供的Reachability来检测到。可能导致操作系统错误的原因: 1.1 没有网络:如果设备没有数据网络连接,那么连接很快会被 拒绝或者失败。 1.2 无法路由到目标主机,设备可能连接网络了,但是连接的目标可能处于隔离的网络中或者掉线状态。 1.3 没有应用监听目标端口,客户端把数据发送到目的主机指定的端口号,如果服务器没有监听这个端口号(TCP/UDP服务端需要监听指定的端口号)或者需要连接的任务太多,则请求会被拒绝。 1.4 主机域名无法解析,域名的解析并不一定成功的(笔者公司某款APP第一次用的时候域名DNS解析就容易失败) 1.5 主机域名错误,域名写错了肯定找不到目标服务器的,我在正确域名tb.ataw.cn改为/tb.ataw1.cn则会报错: Error Domain=NSURLErrorDomain Code=-1003 “未能找到使用指定主机名的服务器。” UserInfo={NSUnderlyingError=0x174448040 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 “(null)” UserInfo={_kCFStreamErrorCodeKey=50331647, _kCFStreamErrorDomainKey=6147616992}}, NSErrorFailingURLStringKey=http://tb.ataw1.cn/app/UserLogin, NSErrorFailingURLKey=http://tb.ataw1.cn/app/UserLogin, _kCFStreamErrorDomainKey=6147616992, _kCFStreamErrorCodeKey=50331647, NSLocalizedDescription=未能找到使用指定主机名的服务器。} 2、HTTP错误:由HTTP请求、HTTP服务器或者应用服务器的问题造成,这种类型的错误通常通过HTTP响应头的状态码发送给客户端。HTTP错误的类型和原因: 2.1 信息性质的100级别,来自HTTP服务器的信息,表示请求的处理将会继续,但是有警告(笔者目前还没遇到过) 2.2 成功的200级别,表示请求成功了,但是返回的数据不同代表了不同的结果,例如204表示请求成功,但是不会向客户端返回负载。 2.3 重定向需要的300级别,表示客户端必须执行某个操作才能继续请求,因为需要的资源已经移动了,URL加载系统会自动处理重定向而无需通知代码,如果需要自定义处理 重定向,应该是用异步请求。 2.4 客户端错误的400级别,表示客户端发出了服务器无法处理的错误数据,需要注意你URL后面的路径、请求的参数格式、请求头的设置等,例如,我把正确路径http://tb.ataw.cn/app/UserLogin 写成http://tb.ataw.cn/app/UserLogin1,则会报错: { URL: http://tb.ataw.cn/app/UserLogin1 } { status code: 404, headers { Server=Microsoft-IIS/7.5; Content-Type=text/html; charset=utf-8; X-Powered-By=ASP.NET; Date=Fri, 23 Sep 2016 06:41:27 GMT; Content-Length=3431; Cache-Control=private; X-AspNet-Version=4.0.30319; } } 2.5 下游错误的500级别,表示服务器与下游服务器之间出现了错误,客户段就会收到500级别的错误,这时候通常都是后台开发的事情了,移动端告知他们修改。 3、应用错误:应用产生的错误(这一层的错误是我们开发中必须打交道的,客户端可以根据服务端返回负载中的状态码来进行业务逻辑处理),这些错误是运行在服务层之上的业务逻辑和应用造成的,这一层中的状态码是可以自定义的,所以需要和后台人员沟通好以便不同情况好处理业务逻辑。常见,例如,服务端的代码异常(笔者公司这种问题还蛮多的),这种错误一般服务端人员会给返回给客户端的负载状态码子段赋值500,例如,当我们登录成功时,后台返回的负载中状态码为200,如果登陆账号密码错误,则后台人员会返回一个不同的状态码。注意:这一层的状态码后台人员是可以任意定义的,所以开发中一定要沟通好哪个状态码对应什么状态。 */ /** 计算机网络中五层协议分别是(从下向上): 1) 物理层 2)数据链路层 3)网络层 4)传输层 5)应用层 其功能分别是: 1)物理层主要负责在物理线路上传输原始的二进制数据; 2)数据链路层主要负责在通信的实体间建立数据链路连接; 3)网络层主要负责创建逻辑链路,以及实现数据包的分片和重组,实现拥塞控制、网络互连等功能; 4)传输曾负责向用户提供端到端的通信服务,实现流量控制以及差错控制; 5)应用层为应用程序提供了网络服务。 一般来说,物理层和数据链路层是由计算机硬件(如网卡)实现的,网络层和传输层由操作系统软件实现,而应用层由应用程序或用户创建实现。 */ /** NSURLSession使用参考:http://www.cnblogs.com/mddblog/p/5215453.html // 2. 图片下载方式3 使用NSURLSession下载,需要设置其缓存模式为 临时会话\不缓存 // 设置会话的缓存模式 NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration ephemeralSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig]; NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:urlStr] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (error) { NSLog(@"合影下载错误: %@", error); return ; } // 文件的路径, 必须加后缀名字,不然的话,copyItemAtPath或removeItemAtPath都会失败 NSString *fullPath = [[Const documentPath] stringByAppendingString: @"img.png"]; NSError *fileCopyError; NSError *fileDeletError; if (location) { // 剪切文件 // 第一个参数:要剪切的文件在哪里 第二个参数:文件要要保存到哪里 // [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL URLWithString:fullPath] error: &er]; if ([[Const fileManager] fileExistsAtPath:fullPath]) { [[Const fileManager] removeItemAtPath:fullPath error:&fileDeletError]; } // 也会将Temp下面的文件移动 [[Const fileManager] copyItemAtPath:location.path toPath: fullPath error:&fileCopyError]; if (fileCopyError == nil) { NSLog(@"file save success"); _takePhotoView.hidden = YES; _uploadBtn.hidden = YES; _uploadView.hidden = NO; dispatch_async(dispatch_get_main_queue(), ^{ _imgV.image = [UIImage imageWithContentsOfFile:fullPath]; }); } else { NSLog(@"file save error: %@", fileCopyError); } } }]; [downloadTask resume]; */ import UIKit class MySystemRequest: NSObject { var request:URLRequest! // 由此来配置URLSession // private let sessionConfig = URLSessionConfiguration.default private let session = URLSession.init(configuration: URLSessionConfiguration.default) private var currentTask:URLSessionDataTask! private let operationQueue = OperationQueue.init() private let queueName = "operationQueue_system_01" // private struct completeAction{ // static let completeAction = Selector.init("result") // } typealias SucceedAction = (_ responseObject:AnyObject, _ code:String) -> () typealias FailedAction = (_ error:String, _ code:String) -> () typealias CompletedAction = (_ responseObject:AnyObject, _ code:String) -> () struct CompletedStruct { var successAction:SucceedAction? let failAction:FailedAction? } enum ErrorCode: Int { case /** 超时 */ kTimeOutErrorCode = -1001, /** 网络错误 */ kConnectError = -1, /** 返回的不是字典类型 */ kRequestErrorCodeNull = 32000, /** 返回的字典是空 */ kRequestErrorCodeException = 32100, /** 成功 */ kHTTP_200 = 200, /** 错误请求,请求参数错误 */ kHTTP_400 = 400, /** 授权、未登录 */ kHTTP_401 = 401, /** 未找到资源 */ kHTTP_404 = 404, /** 请求方法错误 */ kHTTP_405 = 405, /** 服务器内容错误 */ kHTTP_500 = 500 } enum RequestMethod:String { case get = "GET", post = "POST", delete = "DELETE", insert = "INSERT" } override init() { super.init() defaultSets() } private func defaultSets(){ // 1. request.timeoutInterval = 30 // 缓存模式 request.cachePolicy = .reloadIgnoringLocalCacheData // 设置http头部 request.allHTTPHeaderFields = ["":""] // 2. operationQueue.name = queueName // 最大并发数量 operationQueue.maxConcurrentOperationCount = 2 } /** 总的请求方法 - parameter path: 路径 - parameter params: 参数 - parameter completeHandler: 回调 */ func request(byMethod method:RequestMethod, withPath path:String, params:[String:AnyObject], completeHandler: CompletedAction) -> URLSessionTask? { // 1. 请求方式 switch method { case .get: request.httpMethod = RequestMethod.get.rawValue case .post: request.httpMethod = RequestMethod.post.rawValue case .delete: request.httpMethod = RequestMethod.delete.rawValue case .insert: request.httpMethod = RequestMethod.insert.rawValue } // 2. url地址 let url = URL.init(string: path) if url == nil { debugPrint("\(method)请求,url有误!") return nil } request.url = url // 3. task let task = session.dataTask(with: request, completionHandler: { (data, response, error) in // 5. 判断请求失败或成功 // let result = String.init(data: data!, encoding: NSUTF8StringEncoding) // 网络错误分层处理 // 5.1 系统错误的处理 if error != nil { } // 5.2 HTTP错误处理 let httpResponse = response as! HTTPURLResponse if httpResponse.statusCode == 300 { }else if httpResponse.statusCode == 400 { }else if httpResponse.statusCode == 500 { } // 5.3 if false { // 失败 // getFailResult(error!, code: "") }else{ // 成功 // let successObj = getSuccessResutlt(response!, code: "") } // 3.1 失败、成功都 回调 // completeHandler(responseObject: response!, code: "") }) currentTask = task // 4. 开始 // 创建NSOperation, 将操作加入其中,再将此NSOperation加入NSOperationQueue let operation = BlockOperation.init { task.resume() } operationQueue.addOperation(operation) operation.start() //B等A执行完才执行, 设置操作依赖 // operation.addDependency(operationA) // operation等operationA执行完才执行 // 4.1 开始 // operationQueue.addOperationWithBlock { // task.resume() // } return currentTask } // MARK: get请求 func get(withPath path:String, params:[String:AnyObject], completeHandler:CompletedAction) { // 调用总请求 request(byMethod: .get, withPath: path, params: params, completeHandler: completeHandler) } // MARK: 上传1. urlStr:请求地址 data:上传的二进制数据 func upload(_ urlStr:String, withData data:Data?) { let url = URL.init(string: urlStr)! let request = URLRequest.init(url: url) _ = session.uploadTask(with: request, from: data, completionHandler: { (data, response, error) in }) } // MARK: 上传2. urlStr:请求地址 filePath:上传的文件 func upload(_ urlStr:String, withFilePath file:String) { let url = URL.init(string: urlStr)! let request = URLRequest.init(url: url) let filePath = URL.init(fileURLWithPath: file) _ = session.uploadTask(with: request, fromFile: filePath, completionHandler: { data, response, error in }) } // MARK: 下载 func download(_ urlStr:String) { let path = URL.init(string: urlStr)! _ = session.downloadTask(with: path, completionHandler: { (url, response, error) in }) } // MARK: 获取请求结果 成功的 func getSuccessResutlt(_ responseObject:AnyObject, code:String) -> [String: AnyObject] { // 转换为字典 let dic = responseObject as! [String: AnyObject] return dic } // MARK: 获取请求结果 失败的 func getFailResult(_ error:String, code:String) { // 主要是对错误信息的处理 } // MARK: 取消所有请求 func cancleAllRequest() { operationQueue.cancelAllOperations() } // MARK: 取消当前请求 func cancleCurrentRequest() { currentTask.cancel() } // ------------------------- private ---------------- // }
mit
ff190af1616e50f75e2db3e2fd417461
29.909091
471
0.619291
3.405007
false
false
false
false
yimajo/Alamofire
Source/ServerTrustEvaluation.swift
2
37498
// // ServerTrustPolicy.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for managing the mapping of `ServerTrustEvaluating` values to given hosts. open class ServerTrustManager { /// Determines whether all hosts for this `ServerTrustManager` must be evaluated. `true` by default. public let allHostsMustBeEvaluated: Bool /// The dictionary of policies mapped to a particular host. public let evaluators: [String: ServerTrustEvaluating] /// Initializes the `ServerTrustManager` instance with the given evaluators. /// /// Since different servers and web services can have different leaf certificates, intermediate and even root /// certificates, it is important to have the flexibility to specify evaluation policies on a per host basis. This /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key /// pinning for host3 and disabling evaluation for host4. /// /// - Parameters: /// - allHostsMustBeEvaluated: The value determining whether all hosts for this instance must be evaluated. `true` /// by default. /// - evaluators: A dictionary of evaluators mapped to hosts. public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String: ServerTrustEvaluating]) { self.allHostsMustBeEvaluated = allHostsMustBeEvaluated self.evaluators = evaluators } #if !(os(Linux) || os(Windows)) /// Returns the `ServerTrustEvaluating` value for the given host, if one is set. /// /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override /// this method and implement more complex mapping implementations such as wildcards. /// /// - Parameter host: The host to use when searching for a matching policy. /// /// - Returns: The `ServerTrustEvaluating` value for the given host if found, `nil` otherwise. /// - Throws: `AFError.serverTrustEvaluationFailed` if `allHostsMustBeEvaluated` is `true` and no matching /// evaluators are found. open func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? { guard let evaluator = evaluators[host] else { if allHostsMustBeEvaluated { throw AFError.serverTrustEvaluationFailed(reason: .noRequiredEvaluator(host: host)) } return nil } return evaluator } #endif } /// A protocol describing the API used to evaluate server trusts. public protocol ServerTrustEvaluating { #if os(Linux) || os(Windows) // Implement this once Linux/Windows has API for evaluating server trusts. #else /// Evaluates the given `SecTrust` value for the given `host`. /// /// - Parameters: /// - trust: The `SecTrust` value to evaluate. /// - host: The host for which to evaluate the `SecTrust` value. /// /// - Returns: A `Bool` indicating whether the evaluator considers the `SecTrust` value valid for `host`. func evaluate(_ trust: SecTrust, forHost host: String) throws #endif } // MARK: - Server Trust Evaluators #if !(os(Linux) || os(Windows)) /// An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the /// host provided by the challenge. Applications are encouraged to always validate the host in production environments /// to guarantee the validity of the server's certificate chain. public final class DefaultTrustEvaluator: ServerTrustEvaluating { private let validateHost: Bool /// Creates a `DefaultTrustEvaluator`. /// /// - Parameter validateHost: Determines whether or not the evaluator should validate the host. `true` by default. public init(validateHost: Bool = true) { self.validateHost = validateHost } public func evaluate(_ trust: SecTrust, forHost host: String) throws { if validateHost { try trust.af.performValidation(forHost: host) } try trust.af.performDefaultValidation(forHost: host) } } /// An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate /// the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates. /// Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS /// 10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production /// environments to guarantee the validity of the server's certificate chain. public final class RevocationTrustEvaluator: ServerTrustEvaluating { /// Represents the options to be use when evaluating the status of a certificate. /// Only Revocation Policy Constants are valid, and can be found in [Apple's documentation](https://developer.apple.com/documentation/security/certificate_key_and_trust_services/policies/1563600-revocation_policy_constants). public struct Options: OptionSet { /// Perform revocation checking using the CRL (Certification Revocation List) method. public static let crl = Options(rawValue: kSecRevocationCRLMethod) /// Consult only locally cached replies; do not use network access. public static let networkAccessDisabled = Options(rawValue: kSecRevocationNetworkAccessDisabled) /// Perform revocation checking using OCSP (Online Certificate Status Protocol). public static let ocsp = Options(rawValue: kSecRevocationOCSPMethod) /// Prefer CRL revocation checking over OCSP; by default, OCSP is preferred. public static let preferCRL = Options(rawValue: kSecRevocationPreferCRL) /// Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a /// "best attempt" basis, where failure to reach the server is not considered fatal. public static let requirePositiveResponse = Options(rawValue: kSecRevocationRequirePositiveResponse) /// Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the /// certificate and the value of `preferCRL`. public static let any = Options(rawValue: kSecRevocationUseAnyAvailableMethod) /// The raw value of the option. public let rawValue: CFOptionFlags /// Creates an `Options` value with the given `CFOptionFlags`. /// /// - Parameter rawValue: The `CFOptionFlags` value to initialize with. public init(rawValue: CFOptionFlags) { self.rawValue = rawValue } } private let performDefaultValidation: Bool private let validateHost: Bool private let options: Options /// Creates a `RevocationTrustEvaluator` using the provided parameters. /// /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. /// /// - Parameters: /// - performDefaultValidation: Determines whether default validation should be performed in addition to /// evaluating the pinned certificates. `true` by default. /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to /// performing the default evaluation, even if `performDefaultValidation` is `false`. /// `true` by default. /// - options: The `Options` to use to check the revocation status of the certificate. `.any` by /// default. public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any) { self.performDefaultValidation = performDefaultValidation self.validateHost = validateHost self.options = options } public func evaluate(_ trust: SecTrust, forHost host: String) throws { if performDefaultValidation { try trust.af.performDefaultValidation(forHost: host) } if validateHost { try trust.af.performValidation(forHost: host) } if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { try trust.af.evaluate(afterApplying: SecPolicy.af.revocation(options: options)) } else { try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options)) } } } } #if swift(>=5.5) extension ServerTrustEvaluating where Self == RevocationTrustEvaluator { /// Provides a default `RevocationTrustEvaluator` instance. public static var revocationChecking: RevocationTrustEvaluator { RevocationTrustEvaluator() } /// Creates a `RevocationTrustEvaluator` using the provided parameters. /// /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. /// /// - Parameters: /// - performDefaultValidation: Determines whether default validation should be performed in addition to /// evaluating the pinned certificates. `true` by default. /// - validateHost: Determines whether or not the evaluator should validate the host, in addition /// to performing the default evaluation, even if `performDefaultValidation` is /// `false`. `true` by default. /// - options: The `Options` to use to check the revocation status of the certificate. `.any` /// by default. /// - Returns: The `RevocationTrustEvaluator`. public static func revocationChecking(performDefaultValidation: Bool = true, validateHost: Bool = true, options: RevocationTrustEvaluator.Options = .any) -> RevocationTrustEvaluator { RevocationTrustEvaluator(performDefaultValidation: performDefaultValidation, validateHost: validateHost, options: options) } } #endif /// Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned /// certificates match one of the server certificates. By validating both the certificate chain and host, certificate /// pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. /// Applications are encouraged to always validate the host and require a valid certificate chain in production /// environments. public final class PinnedCertificatesTrustEvaluator: ServerTrustEvaluating { private let certificates: [SecCertificate] private let acceptSelfSignedCertificates: Bool private let performDefaultValidation: Bool private let validateHost: Bool /// Creates a `PinnedCertificatesTrustEvaluator` from the provided parameters. /// /// - Parameters: /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der` /// certificates in `Bundle.main` by default. /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE /// FALSE IN PRODUCTION! /// - performDefaultValidation: Determines whether default validation should be performed in addition to /// evaluating the pinned certificates. `true` by default. /// - validateHost: Determines whether or not the evaluator should validate the host, in addition /// to performing the default evaluation, even if `performDefaultValidation` is /// `false`. `true` by default. public init(certificates: [SecCertificate] = Bundle.main.af.certificates, acceptSelfSignedCertificates: Bool = false, performDefaultValidation: Bool = true, validateHost: Bool = true) { self.certificates = certificates self.acceptSelfSignedCertificates = acceptSelfSignedCertificates self.performDefaultValidation = performDefaultValidation self.validateHost = validateHost } public func evaluate(_ trust: SecTrust, forHost host: String) throws { guard !certificates.isEmpty else { throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound) } if acceptSelfSignedCertificates { try trust.af.setAnchorCertificates(certificates) } if performDefaultValidation { try trust.af.performDefaultValidation(forHost: host) } if validateHost { try trust.af.performValidation(forHost: host) } let serverCertificatesData = Set(trust.af.certificateData) let pinnedCertificatesData = Set(certificates.af.data) let pinnedCertificatesInServerData = !serverCertificatesData.isDisjoint(with: pinnedCertificatesData) if !pinnedCertificatesInServerData { throw AFError.serverTrustEvaluationFailed(reason: .certificatePinningFailed(host: host, trust: trust, pinnedCertificates: certificates, serverCertificates: trust.af.certificates)) } } } #if swift(>=5.5) extension ServerTrustEvaluating where Self == PinnedCertificatesTrustEvaluator { /// Provides a default `PinnedCertificatesTrustEvaluator` instance. public static var pinnedCertificates: PinnedCertificatesTrustEvaluator { PinnedCertificatesTrustEvaluator() } /// Creates a `PinnedCertificatesTrustEvaluator` using the provided parameters. /// /// - Parameters: /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der` /// certificates in `Bundle.main` by default. /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE /// FALSE IN PRODUCTION! /// - performDefaultValidation: Determines whether default validation should be performed in addition to /// evaluating the pinned certificates. `true` by default. /// - validateHost: Determines whether or not the evaluator should validate the host, in addition /// to performing the default evaluation, even if `performDefaultValidation` is /// `false`. `true` by default. public static func pinnedCertificates(certificates: [SecCertificate] = Bundle.main.af.certificates, acceptSelfSignedCertificates: Bool = false, performDefaultValidation: Bool = true, validateHost: Bool = true) -> PinnedCertificatesTrustEvaluator { PinnedCertificatesTrustEvaluator(certificates: certificates, acceptSelfSignedCertificates: acceptSelfSignedCertificates, performDefaultValidation: performDefaultValidation, validateHost: validateHost) } } #endif /// Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned /// public keys match one of the server certificate public keys. By validating both the certificate chain and host, /// public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. /// Applications are encouraged to always validate the host and require a valid certificate chain in production /// environments. public final class PublicKeysTrustEvaluator: ServerTrustEvaluating { private let keys: [SecKey] private let performDefaultValidation: Bool private let validateHost: Bool /// Creates a `PublicKeysTrustEvaluator` from the provided parameters. /// /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. /// /// - Parameters: /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all /// certificates included in the main bundle. /// - performDefaultValidation: Determines whether default validation should be performed in addition to /// evaluating the pinned certificates. `true` by default. /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to /// performing the default evaluation, even if `performDefaultValidation` is `false`. /// `true` by default. public init(keys: [SecKey] = Bundle.main.af.publicKeys, performDefaultValidation: Bool = true, validateHost: Bool = true) { self.keys = keys self.performDefaultValidation = performDefaultValidation self.validateHost = validateHost } public func evaluate(_ trust: SecTrust, forHost host: String) throws { guard !keys.isEmpty else { throw AFError.serverTrustEvaluationFailed(reason: .noPublicKeysFound) } if performDefaultValidation { try trust.af.performDefaultValidation(forHost: host) } if validateHost { try trust.af.performValidation(forHost: host) } let pinnedKeysInServerKeys: Bool = { for serverPublicKey in trust.af.publicKeys { for pinnedPublicKey in keys { if serverPublicKey == pinnedPublicKey { return true } } } return false }() if !pinnedKeysInServerKeys { throw AFError.serverTrustEvaluationFailed(reason: .publicKeyPinningFailed(host: host, trust: trust, pinnedKeys: keys, serverKeys: trust.af.publicKeys)) } } } #if swift(>=5.5) extension ServerTrustEvaluating where Self == PublicKeysTrustEvaluator { /// Provides a default `PublicKeysTrustEvaluator` instance. public static var publicKeys: PublicKeysTrustEvaluator { PublicKeysTrustEvaluator() } /// Creates a `PublicKeysTrustEvaluator` from the provided parameters. /// /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. /// /// - Parameters: /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all /// certificates included in the main bundle. /// - performDefaultValidation: Determines whether default validation should be performed in addition to /// evaluating the pinned certificates. `true` by default. /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to /// performing the default evaluation, even if `performDefaultValidation` is `false`. /// `true` by default. public static func publicKeys(keys: [SecKey] = Bundle.main.af.publicKeys, performDefaultValidation: Bool = true, validateHost: Bool = true) -> PublicKeysTrustEvaluator { PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: performDefaultValidation, validateHost: validateHost) } } #endif /// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the /// evaluators consider it valid. public final class CompositeTrustEvaluator: ServerTrustEvaluating { private let evaluators: [ServerTrustEvaluating] /// Creates a `CompositeTrustEvaluator` from the provided evaluators. /// /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. public init(evaluators: [ServerTrustEvaluating]) { self.evaluators = evaluators } public func evaluate(_ trust: SecTrust, forHost host: String) throws { try evaluators.evaluate(trust, forHost: host) } } #if swift(>=5.5) extension ServerTrustEvaluating where Self == CompositeTrustEvaluator { /// Creates a `CompositeTrustEvaluator` from the provided evaluators. /// /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. public static func composite(evaluators: [ServerTrustEvaluating]) -> CompositeTrustEvaluator { CompositeTrustEvaluator(evaluators: evaluators) } } #endif /// Disables all evaluation which in turn will always consider any server trust as valid. /// /// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test /// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html). /// /// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** @available(*, deprecated, renamed: "DisabledTrustEvaluator", message: "DisabledEvaluator has been renamed DisabledTrustEvaluator.") public typealias DisabledEvaluator = DisabledTrustEvaluator /// Disables all evaluation which in turn will always consider any server trust as valid. /// /// /// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test /// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html). /// /// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** public final class DisabledTrustEvaluator: ServerTrustEvaluating { /// Creates an instance. public init() {} public func evaluate(_ trust: SecTrust, forHost host: String) throws {} } // MARK: - Extensions extension Array where Element == ServerTrustEvaluating { #if os(Linux) || os(Windows) // Add this same convenience method for Linux/Windows. #else /// Evaluates the given `SecTrust` value for the given `host`. /// /// - Parameters: /// - trust: The `SecTrust` value to evaluate. /// - host: The host for which to evaluate the `SecTrust` value. /// /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`. public func evaluate(_ trust: SecTrust, forHost host: String) throws { for evaluator in self { try evaluator.evaluate(trust, forHost: host) } } #endif } extension Bundle: AlamofireExtended {} extension AlamofireExtension where ExtendedType: Bundle { /// Returns all valid `cer`, `crt`, and `der` certificates in the bundle. public var certificates: [SecCertificate] { paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in guard let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil } return certificate } } /// Returns all public keys for the valid certificates in the bundle. public var publicKeys: [SecKey] { certificates.af.publicKeys } /// Returns all pathnames for the resources identified by the provided file extensions. /// /// - Parameter types: The filename extensions locate. /// /// - Returns: All pathnames for the given filename extensions. public func paths(forResourcesOfTypes types: [String]) -> [String] { Array(Set(types.flatMap { type.paths(forResourcesOfType: $0, inDirectory: nil) })) } } extension SecTrust: AlamofireExtended {} extension AlamofireExtension where ExtendedType == SecTrust { /// Evaluates `self` after applying the `SecPolicy` value provided. /// /// - Parameter policy: The `SecPolicy` to apply to `self` before evaluation. /// /// - Throws: Any `Error` from applying the `SecPolicy` or from evaluation. @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) public func evaluate(afterApplying policy: SecPolicy) throws { try apply(policy: policy).af.evaluate() } /// Attempts to validate `self` using the `SecPolicy` provided and transforming any error produced using the closure passed. /// /// - Parameters: /// - policy: The `SecPolicy` used to evaluate `self`. /// - errorProducer: The closure used transform the failed `OSStatus` and `SecTrustResultType`. /// - Throws: Any `Error` from applying the `policy`, or the result of `errorProducer` if validation fails. @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(afterApplying:)") @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(afterApplying:)") public func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws { try apply(policy: policy).af.validate(errorProducer: errorProducer) } /// Applies a `SecPolicy` to `self`, throwing if it fails. /// /// - Parameter policy: The `SecPolicy`. /// /// - Returns: `self`, with the policy applied. /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.policyApplicationFailed` reason. public func apply(policy: SecPolicy) throws -> SecTrust { let status = SecTrustSetPolicies(type, policy) guard status.af.isSuccess else { throw AFError.serverTrustEvaluationFailed(reason: .policyApplicationFailed(trust: type, policy: policy, status: status)) } return type } /// Evaluate `self`, throwing an `Error` if evaluation fails. /// /// - Throws: `AFError.serverTrustEvaluationFailed` with reason `.trustValidationFailed` and associated error from /// the underlying evaluation. @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) public func evaluate() throws { var error: CFError? let evaluationSucceeded = SecTrustEvaluateWithError(type, &error) if !evaluationSucceeded { throw AFError.serverTrustEvaluationFailed(reason: .trustEvaluationFailed(error: error)) } } /// Validate `self`, passing any failure values through `errorProducer`. /// /// - Parameter errorProducer: The closure used to transform the failed `OSStatus` and `SecTrustResultType` into an /// `Error`. /// - Throws: The `Error` produced by the `errorProducer` closure. @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate()") @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate()") @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate()") @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate()") public func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws { var result = SecTrustResultType.invalid let status = SecTrustEvaluate(type, &result) guard status.af.isSuccess && result.af.isSuccess else { throw errorProducer(status, result) } } /// Sets a custom certificate chain on `self`, allowing full validation of a self-signed certificate and its chain. /// /// - Parameter certificates: The `SecCertificate`s to add to the chain. /// - Throws: Any error produced when applying the new certificate chain. public func setAnchorCertificates(_ certificates: [SecCertificate]) throws { // Add additional anchor certificates. let status = SecTrustSetAnchorCertificates(type, certificates as CFArray) guard status.af.isSuccess else { throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: status, certificates: certificates)) } // Trust only the set anchor certs. let onlyStatus = SecTrustSetAnchorCertificatesOnly(type, true) guard onlyStatus.af.isSuccess else { throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: onlyStatus, certificates: certificates)) } } /// The public keys contained in `self`. public var publicKeys: [SecKey] { certificates.af.publicKeys } #if swift(>=5.5.1) // Xcode 13.1 / 2021 SDKs. /// The `SecCertificate`s contained in `self`. public var certificates: [SecCertificate] { if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) { return (SecTrustCopyCertificateChain(type) as? [SecCertificate]) ?? [] } else { return (0..<SecTrustGetCertificateCount(type)).compactMap { index in SecTrustGetCertificateAtIndex(type, index) } } } #else /// The `SecCertificate`s contained in `self`. public var certificates: [SecCertificate] { (0..<SecTrustGetCertificateCount(type)).compactMap { index in SecTrustGetCertificateAtIndex(type, index) } } #endif /// The `Data` values for all certificates contained in `self`. public var certificateData: [Data] { certificates.af.data } /// Validates `self` after applying `SecPolicy.af.default`. This evaluation does not validate the hostname. /// /// - Parameter host: The hostname, used only in the error output if validation fails. /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason. public func performDefaultValidation(forHost host: String) throws { if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { try evaluate(afterApplying: SecPolicy.af.default) } else { try validate(policy: SecPolicy.af.default) { status, result in AFError.serverTrustEvaluationFailed(reason: .defaultEvaluationFailed(output: .init(host, type, status, result))) } } } /// Validates `self` after applying `SecPolicy.af.hostname(host)`, which performs the default validation as well as /// hostname validation. /// /// - Parameter host: The hostname to use in the validation. /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason. public func performValidation(forHost host: String) throws { if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { try evaluate(afterApplying: SecPolicy.af.hostname(host)) } else { try validate(policy: SecPolicy.af.hostname(host)) { status, result in AFError.serverTrustEvaluationFailed(reason: .hostValidationFailed(output: .init(host, type, status, result))) } } } } extension SecPolicy: AlamofireExtended {} extension AlamofireExtension where ExtendedType == SecPolicy { /// Creates a `SecPolicy` instance which will validate server certificates but not require a host name match. public static let `default` = SecPolicyCreateSSL(true, nil) /// Creates a `SecPolicy` instance which will validate server certificates and much match the provided hostname. /// /// - Parameter hostname: The hostname to validate against. /// /// - Returns: The `SecPolicy`. public static func hostname(_ hostname: String) -> SecPolicy { SecPolicyCreateSSL(true, hostname as CFString) } /// Creates a `SecPolicy` which checks the revocation of certificates. /// /// - Parameter options: The `RevocationTrustEvaluator.Options` for evaluation. /// /// - Returns: The `SecPolicy`. /// - Throws: An `AFError.serverTrustEvaluationFailed` error with reason `.revocationPolicyCreationFailed` /// if the policy cannot be created. public static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy { guard let policy = SecPolicyCreateRevocation(options.rawValue) else { throw AFError.serverTrustEvaluationFailed(reason: .revocationPolicyCreationFailed) } return policy } } extension Array: AlamofireExtended {} extension AlamofireExtension where ExtendedType == [SecCertificate] { /// All `Data` values for the contained `SecCertificate`s. public var data: [Data] { type.map { SecCertificateCopyData($0) as Data } } /// All public `SecKey` values for the contained `SecCertificate`s. public var publicKeys: [SecKey] { type.compactMap(\.af.publicKey) } } extension SecCertificate: AlamofireExtended {} extension AlamofireExtension where ExtendedType == SecCertificate { /// The public key for `self`, if it can be extracted. /// /// - Note: On 2020 OSes and newer, only RSA and ECDSA keys are supported. /// public var publicKey: SecKey? { let policy = SecPolicyCreateBasicX509() var trust: SecTrust? let trustCreationStatus = SecTrustCreateWithCertificates(type, policy, &trust) guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil } if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) { return SecTrustCopyKey(createdTrust) } else { return SecTrustCopyPublicKey(createdTrust) } } } extension OSStatus: AlamofireExtended {} extension AlamofireExtension where ExtendedType == OSStatus { /// Returns whether `self` is `errSecSuccess`. public var isSuccess: Bool { type == errSecSuccess } } extension SecTrustResultType: AlamofireExtended {} extension AlamofireExtension where ExtendedType == SecTrustResultType { /// Returns whether `self is `.unspecified` or `.proceed`. public var isSuccess: Bool { type == .unspecified || type == .proceed } } #endif
mit
7bab76c5423c0914d94c3287103fbcc4
49.741543
228
0.651475
5.401613
false
false
false
false
pisces/IrregularCollectionUIKit
Example/IrregularCollectionUIKit/DemoViewController.swift
1
5508
// // DemoViewController.swift // IrregularCollectionUIKit // // Created by pisces on 9/19/16. // Copyright © 2016 Steve Kim. All rights reserved. // import UIKit class DemoViewController: IrregularCollectionViewController { let sizeArray = [400, 300, 200] let imageNames = ["201499971412727010.jpg", "99763_62164_3159.jpg", "7.jpg", "20160408110556_11.jpg", "201606100719471127_1.jpg", "article_20150904-1.jpg", "img_20150502111148_a5d91d53.jpg", "R1280x0.jpg"] var contents: [SampleContent] = [] { didSet { collectionView.reloadData() } } // MARK: - Overridden: IrregularCollectionViewController override func viewDidLoad() { super.viewDidLoad() title = "Demo" collectionViewLayout.columnSpacing = 1 collectionViewLayout.numberOfColumns = 3 collectionViewLayout.sectionInset = UIEdgeInsetsMake(1, 1, 1, 1) collectionView.register(SampleViewCell.self, forCellWithReuseIdentifier: "SampleViewCell") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if isFirstViewAppearence { contents = createRandomSizeItems(1000) } } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return contents.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCell(withReuseIdentifier: "SampleViewCell", for: indexPath) } override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { (cell as? SampleViewCell)?.content = contents[indexPath.item] } override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, originalItemSizeAt indexPath: IndexPath) -> CGSize { let content = contents[indexPath.item] return CGSize(width: CGFloat(content.width), height: CGFloat(content.height)) } // MARK: - Private methods private func createRandomSizeItems(_ count: Int) -> [SampleContent] { var source: Array<SampleContent> = [] for i in 0..<count { let indexOfHeight = Int(arc4random()%UInt32(sizeArray.count)) let indexOfWidth = Int(arc4random()%UInt32(sizeArray.count)) let content = SampleContent(width: sizeArray[indexOfWidth], height: sizeArray[indexOfHeight]) content.url = imageNames[i%imageNames.count] source.append(content) } return source } private func createStaticItems() -> [SampleContent] { return [ SampleContent(width: 300, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 200), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 200), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 200), SampleContent(width: 400, height: 300), SampleContent(width: 200, height: 300), SampleContent(width: 200, height: 300), SampleContent(width: 200, height: 300), SampleContent(width: 200, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 200), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 300), SampleContent(width: 400, height: 300) ] } } class SampleViewCell: UICollectionViewCell { private lazy var imageView: UIImageView = { let view = UIImageView() view.clipsToBounds = true view.contentMode = .scaleAspectFill view.translatesAutoresizingMaskIntoConstraints = false return view }() var content: SampleContent? { didSet { if let url = content?.url { imageView.image = UIImage(named: url) } } } override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(imageView) NSLayoutConstraint.activate([ imageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), imageView.topAnchor.constraint(equalTo: contentView.topAnchor), imageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)]) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
7e13be919466d49d28577f54a0919c3b
39.792593
209
0.642092
4.755613
false
false
false
false
Masteryyz/CSYMicroBlockSina
CSYMicroBlockSina/CSYMicroBlockSina/Classes/Module/Home/HomeTableViewCell/Buttom/CSYBottomView.swift
1
4394
// // CSYBottomView.swift // CSYMicroBlockSina // // Created by 姚彦兆 on 15/11/15. // Copyright © 2015年 姚彦兆. All rights reserved. // import UIKit import SnapKit class CSYBottomView: UIView { @objc func clickRetweetedButton(){ let nav = CSYDoRetweedController() retweetedBtn.getNavController()?.pushViewController(nav,animated: true) } override init(frame: CGRect) { super.init(frame: frame) setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //设置UI private func setUpUI(){ let topLine = cutLine() addSubview(topLine) topLine.snp_makeConstraints { (make) -> Void in make.top.equalTo(snp_top) make.width.equalTo(snp_width).offset(-10.0) make.centerX.equalTo(snp_centerX) make.height.equalTo(lineWidth) } //添加转发按钮 addSubview(retweetedBtn) //添加约束 retweetedBtn.snp_makeConstraints { (make) -> Void in make.top.equalTo(snp_top) make.left.equalTo(snp_left) make.height.equalTo(snp_height) } retweetedBtn.addTarget(self, action: "clickRetweetedButton", forControlEvents: .TouchUpInside) let cutLine1 = cutLine() addSubview(cutLine1) cutLine1.snp_makeConstraints { (make) -> Void in make.left.equalTo(retweetedBtn.snp_right) make.width.equalTo(lineWidth) make.centerY.equalTo(snp_centerY) make.height.equalTo(snp_height).multipliedBy(scale) } addSubview(composeBtn) composeBtn.snp_makeConstraints { (make) -> Void in make.top.equalTo(retweetedBtn.snp_top) make.left.equalTo(retweetedBtn.snp_right) make.height.equalTo(snp_height) make.width.equalTo(retweetedBtn.snp_width) } let cutLine2 = cutLine() addSubview(cutLine2) cutLine2.snp_makeConstraints { (make) -> Void in make.left.equalTo(composeBtn.snp_right) make.width.equalTo(lineWidth) make.centerY.equalTo(snp_centerY) make.height.equalTo(snp_height).multipliedBy(scale) } addSubview(likeBtn) likeBtn.snp_makeConstraints { (make) -> Void in make.left.equalTo(composeBtn.snp_right) make.top.equalTo(composeBtn) make.right.equalTo(snp_right) make.height.equalTo(snp_height) make.width.equalTo(composeBtn.snp_width) } let bottomLine = cutLine() addSubview(bottomLine) bottomLine.snp_makeConstraints { (make) -> Void in make.bottom.equalTo(snp_bottom) make.width.equalTo(snp_width).offset(-10.0) make.centerX.equalTo(snp_centerX) make.height.equalTo(lineWidth) } } //分割线 private func cutLine () -> UIView { let lineView = UIView() lineView.backgroundColor = UIColor.lightGrayColor() return lineView } //懒加载所有控件 lazy var retweetedBtn : UIButton = UIButton(title: "转发", titleColor: UIColor.lightGrayColor(), image: "timeline_icon_retweet", backImage: nil, fontSize: 12) lazy var composeBtn : UIButton = UIButton(title: "评论", titleColor: UIColor.lightGrayColor(), image: "timeline_icon_comment", backImage: nil, fontSize: 12) lazy var likeBtn : UIButton = UIButton(title: "赞", titleColor: UIColor.orangeColor(), image: "timeline_icon_like", backImage: nil, fontSize: 12) }
mit
2245a51efc45354b8ad260b07c14e865
24.591716
160
0.513295
5.02907
false
false
false
false
hadibadjian/GAlileo
reminders/Reminders/Sources/MainTableViewController.swift
1
1818
// Copyright © 2016 HB. All rights reserved. class MainTableViewController: UITableViewController { let menuTableViewCellId = "MenuTableViewCell" let addTableViewCellId = "AddReminderTableViewCell" let reminderViewControllerId = "ReminderViewController" var reminderStorage: AddReminderStorage = AddReminderStorage() override func tableView( tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } override func tableView( tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell? switch indexPath.row { case 0: cell = tableView.dequeueReusableCellWithIdentifier(menuTableViewCellId) if let cell = cell { cell.textLabel?.text = "John" cell.detailTextLabel?.text = "Doe" } case 1: cell = tableView.dequeueReusableCellWithIdentifier(addTableViewCellId) default: cell = nil } return cell! } override func tableView( tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { /* if indexPath.row == 1 { let viewController = storyboard?.instantiateViewControllerWithIdentifier("ReminderViewController") if let viewController = viewController as? ModalReminderViewController { viewController.delegate = self presentViewController(viewController, animated: true, completion: nil) } } */ tableView.deselectRowAtIndexPath(indexPath, animated: true) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let viewController = segue.destinationViewController as? ModalReminderViewController { viewController.delegate = reminderStorage } } } import UIKit
mit
91988bf539aa94666e5a75bf9a33cf6d
27.390625
106
0.70831
5.556575
false
false
false
false
ken0nek/swift
test/Reflection/Inputs/ObjectiveCTypes.swift
1
756
import Foundation public class OC : NSObject { public let nsObject: NSObject public let nsString: NSString public let cfString: CFString public let aBlock: @convention(block) () -> () public init(nsObject: NSObject, nsString: NSString, cfString: CFString, aBlock: @convention(block) () -> ()) { self.nsObject = nsObject self.nsString = nsString self.cfString = cfString self.aBlock = aBlock } } public class GenericOC<T> : NSObject { public let ocnss: GenericOC<NSString> public let occfs: GenericOC<CFString> public init(nss: GenericOC<NSString>, cfs: GenericOC<CFString>) { self.ocnss = nss self.occfs = cfs } } public class HasObjCClasses { let url = NSURL() let integer = NSInteger() }
apache-2.0
52f312301e06aaca8e0c0879773f135e
24.2
73
0.683862
3.837563
false
false
false
false
lcllkzdzq/json2model
json2model/json2model/ObjectNode.swift
1
664
// // ObjectNode.swift // json2model // // Created by lcl on 16/9/7. // Copyright © 2016年 Vulpes. All rights reserved. // import Foundation class ObjectNode: Node { var dic = Dictionary<String, AnyObject>() var type: NodeType = .ObjectNode var subnodes : Array<Node>? = Array<Node>() var parentNode: Node? init(dic: Dictionary<String, AnyObject>, parent : Node?) { self.dic = dic self.parentNode = parent for (_, value) in dic { subnodes!.append(NodeFactory.createNode(value, parent: self)) } } var originalData: AnyObject { get { return dic } } }
mit
900f385b4e6c0f023697355f3bd38093
19.6875
73
0.586989
3.820809
false
false
false
false
danydev/DORateLimit
DORateLimit/RateLimit.swift
1
9219
// // RateLimit.swift // RateLimitExample // // Created by Daniele Orrù on 28/06/15. // Copyright (c) 2015 Daniele Orru'. All rights reserved. // import Foundation class ThrottleInfo { let key: String let threshold: TimeInterval let trailing: Bool let closure: () -> () init(key: String, threshold: TimeInterval, trailing: Bool, closure: @escaping () -> ()) { self.key = key self.threshold = threshold self.trailing = trailing self.closure = closure } } class ThrottleExecutionInfo { let lastExecutionDate: Date let timer: Timer? let throttleInfo: ThrottleInfo init(lastExecutionDate: Date, timer: Timer? = nil, throttleInfo: ThrottleInfo) { self.lastExecutionDate = lastExecutionDate self.timer = timer self.throttleInfo = throttleInfo } } class DebounceInfo { let key: String let threshold: TimeInterval let atBegin: Bool let closure: () -> () init(key: String, threshold: TimeInterval, atBegin: Bool, closure: @escaping () -> ()) { self.key = key self.threshold = threshold self.atBegin = atBegin self.closure = closure } } class DebounceExecutionInfo { let timer: Timer? let debounceInfo: DebounceInfo init(timer: Timer? = nil, debounceInfo: DebounceInfo) { self.timer = timer self.debounceInfo = debounceInfo } } /** Provide debounce and throttle functionality. */ open class RateLimit { fileprivate static let queue = DispatchQueue(label: "org.orru.RateLimit", attributes: []) fileprivate static var throttleExecutionDictionary = [String : ThrottleExecutionInfo]() fileprivate static var debounceExecutionDictionary = [String : DebounceExecutionInfo]() /** Throttle call to a closure using a given threshold - parameter name: - parameter threshold: - parameter trailing: - parameter closure: */ public static func throttle(_ key: String, threshold: TimeInterval, trailing: Bool = false, closure: @escaping ()->()) { let now = Date() var canExecuteClosure = false if let rateLimitInfo = self.throttleInfoForKey(key) { let timeDifference = rateLimitInfo.lastExecutionDate.timeIntervalSince(now) if timeDifference < 0 && fabs(timeDifference) < threshold { if trailing && rateLimitInfo.timer == nil { let timer = Timer.scheduledTimer(timeInterval: threshold, target: self, selector: #selector(RateLimit.throttleTimerFired(_:)), userInfo: ["rateLimitInfo" : rateLimitInfo], repeats: false) let throttleInfo = ThrottleInfo(key: key, threshold: threshold, trailing: trailing, closure: closure) self.setThrottleInfoForKey(ThrottleExecutionInfo(lastExecutionDate: rateLimitInfo.lastExecutionDate, timer: timer, throttleInfo: throttleInfo), forKey: key) } } else { canExecuteClosure = true } } else { canExecuteClosure = true } if canExecuteClosure { let throttleInfo = ThrottleInfo(key: key, threshold: threshold, trailing: trailing, closure: closure) self.setThrottleInfoForKey(ThrottleExecutionInfo(lastExecutionDate: now, timer: nil, throttleInfo: throttleInfo), forKey: key) closure() } } @objc fileprivate static func throttleTimerFired(_ timer: Timer) { if let userInfo = timer.userInfo as? [String : AnyObject], let rateLimitInfo = userInfo["rateLimitInfo"] as? ThrottleExecutionInfo { self.throttle(rateLimitInfo.throttleInfo.key, threshold: rateLimitInfo.throttleInfo.threshold, trailing: rateLimitInfo.throttleInfo.trailing, closure: rateLimitInfo.throttleInfo.closure) } } /** Debounce call to a closure using a given threshold - parameter key: - parameter threshold: - parameter atBegin: - parameter closure: */ public static func debounce(_ key: String, threshold: TimeInterval, atBegin: Bool = true, closure: @escaping ()->()) { var canExecuteClosure = false if let rateLimitInfo = self.debounceInfoForKey(key) { if let timer = rateLimitInfo.timer, timer.isValid { timer.invalidate() let debounceInfo = DebounceInfo(key: key, threshold: threshold, atBegin: atBegin, closure: closure) let timer = Timer.scheduledTimer(timeInterval: threshold, target: self, selector: #selector(RateLimit.debounceTimerFired(_:)), userInfo: ["rateLimitInfo" : debounceInfo], repeats: false) self.setDebounceInfoForKey(DebounceExecutionInfo(timer: timer, debounceInfo: debounceInfo), forKey: key) } else { if (atBegin) { canExecuteClosure = true } else { let debounceInfo = DebounceInfo(key: key, threshold: threshold, atBegin: atBegin, closure: closure) let timer = Timer.scheduledTimer(timeInterval: threshold, target: self, selector: #selector(RateLimit.debounceTimerFired(_:)), userInfo: ["rateLimitInfo" : debounceInfo], repeats: false) self.setDebounceInfoForKey(DebounceExecutionInfo(timer: timer, debounceInfo: debounceInfo), forKey: key) } } } else { if (atBegin) { canExecuteClosure = true } else { let debounceInfo = DebounceInfo(key: key, threshold: threshold, atBegin: atBegin, closure: closure) let timer = Timer.scheduledTimer(timeInterval: threshold, target: self, selector: #selector(RateLimit.debounceTimerFired(_:)), userInfo: ["rateLimitInfo" : debounceInfo], repeats: false) self.setDebounceInfoForKey(DebounceExecutionInfo(timer: timer, debounceInfo: debounceInfo), forKey: key) } } if canExecuteClosure { let debounceInfo = DebounceInfo(key: key, threshold: threshold, atBegin: atBegin, closure: closure) let timer = Timer.scheduledTimer(timeInterval: threshold, target: self, selector: #selector(RateLimit.debounceTimerFired(_:)), userInfo: ["rateLimitInfo" : debounceInfo], repeats: false) self.setDebounceInfoForKey(DebounceExecutionInfo(timer: timer, debounceInfo: debounceInfo), forKey: key) closure() } } @objc fileprivate static func debounceTimerFired(_ timer: Timer) { if let userInfo = timer.userInfo as? [String : AnyObject], let debounceInfo = userInfo["rateLimitInfo"] as? DebounceInfo, !debounceInfo.atBegin { debounceInfo.closure() } } /** Reset rate limit information for both bouncing and throlling */ public static func resetAllRateLimit() { queue.sync { for key in self.throttleExecutionDictionary.keys { if let rateLimitInfo = self.throttleExecutionDictionary[key], let timer = rateLimitInfo.timer, timer.isValid { timer.invalidate() } self.throttleExecutionDictionary[key] = nil } for key in self.debounceExecutionDictionary.keys { if let rateLimitInfo = self.debounceExecutionDictionary[key], let timer = rateLimitInfo.timer, timer.isValid { timer.invalidate() } self.debounceExecutionDictionary[key] = nil } } } /** Reset rate limit information for both bouncing and throlling for a specific key */ public static func resetRateLimitForKey(_ key: String) { queue.sync { if let rateLimitInfo = self.throttleExecutionDictionary[key], let timer = rateLimitInfo.timer, timer.isValid { timer.invalidate() } self.throttleExecutionDictionary[key] = nil if let rateLimitInfo = self.debounceExecutionDictionary[key], let timer = rateLimitInfo.timer, timer.isValid { timer.invalidate() } self.debounceExecutionDictionary[key] = nil } } fileprivate static func throttleInfoForKey(_ key: String) -> ThrottleExecutionInfo? { var rateLimitInfo: ThrottleExecutionInfo? queue.sync { rateLimitInfo = self.throttleExecutionDictionary[key] } return rateLimitInfo } fileprivate static func setThrottleInfoForKey(_ rateLimitInfo: ThrottleExecutionInfo, forKey key: String) { queue.sync { self.throttleExecutionDictionary[key] = rateLimitInfo } } fileprivate static func debounceInfoForKey(_ key: String) -> DebounceExecutionInfo? { var rateLimitInfo: DebounceExecutionInfo? queue.sync { rateLimitInfo = self.debounceExecutionDictionary[key] } return rateLimitInfo } fileprivate static func setDebounceInfoForKey(_ rateLimitInfo: DebounceExecutionInfo, forKey key: String) { queue.sync { self.debounceExecutionDictionary[key] = rateLimitInfo } } }
mit
45ee3b43e575bc95aff714cd5ec9ae4d
38.225532
207
0.642439
4.81861
false
false
false
false
sendyhalim/iYomu
Yomu/Screens/MangaList/MangaRealm.swift
1
2056
// // MangaRealm.swift // Yomu // // Created by Sendy Halim on 5/30/17. // Copyright © 2017 Sendy Halim. All rights reserved. // import Foundation import RealmSwift /// Represents Manga object for `Realm` database class MangaRealm: Object { @objc dynamic var id: String = "" @objc dynamic var slug: String = "" @objc dynamic var title: String = "" @objc dynamic var author: String = "" @objc dynamic var imageEndpoint: String = "" @objc dynamic var releasedYear: Int = 0 @objc dynamic var commaSeparatedCategories: String = "" @objc dynamic var plot: String = "" @objc dynamic var position: Int = MangaPosition.undefined.rawValue override static func primaryKey() -> String? { return "id" } /// Convert the given `Manga` struct to `MangaRealm` object /// /// - parameter manga: `Manga` /// /// - returns: `MangaRealm` static func from(manga: Manga) -> MangaRealm { let mangaRealm = MangaRealm() mangaRealm.id = manga.id! mangaRealm.slug = manga.slug mangaRealm.title = manga.title mangaRealm.author = manga.author mangaRealm.imageEndpoint = manga.image.endpoint mangaRealm.releasedYear = manga.releasedYear ?? 0 mangaRealm.commaSeparatedCategories = manga.categories.joined(separator: ",") mangaRealm.position = manga.position mangaRealm.plot = manga.plot return mangaRealm } /// Convert the given `MangaRealm` object to `Manga` struct /// /// - parameter mangaRealm: `MangaRealm` /// /// - returns: `Manga` static func mangaFrom(mangaRealm: MangaRealm) -> Manga { let categories = mangaRealm .commaSeparatedCategories .split { $0 == "," } .map(String.init) return Manga( position: mangaRealm.position, id: mangaRealm.id, slug: mangaRealm.slug, title: mangaRealm.title, author: mangaRealm.author, image: ImageUrl(endpoint: mangaRealm.imageEndpoint), releasedYear: mangaRealm.releasedYear, plot: mangaRealm.plot, categories: categories ) } }
mit
19a70f9683c04bb442deb8a2abbe5094
26.77027
81
0.665693
3.663102
false
false
false
false
getsocial-im/getsocial-ios-sdk
example/GetSocialDemo/Views/Communities/Feed/FeedViewController.swift
1
7009
// // GenericPagingViewController.swift // GetSocialDemo // // Copyright © 2020 GetSocial BV. All rights reserved. // import UIKit import GetSocialSDK protocol FeedTableViewControllerDelegate { } class FeedViewController: UIViewController { var viewModel: FeedModel = FeedModel() var query: ActivitiesQuery? var loadingOlders: Bool = false var delegate: FeedTableViewControllerDelegate? var tableView: UITableView = UITableView() override func viewDidLoad() { super.viewDidLoad() self.tableView.backgroundColor = .white self.tableView.register(ActivityTableViewCell.self, forCellReuseIdentifier: "activitytableviewcell") self.tableView.allowsSelection = false self.title = "DemoFeed" self.viewModel.onInitialDataLoaded = { self.hideActivityIndicatorView() self.tableView.reloadData() } self.viewModel.onDidOlderLoad = { self.hideActivityIndicatorView() self.tableView.reloadData() self.loadingOlders = false } self.viewModel.reactionUpdated = { index in self.hideActivityIndicatorView() let indexToReload = IndexPath.init(row: index, section: 0) self.tableView.reloadRows(at: [indexToReload], with: .automatic) self.showAlert(withText: "Reactions updated") } self.viewModel.onError = { error in self.hideActivityIndicatorView() self.showAlert(withText: error.localizedDescription) } self.tableView.dataSource = self self.tableView.delegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.executeQuery() } override func viewWillLayoutSubviews() { layoutTableView() } private func executeQuery() { self.showActivityIndicatorView() self.viewModel.loadEntries(query: self.query ?? ActivitiesQuery.timeline()) } func scrollViewDidScroll(_ scrollView: UIScrollView) { let actualPosition = scrollView.contentOffset.y let contentHeight = scrollView.contentSize.height - scrollView.frame.size.height if actualPosition > 0 && self.viewModel.numberOfEntries() > 0 && actualPosition > contentHeight && !self.loadingOlders && self.viewModel.nextCursor.count != 0 { self.loadingOlders = true self.showActivityIndicatorView() self.viewModel.loadOlder() } } internal func layoutTableView() { tableView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.tableView) let top = tableView.topAnchor.constraint(equalTo: self.view.topAnchor) let left = tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor) let right = tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor) let bottom = tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor) NSLayoutConstraint.activate([left, top, right, bottom]) } } extension FeedViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 110 } } extension FeedViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.viewModel.numberOfEntries() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "activitytableviewcell") as? ActivityTableViewCell let item = self.viewModel.entry(at: indexPath.row) cell?.update(activity: item) cell?.delegate = self return cell ?? UITableViewCell() } } extension FeedViewController: ActivityTableViewCellDelegate { func onShowActions(_ ofActivity: String) { let actionSheet = UIAlertController.init(title: "Available actions", message: nil, preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction.init(title: "Reaction details", style: .default, handler: { _ in if let activity = self.viewModel.findActivity(ofActivity) { let description = "Known reactors: \(activity.reactions), my reactions: \(activity.myReactions), reactions count: \(activity.reactionsCount), bookmarks count: \(activity.bookmarksCount), is Bookmarked: \(activity.isBookmarked)" self.showAlert(withText: description) } })) actionSheet.addAction(UIAlertAction.init(title: "Comment details", style: .default, handler: { _ in if let activity = self.viewModel.findActivity(ofActivity) { let description = "Known commenters: \(activity.commenters), comments count: \(activity.commentsCount)" self.showAlert(withText: description) } })) actionSheet.addAction(UIAlertAction.init(title: "Add reaction", style: .default, handler: { _ in self.showReactionInput(title: "Add reaction") { reaction in self.showActivityIndicatorView() self.viewModel.addReaction(reaction, activityId: ofActivity) } })) actionSheet.addAction(UIAlertAction.init(title: "Set reaction", style: .default, handler: { _ in self.showReactionInput(title: "Set reaction") { reaction in self.showActivityIndicatorView() self.viewModel.setReaction(reaction, activityId: ofActivity) } })) actionSheet.addAction(UIAlertAction.init(title: "Remove reaction", style: .default, handler: { _ in self.showReactionInput(title: "Remove reaction") { reaction in self.showActivityIndicatorView() self.viewModel.removeReaction(reaction, activityId: ofActivity) } })) if let activity = self.viewModel.findActivity(ofActivity) { if !activity.isBookmarked { actionSheet.addAction(UIAlertAction.init(title: "Bookmark", style: .default, handler: { _ in self.showActivityIndicatorView() self.viewModel.bookmark(ofActivity) })) } else { actionSheet.addAction(UIAlertAction.init(title: "Remove Bookmark", style: .default, handler: { _ in self.showActivityIndicatorView() self.viewModel.removeBookmark(ofActivity) })) } } actionSheet.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil)) self.present(actionSheet, animated: true, completion: nil) } private func showReactionInput(title: String, then: @escaping (String) -> Void) { let alert = UISimpleAlertViewController(title: title, message: "Enter reaction", cancelButtonTitle: "Cancel", otherButtonTitles: ["Ok"]) alert?.addTextField(withPlaceholder: "like", defaultText: "like", isSecure: false) alert?.show(dismissHandler: { (selectedIndex, selectedTitle, didCancel) in if didCancel { return } let reaction = alert?.contentOfTextField(at: 0) then(reaction ?? "like") }) } }
apache-2.0
557ff633bd3bb177a41b18a1413e8e0b
38.370787
243
0.691067
4.690763
false
false
false
false
nineteen-apps/themify
Sources/Parser.swift
1
3305
// -*-swift-*- // The MIT License (MIT) // // Copyright (c) 2017 - Nineteen // // 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. // // Created: 2017-04-27 by Ronaldo Faria Lima // This file purpose: plist/in memory parser import Foundation struct Parser { func parse(rawThemes: [Any]) throws -> Set<Theme> { var themes = Set<Theme>() for readTheme in rawThemes { if let rawTheme = readTheme as? [String: Any] { if let name = rawTheme["name"] as? String { let theme = Theme(name: name) guard let rawElements = rawTheme["elements"] as? [[String: Any]] else { throw ThemifyError.invalidThemeConfiguration } theme.elements = try parseElements(rawElements: rawElements) themes.insert(theme) } else { throw ThemifyError.invalidThemeConfiguration } } } return themes } fileprivate func parseElements(rawElements: [[String: Any]]) throws -> Set<Element> { var elements = Set<Element>() for rawElement in rawElements { guard let rawElementType = rawElement["element"] as? String else { throw ThemifyError.invalidThemeConfiguration } if let element = Element(className: rawElementType) { element.attributes = try parseAttributes(rawAttributes: rawElement) elements.insert(element) } else { throw ThemifyError.invalidThemeConfiguration } } return elements } fileprivate func parseAttributes(rawAttributes: [String: Any]) throws -> Set<Attribute> { var attributes = Set<Attribute>() for (name, value) in rawAttributes { let attribute: Attribute! = Attribute(name: name, value: value) if attribute == nil { continue } attributes.insert(attribute) } if attributes.count == 0 { // There must be at least one single attribute. Otherwise, this theme is not good. throw ThemifyError.invalidThemeConfiguration } return attributes } }
mit
15445cd495bc95e1e59868fd6ce5c00b
40.3125
94
0.629652
4.796807
false
true
false
false
SwiftFS/Swift-FS-China
Sources/SwiftFSChina/router/Topics.swift
1
1901
// // Topics.swift // PerfectChina // // Created by mubin on 2017/7/29. // // import Foundation import PerfectHTTP import PerfectLib class Topics { //所有文章 static func topics(data: [String:Any]) throws -> RequestHandler { return { request, response in do{ let page_no = request.param(name: "page_no")?.int ?? 1 let topic_type = request.param(name: "type") ?? "default" let category = request.param(name: "category") ?? "0" let page_size = page_config.index_topic_page_size var total_count = 0 total_count = try TopicServer.get_total_count(topic_type: topic_type, category: category) let total_page = Utils.total_page(total_count: total_count, page_size: page_size) let topics = TopicServer.get_all(topic_type: topic_type, category: category, page_no: page_no, page_size: page_size) if topics == nil { try response.setBody(json: ["success":false]) response.completed() return } let encoded = try? encoder.encode(topics) if encoded != nil { if let json = String(data: encoded!,encoding:.utf8){ if let decoded = try json.jsonDecode() as? [[String:Any]] { let dic:[String:Any] = ["totalCount":total_count,"totalPage":total_page,"currentPage":page_no,"topics":decoded] try response.setBody(json: ["success":true,"data":dic]) } } } response.completed() }catch{ Log.error(message: "\(error)") } } } }
mit
a2bc029f4523c25a78402e17f1a545b3
30.032787
135
0.487586
4.528708
false
false
false
false
lyle-luan/firefox-ios
Client/Frontend/Browser/Browser.swift
1
4260
/* 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 WebKit protocol BrowserHelper { init?(browser: Browser) class func name() -> String func scriptMessageHandlerName() -> String? func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) } class Browser: NSObject, WKScriptMessageHandler { let webView: WKWebView init(configuration: WKWebViewConfiguration) { configuration.userContentController = WKUserContentController() webView = WKWebView(frame: CGRectZero, configuration: configuration) webView.allowsBackForwardNavigationGestures = true webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") super.init() } var backList: [WKBackForwardListItem]? { return webView.backForwardList.backList as? [WKBackForwardListItem] } var forwardList: [WKBackForwardListItem]? { return webView.backForwardList.forwardList as? [WKBackForwardListItem] } var url: NSURL? { return webView.URL? } var canGoBack: Bool { return webView.canGoBack } var canGoForward: Bool { return webView.canGoForward } func goBack() { webView.goBack() } func goForward() { webView.goForward() } func goToBackForwardListItem(item: WKBackForwardListItem) { webView.goToBackForwardListItem(item) } func loadRequest(request: NSURLRequest) { webView.loadRequest(request) } func stop() { webView.stopLoading() } func reload() { webView.reload() } private var helpers: [String: BrowserHelper] = [String: BrowserHelper]() func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { for helper in helpers.values { if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { if scriptMessageHandlerName == message.name { helper.userContentController(userContentController, didReceiveScriptMessage: message) return } } } } func addHelper(helper: BrowserHelper, name: String) { if let existingHelper = helpers[name] { assertionFailure("Duplicate helper added: \(name)") } helpers[name] = helper // If this helper handles script messages, then get the handler name and register it. The Browser // receives all messages and then dispatches them to the right BrowserHelper. if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { webView.configuration.userContentController.addScriptMessageHandler(self, name: scriptMessageHandlerName) } } func getHelper(#name: String) -> BrowserHelper? { return helpers[name] } } extension WKWebView { func runScriptFunction(function: String, fromScript: String, callback: (AnyObject?) -> Void) { if let path = NSBundle.mainBundle().pathForResource(fromScript, ofType: "js") { if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) { evaluateJavaScript(source, completionHandler: { (obj, err) -> Void in if let err = err { println("Error injecting \(err)") return } self.evaluateJavaScript("__firefox__.\(fromScript).\(function)", completionHandler: { (obj, err) -> Void in self.evaluateJavaScript("delete window.__firefox__.\(fromScript)", completionHandler: { (obj, err) -> Void in }) if let err = err { println("Error running \(err)") return } callback(obj) }) }) } } } }
mpl-2.0
32fd85284e77f9b1a4ea5994b8dfffd4
32.28125
136
0.625587
5.672437
false
false
false
false
Egibide-DAM/swift
02_ejemplos/10_varios/01_optional_chaining/04_acceso_propiedades.playground/Contents.swift
1
1592
class Person { var residence: Residence? } class Room { let name: String init(name: String) { self.name = name } } class Address { var buildingName: String? var buildingNumber: String? var street: String? func buildingIdentifier() -> String? { if let buildingNumber = buildingNumber, let street = street { return "\(buildingNumber) \(street)" } else if buildingName != nil { return buildingName } else { return nil } } } class Residence { var rooms = [Room]() var numberOfRooms: Int { return rooms.count } subscript(i: Int) -> Room { get { return rooms[i] } set { rooms[i] = newValue } } func printNumberOfRooms() { print("The number of rooms is \(numberOfRooms)") } var address: Address? } // ----- let john = Person() if let roomCount = john.residence?.numberOfRooms { print("John's residence has \(roomCount) room(s).") } else { print("Unable to retrieve the number of rooms.") } // Prints "Unable to retrieve the number of rooms." let someAddress = Address() someAddress.buildingNumber = "29" someAddress.street = "Acacia Road" john.residence?.address = someAddress func createAddress() -> Address { print("Function was called.") let someAddress = Address() someAddress.buildingNumber = "29" someAddress.street = "Acacia Road" return someAddress } john.residence?.address = createAddress() // residence vale nil, no se ejecuta la función
apache-2.0
eeabb07da912bc0fa88f1d613cc1b0f8
22.057971
69
0.610308
4.311653
false
false
false
false
eegeo/eegeo-example-app
ios/Include/WrldSDK/iphoneos12.0/WrldNav.framework/Headers/WRLDNavModel.swift
2
8457
import Foundation /** This describes the different events that can be sent out to the nav model. */ @objc public enum WRLDNavEvent: Int { case unknown //!< An unknown event. case startEndButtonClicked //!< Event called when start or end step-by-step directions button is tapped. case selectStartLocationClicked //!< Event called when start location textbox was tapped. case selectEndLocationClicked //!< Event called when end location textbox was tapped. case closeSetupJourneyClicked //!< Event called when close navigation button was tapped. case widgetAnimateOut //!< Event called when navigation widget should animate out. case widgetAnimateIn //!< Event called when navigation widget should animate in. case showHideListButtonClicked //!< Event called when show or hide list button in step-by-step direction is tapped. case startEndLocationsSwapped //!< Event called when start and end locations are swapped. case startLocationClearButtonClicked//!< Event called when start location clear button is tapped. case endLocationClearButtonClicked //!< Event called when end location clear button is tapped. case routeUpdated //!< Event called when route has updated and views should reload. } /** Implement this protocol to receive nav model events. */ @objc public protocol WRLDNavModelEventListener: class { /** Called when a nav event is received. */ @objc optional func eventReceived(_ key: WRLDNavEvent) } /** This describes the different states that the nav model can be in. */ @objc public enum WRLDNavMode: Int { case notReady //!< There is currently not a route configured. case ready //!< A route is configured and we are ready to start. case active //!< Navigation is currently running. } /** This is the model that holds the data that the views display. */ @objc public class WRLDNavModel: NSObject { /** The start location of the route. When the user starts a new route they will enter a new start and end location using the search UI or by selecting a point on the map, that will populate these properties. */ private var m_startLocation: WRLDNavLocation? @objc(startLocation) public var startLocation: WRLDNavLocation? { set { if m_startLocation != newValue { willChangeValue(forKey: "startLocation") m_startLocation = newValue didChangeValue(forKey: "startLocation") } } get { return m_startLocation } } /** The end location of the route. @see startLocation */ private var m_endLocation: WRLDNavLocation? @objc(endLocation) public var endLocation: WRLDNavLocation? { set { if m_endLocation != newValue { willChangeValue(forKey: "endLocation") m_endLocation = newValue didChangeValue(forKey: "endLocation") } } get { return m_endLocation } } /** The list of instructions for the route and the estimated time. */ private var m_route: WRLDNavRoute? @objc(route) public var route: WRLDNavRoute? { set { if m_route != newValue { willChangeValue(forKey: "route") m_route = newValue didChangeValue(forKey: "route") } } get { return m_route } } /** The index of the currently selected direction. This is the direction step that has been selected by the user in the UI. */ private var m_selectedDirectionIndex: Int = 0 @objc(selectedDirectionIndex) public var selectedDirectionIndex: Int { set { if m_selectedDirectionIndex != newValue { willChangeValue(forKey: "selectedDirectionIndex") m_selectedDirectionIndex = newValue didChangeValue(forKey: "selectedDirectionIndex") } } get { return m_selectedDirectionIndex } } /** The index of the current direction. This is the direction step that the location is currently at or have just passed. */ private var m_currentDirectionIndex: Int = 0 @objc(currentDirectionIndex) public var currentDirectionIndex: Int { set { if m_currentDirectionIndex != newValue { willChangeValue(forKey: "currentDirectionIndex") m_currentDirectionIndex = newValue didChangeValue(forKey: "currentDirectionIndex") } } get { return m_currentDirectionIndex } } /** The details of the current direction. This is the direction step that the location is currently at or have just passed. */ @objc(currentDirection) public var currentDirection: WRLDNavDirection? { set { if(currentDirection != newValue) { if (m_route != nil && newValue != nil) { willChangeValue(forKey: "currentDirection") m_route?.updateDirection(index: m_currentDirectionIndex, direction: newValue!) didChangeValue(forKey: "currentDirection") } } } get { return m_route?.directions[m_currentDirectionIndex] } } /** Sets the direction at a set index. @param index The index for the new direction @param direction The new direction @return Bool if been successful */ @objc public func setDirection(_ index: Int, direction: WRLDNavDirection?) -> Bool { if((m_route != nil) && (m_route?.directions != nil) && (direction != nil)){ if(index >= 0 && index < (m_route?.directions.count)!) { m_route?.updateDirection(index: index, direction: direction!) return true } } return false } /** The estimated remaining duration of the route in seconds. */ private var m_remainingRouteDuration: TimeInterval = 0 @objc(remainingRouteDuration) public var remainingRouteDuration: TimeInterval { set { if m_remainingRouteDuration != newValue { willChangeValue(forKey: "remainingRouteDuration") m_remainingRouteDuration = newValue didChangeValue(forKey: "remainingRouteDuration") } } get { return m_remainingRouteDuration } } /** The current navigation mode. */ private var m_navMode: WRLDNavMode = .notReady @objc(navMode) public var navMode: WRLDNavMode { set { if m_navMode != newValue { willChangeValue(forKey: "navMode") m_navMode = newValue didChangeValue(forKey: "navMode") } } get { return m_navMode } } /** Call this to reveive events from the model. The listener will need to implement the eventReceived method, see WRLDNavModelEventListener for an example. @note You will also need to call unregisterEventListener before destruction. @param listener The listener to receive events. */ @objc public func registerNavEventListener(_ listener: WRLDNavModelEventListener) { m_eventListeners.add(listener) } /** Call this to stop a listener from receiving events. */ @objc public func unregisterNavEventListener(_ listener: WRLDNavModelEventListener) { m_eventListeners.remove(listener) } /** Send a nav event to all listeners. */ @objc public func sendNavEvent(_ key: WRLDNavEvent) { let enumerator = m_eventListeners.objectEnumerator() while let listener = enumerator.nextObject() as? WRLDNavModelEventListener { listener.eventReceived?(key) } } private var m_eventListeners: NSHashTable<WRLDNavModelEventListener> = .weakObjects() @objc override public class func automaticallyNotifiesObservers(forKey key: String) -> Bool { return false } }
bsd-2-clause
ea6e472a34ef8c7bb390884faf9e0594
32.035156
124
0.606716
4.998227
false
false
false
false
coffee-cup/solis
SunriseSunset/NSMutableAttributedString.swift
1
1954
// // NSAttributedString.swift // SunriseSunset // // Created by Jake Runzer on 2016-08-03. // Copyright © 2016 Puddllee. All rights reserved. // import Foundation import UIKit extension NSMutableAttributedString { enum AtributeSearchType { case first, all, last } func attributeRangeFor(_ searchString: String, attributeName: String, attributeValue: AnyObject, atributeSearchType: AtributeSearchType) { let inputLength = self.string.count let searchLength = searchString.count var range = NSRange(location: 0, length: self.length) var rangeCollection = [NSRange]() while (range.location != NSNotFound) { range = (self.string as NSString).range(of: searchString, options: [], range: range) if (range.location != NSNotFound) { switch atributeSearchType { case .first: self.addAttribute(NSAttributedString.Key(rawValue: attributeName), value: attributeValue, range: NSRange(location: range.location, length: searchLength)) return case .all: self.addAttribute(NSAttributedString.Key(rawValue: attributeName), value: attributeValue, range: NSRange(location: range.location, length: searchLength)) break case .last: rangeCollection.append(range) break } range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length)) } } switch atributeSearchType { case .last: let indexOfLast = rangeCollection.count - 1 self.addAttribute(NSAttributedString.Key(rawValue: attributeName), value: attributeValue, range: rangeCollection[indexOfLast]) break default: break } } }
mit
2be229c45f8e179391c98c60097f6750
37.294118
173
0.605223
5.180371
false
false
false
false
ahoppen/swift
stdlib/public/core/DictionaryBridging.swift
7
26010
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims /// Equivalent to `NSDictionary.allKeys`, but does not leave objects on the /// autorelease pool. internal func _stdlib_NSDictionary_allKeys( _ object: AnyObject ) -> _BridgingBuffer { let nsd = unsafeBitCast(object, to: _NSDictionary.self) let count = nsd.count let storage = _BridgingBuffer(count) nsd.getObjects(nil, andKeys: storage.baseAddress, count: count) return storage } extension _NativeDictionary { // Bridging @usableFromInline __consuming internal func bridged() -> AnyObject { _connectOrphanedFoundationSubclassesIfNeeded() // We can zero-cost bridge if our keys are verbatim // or if we're the empty singleton. // Temporary var for SOME type safety. let nsDictionary: _NSDictionaryCore if _storage === __RawDictionaryStorage.empty || count == 0 { nsDictionary = __RawDictionaryStorage.empty } else if _isBridgedVerbatimToObjectiveC(Key.self), _isBridgedVerbatimToObjectiveC(Value.self) { nsDictionary = unsafeDowncast( _storage, to: _DictionaryStorage<Key, Value>.self) } else { nsDictionary = _SwiftDeferredNSDictionary(self) } return nsDictionary } } /// An NSEnumerator that works with any _NativeDictionary of /// verbatim bridgeable elements. Used by the various NSDictionary impls. final internal class _SwiftDictionaryNSEnumerator<Key: Hashable, Value> : __SwiftNativeNSEnumerator, _NSEnumerator { @nonobjc internal var base: _NativeDictionary<Key, Value> @nonobjc internal var bridgedKeys: __BridgingHashBuffer? @nonobjc internal var nextBucket: _NativeDictionary<Key, Value>.Bucket @nonobjc internal var endBucket: _NativeDictionary<Key, Value>.Bucket @objc internal override required init() { _internalInvariantFailure("don't call this designated initializer") } internal init(_ base: __owned _NativeDictionary<Key, Value>) { _internalInvariant(_isBridgedVerbatimToObjectiveC(Key.self)) _internalInvariant(_orphanedFoundationSubclassesReparented) self.base = base self.bridgedKeys = nil self.nextBucket = base.hashTable.startBucket self.endBucket = base.hashTable.endBucket super.init() } @nonobjc internal init(_ deferred: __owned _SwiftDeferredNSDictionary<Key, Value>) { _internalInvariant(!_isBridgedVerbatimToObjectiveC(Key.self)) _internalInvariant(_orphanedFoundationSubclassesReparented) self.base = deferred.native self.bridgedKeys = deferred.bridgeKeys() self.nextBucket = base.hashTable.startBucket self.endBucket = base.hashTable.endBucket super.init() } private func bridgedKey(at bucket: _HashTable.Bucket) -> AnyObject { _internalInvariant(base.hashTable.isOccupied(bucket)) if let bridgedKeys = self.bridgedKeys { return bridgedKeys[bucket] } return _bridgeAnythingToObjectiveC(base.uncheckedKey(at: bucket)) } @objc internal func nextObject() -> AnyObject? { if nextBucket == endBucket { return nil } let bucket = nextBucket nextBucket = base.hashTable.occupiedBucket(after: nextBucket) return self.bridgedKey(at: bucket) } @objc(countByEnumeratingWithState:objects:count:) internal func countByEnumerating( with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>, count: Int ) -> Int { var theState = state.pointee if theState.state == 0 { theState.state = 1 // Arbitrary non-zero value. theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects) theState.mutationsPtr = _fastEnumerationStorageMutationsPtr } if nextBucket == endBucket { state.pointee = theState return 0 } // Return only a single element so that code can start iterating via fast // enumeration, terminate it, and continue via NSEnumerator. let unmanagedObjects = _UnmanagedAnyObjectArray(objects) unmanagedObjects[0] = self.bridgedKey(at: nextBucket) nextBucket = base.hashTable.occupiedBucket(after: nextBucket) state.pointee = theState return 1 } } /// This class exists for Objective-C bridging. It holds a reference to a /// _NativeDictionary, and can be upcast to NSSelf when bridging is /// necessary. This is the fallback implementation for situations where /// toll-free bridging isn't possible. On first access, a _NativeDictionary /// of AnyObject will be constructed containing all the bridged elements. final internal class _SwiftDeferredNSDictionary<Key: Hashable, Value> : __SwiftNativeNSDictionary, _NSDictionaryCore { @usableFromInline internal typealias Bucket = _HashTable.Bucket // This stored property must be stored at offset zero. We perform atomic // operations on it. // // Do not access this property directly. @nonobjc private var _bridgedKeys_DoNotUse: AnyObject? // This stored property must be stored at offset one. We perform atomic // operations on it. // // Do not access this property directly. @nonobjc private var _bridgedValues_DoNotUse: AnyObject? /// The unbridged elements. internal var native: _NativeDictionary<Key, Value> internal init(_ native: __owned _NativeDictionary<Key, Value>) { _internalInvariant(native.count > 0) _internalInvariant(!_isBridgedVerbatimToObjectiveC(Key.self) || !_isBridgedVerbatimToObjectiveC(Value.self)) self.native = native super.init() } @objc internal required init( objects: UnsafePointer<AnyObject?>, forKeys: UnsafeRawPointer, count: Int ) { _internalInvariantFailure("don't call this designated initializer") } @nonobjc private var _bridgedKeysPtr: UnsafeMutablePointer<AnyObject?> { return _getUnsafePointerToStoredProperties(self) .assumingMemoryBound(to: Optional<AnyObject>.self) } @nonobjc private var _bridgedValuesPtr: UnsafeMutablePointer<AnyObject?> { return _bridgedKeysPtr + 1 } /// The buffer for bridged keys, if present. @nonobjc private var _bridgedKeys: __BridgingHashBuffer? { guard let ref = _stdlib_atomicLoadARCRef(object: _bridgedKeysPtr) else { return nil } return unsafeDowncast(ref, to: __BridgingHashBuffer.self) } /// The buffer for bridged values, if present. @nonobjc private var _bridgedValues: __BridgingHashBuffer? { guard let ref = _stdlib_atomicLoadARCRef(object: _bridgedValuesPtr) else { return nil } return unsafeDowncast(ref, to: __BridgingHashBuffer.self) } /// Attach a buffer for bridged Dictionary keys. @nonobjc private func _initializeBridgedKeys(_ storage: __BridgingHashBuffer) { _stdlib_atomicInitializeARCRef(object: _bridgedKeysPtr, desired: storage) } /// Attach a buffer for bridged Dictionary values. @nonobjc private func _initializeBridgedValues(_ storage: __BridgingHashBuffer) { _stdlib_atomicInitializeARCRef(object: _bridgedValuesPtr, desired: storage) } @nonobjc internal func bridgeKeys() -> __BridgingHashBuffer? { if _isBridgedVerbatimToObjectiveC(Key.self) { return nil } if let bridgedKeys = _bridgedKeys { return bridgedKeys } // Allocate and initialize heap storage for bridged keys. let bridged = __BridgingHashBuffer.allocate( owner: native._storage, hashTable: native.hashTable) for bucket in native.hashTable { let object = _bridgeAnythingToObjectiveC(native.uncheckedKey(at: bucket)) bridged.initialize(at: bucket, to: object) } // Atomically put the bridged keys in place. _initializeBridgedKeys(bridged) return _bridgedKeys! } @nonobjc internal func bridgeValues() -> __BridgingHashBuffer? { if _isBridgedVerbatimToObjectiveC(Value.self) { return nil } if let bridgedValues = _bridgedValues { return bridgedValues } // Allocate and initialize heap storage for bridged values. let bridged = __BridgingHashBuffer.allocate( owner: native._storage, hashTable: native.hashTable) for bucket in native.hashTable { let value = native.uncheckedValue(at: bucket) let cocoaValue = _bridgeAnythingToObjectiveC(value) bridged.initialize(at: bucket, to: cocoaValue) } // Atomically put the bridged values in place. _initializeBridgedValues(bridged) return _bridgedValues! } @objc(copyWithZone:) internal func copy(with zone: _SwiftNSZone?) -> AnyObject { // Instances of this class should be visible outside of standard library as // having `NSDictionary` type, which is immutable. return self } @inline(__always) private func _key( at bucket: Bucket, bridgedKeys: __BridgingHashBuffer? ) -> AnyObject { if let bridgedKeys = bridgedKeys { return bridgedKeys[bucket] } return _bridgeAnythingToObjectiveC(native.uncheckedKey(at: bucket)) } @inline(__always) private func _value( at bucket: Bucket, bridgedValues: __BridgingHashBuffer? ) -> AnyObject { if let bridgedValues = bridgedValues { return bridgedValues[bucket] } return _bridgeAnythingToObjectiveC(native.uncheckedValue(at: bucket)) } @objc(objectForKey:) internal func object(forKey aKey: AnyObject) -> AnyObject? { guard let nativeKey = _conditionallyBridgeFromObjectiveC(aKey, Key.self) else { return nil } let (bucket, found) = native.find(nativeKey) guard found else { return nil } return _value(at: bucket, bridgedValues: bridgeValues()) } @objc internal func keyEnumerator() -> _NSEnumerator { if _isBridgedVerbatimToObjectiveC(Key.self) { return _SwiftDictionaryNSEnumerator<Key, Value>(native) } return _SwiftDictionaryNSEnumerator<Key, Value>(self) } @objc(getObjects:andKeys:count:) internal func getObjects( _ objects: UnsafeMutablePointer<AnyObject>?, andKeys keys: UnsafeMutablePointer<AnyObject>?, count: Int ) { _precondition(count >= 0, "Invalid count") guard count > 0 else { return } let bridgedKeys = bridgeKeys() let bridgedValues = bridgeValues() var i = 0 // Current position in the output buffers defer { _fixLifetime(self) } switch (_UnmanagedAnyObjectArray(keys), _UnmanagedAnyObjectArray(objects)) { case (let unmanagedKeys?, let unmanagedObjects?): for bucket in native.hashTable { unmanagedKeys[i] = _key(at: bucket, bridgedKeys: bridgedKeys) unmanagedObjects[i] = _value(at: bucket, bridgedValues: bridgedValues) i += 1 guard i < count else { break } } case (let unmanagedKeys?, nil): for bucket in native.hashTable { unmanagedKeys[i] = _key(at: bucket, bridgedKeys: bridgedKeys) i += 1 guard i < count else { break } } case (nil, let unmanagedObjects?): for bucket in native.hashTable { unmanagedObjects[i] = _value(at: bucket, bridgedValues: bridgedValues) i += 1 guard i < count else { break } } case (nil, nil): // Do nothing break } } @objc(enumerateKeysAndObjectsWithOptions:usingBlock:) internal func enumerateKeysAndObjects( options: Int, using block: @convention(block) ( Unmanaged<AnyObject>, Unmanaged<AnyObject>, UnsafeMutablePointer<UInt8> ) -> Void) { let bridgedKeys = bridgeKeys() let bridgedValues = bridgeValues() defer { _fixLifetime(self) } var stop: UInt8 = 0 for bucket in native.hashTable { let key = _key(at: bucket, bridgedKeys: bridgedKeys) let value = _value(at: bucket, bridgedValues: bridgedValues) block( Unmanaged.passUnretained(key), Unmanaged.passUnretained(value), &stop) if stop != 0 { return } } } @objc internal var count: Int { return native.count } @objc(countByEnumeratingWithState:objects:count:) internal func countByEnumerating( with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>?, count: Int ) -> Int { defer { _fixLifetime(self) } let hashTable = native.hashTable var theState = state.pointee if theState.state == 0 { theState.state = 1 // Arbitrary non-zero value. theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects) theState.mutationsPtr = _fastEnumerationStorageMutationsPtr theState.extra.0 = CUnsignedLong(hashTable.startBucket.offset) } // Test 'objects' rather than 'count' because (a) this is very rare anyway, // and (b) the optimizer should then be able to optimize away the // unwrapping check below. if _slowPath(objects == nil) { return 0 } let unmanagedObjects = _UnmanagedAnyObjectArray(objects!) var bucket = _HashTable.Bucket(offset: Int(theState.extra.0)) let endBucket = hashTable.endBucket _precondition(bucket == endBucket || hashTable.isOccupied(bucket), "Invalid fast enumeration state") var stored = 0 // Only need to bridge once, so we can hoist it out of the loop. let bridgedKeys = bridgeKeys() for i in 0..<count { if bucket == endBucket { break } unmanagedObjects[i] = _key(at: bucket, bridgedKeys: bridgedKeys) stored += 1 bucket = hashTable.occupiedBucket(after: bucket) } theState.extra.0 = CUnsignedLong(bucket.offset) state.pointee = theState return stored } } // NOTE: older runtimes called this struct _CocoaDictionary. The two // must coexist without conflicting ObjC class names from the nested // classes, so it was renamed. The old names must not be used in the new // runtime. @usableFromInline @frozen internal struct __CocoaDictionary { @usableFromInline internal let object: AnyObject @inlinable internal init(_ object: __owned AnyObject) { self.object = object } } extension __CocoaDictionary { @usableFromInline internal func isEqual(to other: __CocoaDictionary) -> Bool { return _stdlib_NSObject_isEqual(self.object, other.object) } } extension __CocoaDictionary: _DictionaryBuffer { @usableFromInline internal typealias Key = AnyObject @usableFromInline internal typealias Value = AnyObject @usableFromInline // FIXME(cocoa-index): Should be inlinable internal var startIndex: Index { @_effects(releasenone) get { let allKeys = _stdlib_NSDictionary_allKeys(self.object) return Index(Index.Storage(self, allKeys), offset: 0) } } @usableFromInline // FIXME(cocoa-index): Should be inlinable internal var endIndex: Index { @_effects(releasenone) get { let allKeys = _stdlib_NSDictionary_allKeys(self.object) return Index(Index.Storage(self, allKeys), offset: allKeys.count) } } @usableFromInline // FIXME(cocoa-index): Should be inlinable @_effects(releasenone) internal func index(after index: Index) -> Index { validate(index) var result = index result._offset += 1 return result } internal func validate(_ index: Index) { _precondition(index.storage.base.object === self.object, "Invalid index") _precondition(index._offset < index.storage.allKeys.count, "Attempt to access endIndex") } @usableFromInline // FIXME(cocoa-index): Should be inlinable internal func formIndex(after index: inout Index, isUnique: Bool) { validate(index) index._offset += 1 } @usableFromInline // FIXME(cocoa-index): Should be inlinable @_effects(releasenone) internal func index(forKey key: Key) -> Index? { // Fast path that does not involve creating an array of all keys. In case // the key is present, this lookup is a penalty for the slow path, but the // potential savings are significant: we could skip a memory allocation and // a linear search. if lookup(key) == nil { return nil } let allKeys = _stdlib_NSDictionary_allKeys(object) for i in 0..<allKeys.count { if _stdlib_NSObject_isEqual(key, allKeys[i]) { return Index(Index.Storage(self, allKeys), offset: i) } } _internalInvariantFailure( "An NSDictionary key wasn't listed amongst its enumerated contents") } @usableFromInline internal var count: Int { let nsd = unsafeBitCast(object, to: _NSDictionary.self) return nsd.count } @usableFromInline internal func contains(_ key: Key) -> Bool { let nsd = unsafeBitCast(object, to: _NSDictionary.self) return nsd.object(forKey: key) != nil } @usableFromInline internal func lookup(_ key: Key) -> Value? { let nsd = unsafeBitCast(object, to: _NSDictionary.self) return nsd.object(forKey: key) } @usableFromInline // FIXME(cocoa-index): Should be inlinable @_effects(releasenone) internal func lookup(_ index: Index) -> (key: Key, value: Value) { _precondition(index.storage.base.object === self.object, "Invalid index") let key: Key = index.storage.allKeys[index._offset] let value: Value = index.storage.base.object.object(forKey: key)! return (key, value) } @usableFromInline // FIXME(cocoa-index): Make inlinable @_effects(releasenone) func key(at index: Index) -> Key { _precondition(index.storage.base.object === self.object, "Invalid index") return index.key } @usableFromInline // FIXME(cocoa-index): Make inlinable @_effects(releasenone) func value(at index: Index) -> Value { _precondition(index.storage.base.object === self.object, "Invalid index") let key = index.storage.allKeys[index._offset] return index.storage.base.object.object(forKey: key)! } } extension __CocoaDictionary { @inlinable internal func mapValues<Key: Hashable, Value, T>( _ transform: (Value) throws -> T ) rethrows -> _NativeDictionary<Key, T> { var result = _NativeDictionary<Key, T>(capacity: self.count) for (cocoaKey, cocoaValue) in self { let key = _forceBridgeFromObjectiveC(cocoaKey, Key.self) let value = _forceBridgeFromObjectiveC(cocoaValue, Value.self) try result.insertNew(key: key, value: transform(value)) } return result } } extension __CocoaDictionary { @frozen @usableFromInline internal struct Index { internal var _storage: Builtin.BridgeObject internal var _offset: Int internal var storage: Storage { @inline(__always) get { let storage = _bridgeObject(toNative: _storage) return unsafeDowncast(storage, to: Storage.self) } } internal init(_ storage: Storage, offset: Int) { self._storage = _bridgeObject(fromNative: storage) self._offset = offset } } } extension __CocoaDictionary.Index { // FIXME(cocoa-index): Try using an NSEnumerator to speed this up. internal class Storage { // Assumption: we rely on NSDictionary.getObjects when being // repeatedly called on the same NSDictionary, returning items in the same // order every time. // Similarly, the same assumption holds for NSSet.allObjects. /// A reference to the NSDictionary, which owns members in `allObjects`, /// or `allKeys`, for NSSet and NSDictionary respectively. internal let base: __CocoaDictionary // FIXME: swift-3-indexing-model: try to remove the cocoa reference, but // make sure that we have a safety check for accessing `allKeys`. Maybe // move both into the dictionary/set itself. /// An unowned array of keys. internal var allKeys: _BridgingBuffer internal init( _ base: __owned __CocoaDictionary, _ allKeys: __owned _BridgingBuffer ) { self.base = base self.allKeys = allKeys } } } extension __CocoaDictionary.Index { @usableFromInline internal var handleBitPattern: UInt { @_effects(readonly) get { return unsafeBitCast(storage, to: UInt.self) } } @usableFromInline internal var dictionary: __CocoaDictionary { @_effects(releasenone) get { return storage.base } } } extension __CocoaDictionary.Index { @usableFromInline // FIXME(cocoa-index): Make inlinable @nonobjc internal var key: AnyObject { @_effects(readonly) get { _precondition(_offset < storage.allKeys.count, "Attempting to access Dictionary elements using an invalid index") return storage.allKeys[_offset] } } @usableFromInline // FIXME(cocoa-index): Make inlinable @nonobjc internal var age: Int32 { @_effects(readonly) get { return _HashTable.age(for: storage.base.object) } } } extension __CocoaDictionary.Index: Equatable { @usableFromInline // FIXME(cocoa-index): Make inlinable @_effects(readonly) internal static func == ( lhs: __CocoaDictionary.Index, rhs: __CocoaDictionary.Index ) -> Bool { _precondition(lhs.storage.base.object === rhs.storage.base.object, "Comparing indexes from different dictionaries") return lhs._offset == rhs._offset } } extension __CocoaDictionary.Index: Comparable { @usableFromInline // FIXME(cocoa-index): Make inlinable @_effects(readonly) internal static func < ( lhs: __CocoaDictionary.Index, rhs: __CocoaDictionary.Index ) -> Bool { _precondition(lhs.storage.base.object === rhs.storage.base.object, "Comparing indexes from different dictionaries") return lhs._offset < rhs._offset } } extension __CocoaDictionary: Sequence { @usableFromInline final internal class Iterator { // Cocoa Dictionary iterator has to be a class, otherwise we cannot // guarantee that the fast enumeration struct is pinned to a certain memory // location. // This stored property should be stored at offset zero. There's code below // relying on this. internal var _fastEnumerationState: _SwiftNSFastEnumerationState = _makeSwiftNSFastEnumerationState() // This stored property should be stored right after // `_fastEnumerationState`. There's code below relying on this. internal var _fastEnumerationStackBuf = _CocoaFastEnumerationStackBuf() internal let base: __CocoaDictionary internal var _fastEnumerationStatePtr: UnsafeMutablePointer<_SwiftNSFastEnumerationState> { return _getUnsafePointerToStoredProperties(self).assumingMemoryBound( to: _SwiftNSFastEnumerationState.self) } internal var _fastEnumerationStackBufPtr: UnsafeMutablePointer<_CocoaFastEnumerationStackBuf> { return UnsafeMutableRawPointer(_fastEnumerationStatePtr + 1) .assumingMemoryBound(to: _CocoaFastEnumerationStackBuf.self) } // These members have to be word-sized integers, they cannot be limited to // Int8 just because our storage holds 16 elements: fast enumeration is // allowed to return inner pointers to the container, which can be much // larger. internal var itemIndex: Int = 0 internal var itemCount: Int = 0 internal init(_ base: __owned __CocoaDictionary) { self.base = base } } @usableFromInline @_effects(releasenone) internal __consuming func makeIterator() -> Iterator { return Iterator(self) } } extension __CocoaDictionary.Iterator: IteratorProtocol { @usableFromInline internal typealias Element = (key: AnyObject, value: AnyObject) @usableFromInline internal func nextKey() -> AnyObject? { if itemIndex < 0 { return nil } let base = self.base if itemIndex == itemCount { let stackBufCount = _fastEnumerationStackBuf.count // We can't use `withUnsafeMutablePointer` here to get pointers to // properties, because doing so might introduce a writeback storage, but // fast enumeration relies on the pointer identity of the enumeration // state struct. itemCount = base.object.countByEnumerating( with: _fastEnumerationStatePtr, objects: UnsafeMutableRawPointer(_fastEnumerationStackBufPtr) .assumingMemoryBound(to: AnyObject.self), count: stackBufCount) if itemCount == 0 { itemIndex = -1 return nil } itemIndex = 0 } let itemsPtrUP = UnsafeMutableRawPointer(_fastEnumerationState.itemsPtr!) .assumingMemoryBound(to: AnyObject.self) let itemsPtr = _UnmanagedAnyObjectArray(itemsPtrUP) let key: AnyObject = itemsPtr[itemIndex] itemIndex += 1 return key } @usableFromInline internal func next() -> Element? { guard let key = nextKey() else { return nil } let value: AnyObject = base.object.object(forKey: key)! return (key, value) } } //===--- Bridging ---------------------------------------------------------===// extension Dictionary { @inlinable public __consuming func _bridgeToObjectiveCImpl() -> AnyObject { guard _variant.isNative else { return _variant.asCocoa.object } return _variant.asNative.bridged() } /// Returns the native Dictionary hidden inside this NSDictionary; /// returns nil otherwise. public static func _bridgeFromObjectiveCAdoptingNativeStorageOf( _ s: __owned AnyObject ) -> Dictionary<Key, Value>? { // Try all three NSDictionary impls that we currently provide. if let deferred = s as? _SwiftDeferredNSDictionary<Key, Value> { return Dictionary(_native: deferred.native) } if let nativeStorage = s as? _DictionaryStorage<Key, Value> { return Dictionary(_native: _NativeDictionary(nativeStorage)) } if s === __RawDictionaryStorage.empty { return Dictionary() } // FIXME: what if `s` is native storage, but for different key/value type? return nil } } #endif // _runtime(_ObjC)
apache-2.0
b984d95994430499940660685ed89df7
30.875
80
0.691388
4.573589
false
false
false
false
dreamsxin/swift
test/DebugInfo/mangling.swift
3
1932
// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s // Type: // Swift.Dictionary<Swift.Int64, Swift.String> func markUsed<T>(_ t: T) {} // Variable: // mangling.myDict : Swift.Dictionary<Swift.Int64, Swift.String> // CHECK: !DIGlobalVariable(name: "myDict", // CHECK-SAME: linkageName: "_Tv8mangling6myDictGVs10DictionaryVs5Int64SS_", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[DT:[0-9]+]] // CHECK: ![[DT]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Dictionary" var myDict = Dictionary<Int64, String>() myDict[12] = "Hello!" // mangling.myTuple1 : (Name : Swift.String, Id : Swift.Int64) // CHECK: !DIGlobalVariable(name: "myTuple1", // CHECK-SAME: linkageName: "_Tv8mangling8myTuple1T4NameSS2IdVs5Int64_", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[TT1:[0-9]+]] // CHECK: ![[TT1]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_TtT4NameSS2IdVs5Int64_" var myTuple1 : (Name: String, Id: Int64) = ("A", 1) // mangling.myTuple2 : (Swift.String, Id : Swift.Int64) // CHECK: !DIGlobalVariable(name: "myTuple2", // CHECK-SAME: linkageName: "_Tv8mangling8myTuple2TSS2IdVs5Int64_", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[TT2:[0-9]+]] // CHECK: ![[TT2]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_TtTSS2IdVs5Int64_" var myTuple2 : ( String, Id: Int64) = ("B", 2) // mangling.myTuple3 : (Swift.String, Swift.Int64) // CHECK: !DIGlobalVariable(name: "myTuple3", // CHECK-SAME: linkageName: "_Tv8mangling8myTuple3TSSVs5Int64_", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[TT3:[0-9]+]] // CHECK: ![[TT3]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_TtTSSVs5Int64_" var myTuple3 : ( String, Int64) = ("C", 3) markUsed(myTuple1.Id) markUsed(myTuple2.Id) markUsed({ $0.1 }(myTuple3))
apache-2.0
c6aa322557637131d1edced1a0d3ffa8
45
97
0.621636
2.98609
false
false
false
false
cliqz-oss/browser-ios
Client/Cliqz/Foundation/Helpers/NewsNotificationPermissionHelper.swift
2
5232
// // NewsNotificationPermissionHelper.swift // Client // // Created by Mahmoud Adam on 5/27/16. // Copyright © 2016 Mozilla. All rights reserved. // import UIKit class NewsNotificationPermissionHelper: NSObject { //MARK: - Constants fileprivate let minimumNumberOfOpenings = 4 fileprivate let minimumNumberOfDays = 8 fileprivate let askedBeforeKey = "askedBefore" fileprivate let lastAskDayKey = "lastAskDay" fileprivate let disableAskingKey = "disableAsking" fileprivate let newInstallKey = "newInstall" fileprivate let installDayKey = "installDay" fileprivate let numberOfOpeningsKey = "numberOfOpenings" fileprivate var askingDisabled: Bool? //MARK: - Singltone & init static let sharedInstance = NewsNotificationPermissionHelper() //MARK: - Public APIs func onAppEnterBackground() { return // TODO: Commented till push notifications will be available /* let numberOfOpenings = getNumerOfOpenings() LocalDataStore.setObject(numberOfOpenings + 1, forKey: numberOfOpeningsKey) askingDisabled = LocalDataStore.objectForKey(disableAskingKey) as? Bool */ } func onAskForPermission() { LocalDataStore.setObject(true, forKey: askedBeforeKey) LocalDataStore.setObject(0, forKey: numberOfOpeningsKey) LocalDataStore.setObject(Date.getDay(), forKey: lastAskDayKey) } func isAksedForPermissionBefore() -> Bool { guard let askedBefore = LocalDataStore.objectForKey(askedBeforeKey) as? Bool else { return false } return askedBefore } func disableAskingForPermission () { askingDisabled = true LocalDataStore.setObject(askingDisabled, forKey: disableAskingKey) } func isAskingForPermissionDisabled () -> Bool { guard let isDisabled = askingDisabled else { return false } return isDisabled } func shouldAskForPermission() -> Bool { return false // TODO: Commented till push notifications will be available /* if isAskingForPermissionDisabled() || UIApplication.sharedApplication().isRegisteredForRemoteNotifications() { return false } var shouldAskForPermission = true if isNewInstall() || isAksedForPermissionBefore() { if getNumberOfDaysSinceLastAction() < minimumNumberOfDays || getNumerOfOpenings() < minimumNumberOfOpenings { shouldAskForPermission = false } } return shouldAskForPermission */ } func enableNewsNotifications() { let notificationSettings = UIUserNotificationSettings(types: [UIUserNotificationType.badge, UIUserNotificationType.sound, UIUserNotificationType.alert], categories: nil) UIApplication.shared.registerForRemoteNotifications() UIApplication.shared.registerUserNotificationSettings(notificationSettings) TelemetryLogger.sharedInstance.logEvent(.NewsNotification("enable")) } func disableNewsNotifications() { UIApplication.shared.unregisterForRemoteNotifications() TelemetryLogger.sharedInstance.logEvent(.NewsNotification("disalbe")) } //MARK: - Private APIs fileprivate func isNewInstall() -> Bool { var isNewInstall = false // check if it is calcualted before if let isNewInstall = LocalDataStore.objectForKey(newInstallKey) as? Bool { return isNewInstall; } // compare today's day with install day to determine whether it is update or new install let todaysDay = Date.getDay() if let installDay = TelemetryLogger.sharedInstance.getInstallDay(), todaysDay == installDay { isNewInstall = true LocalDataStore.setObject(todaysDay, forKey: installDayKey) } LocalDataStore.setObject(isNewInstall, forKey: newInstallKey) return isNewInstall } fileprivate func getNumberOfDaysSinceLastAction() -> Int { if isNewInstall() && !isAksedForPermissionBefore() { return getNumberOfDaysSinceInstall() } else { return getNumberOfDaysSinceLastAsk() } } fileprivate func getNumberOfDaysSinceInstall() -> Int { guard let installDay = LocalDataStore.objectForKey(installDayKey) as? Int else { return 0 } let daysSinceInstal = Date.getDay() - installDay return daysSinceInstal } fileprivate func getNumberOfDaysSinceLastAsk() -> Int { guard let lastAskDay = LocalDataStore.objectForKey(lastAskDayKey) as? Int else { return 0 } let daysSinceLastAsk = Date.getDay() - lastAskDay return daysSinceLastAsk } fileprivate func getNumerOfOpenings() -> Int { guard let numberOfOpenings = LocalDataStore.objectForKey(numberOfOpeningsKey) as? Int else { return 0 } return numberOfOpenings } }
mpl-2.0
a0111f04c15a387c2fc95ff978a9e550
31.899371
177
0.650162
5.278507
false
false
false
false
theappbusiness/TABResourceLoader
Tests/TABResourceLoaderTests/Mocks/MockJSONDecodableResource.swift
1
1181
// // MockJSONDecodableResource.swift // TABResourceLoader // // Created by Sam Dods on 06/10/2017. // Copyright © 2017 Kin + Carta. All rights reserved. // import Foundation @testable import TABResourceLoader // MARK: - Object struct MockJSONDecodableResource: JSONDecodableResourceType { typealias Model = MockObject typealias Root = Model } struct MockNestedJSONDecodableResource: JSONDecodableResourceType { typealias Model = MockObject struct ResponseRoot: Decodable { let data: NestedData struct NestedData: Decodable { let mock: MockObject } } func model(mappedFrom root: ResponseRoot) throws -> MockObject { return root.data.mock } } // MARK: - Array struct MockJSONArrayDecodableResource: JSONDecodableResourceType { typealias Model = [MockObject] typealias Root = Model } struct MockNestedJSONArrayDecodableResource: JSONDecodableResourceType { typealias Model = [MockObject] struct ResponseRoot: Decodable { let data: NestedData struct NestedData: Decodable { let mocks: [MockObject] } } func model(mappedFrom root: ResponseRoot) throws -> [MockObject] { return root.data.mocks } }
mit
c2b4693c669628018a06e2b18de0e7be
20.851852
72
0.734746
4.214286
false
false
false
false
mcxiaoke/learning-ios
cocoa_programming_for_osx/31_CustomViewContainers/ViewControl/ViewControl/ImageViewController.swift
1
2212
// // ImageViewController.swift // ViewControl // // Created by mcxiaoke on 16/5/23. // Copyright © 2016年 mcxiaoke. All rights reserved. // import Cocoa class ImageViewController: NSViewController, ImageRepresentable { weak var imageView: NSImageView? var image: NSImage? override func loadView() { self.view = NSView(frame: CGRectZero) self.view.translatesAutoresizingMaskIntoConstraints = false let imageView = NSImageView(frame:CGRectZero) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.imageScaling = NSImageScaling.ScaleProportionallyDown self.imageView = imageView self.view.addSubview(imageView) let constraint1 = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[imageView]-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["imageView":imageView]) let constraint2 = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[imageView]-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["imageView":imageView]) NSLayoutConstraint.activateConstraints(constraint1) NSLayoutConstraint.activateConstraints(constraint2) // let top = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0) // let bottom = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0) // let leading = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0.0) // let trailing = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0.0) // NSLayoutConstraint.activateConstraints([top, bottom, leading, trailing]) } override func viewDidLoad() { super.viewDidLoad() self.imageView?.image = image } }
apache-2.0
ef6d65680a64c600a71ad53ef5a624fd
51.595238
220
0.764599
4.908889
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Code/WMFReferencePageViewController.swift
1
5092
import WMF extension UIViewController { @objc class func wmf_viewControllerFromReferencePanelsStoryboard() -> Self { return self.wmf_viewControllerFromStoryboardNamed("WMFReferencePanels") } } @objc protocol WMFReferencePageViewAppearanceDelegate : NSObjectProtocol { func referencePageViewControllerWillAppear(_ referencePageViewController: WMFReferencePageViewController) func referencePageViewControllerWillDisappear(_ referencePageViewController: WMFReferencePageViewController) } class WMFReferencePageViewController: UIViewController, UIPageViewControllerDataSource, Themeable { @objc var lastClickedReferencesIndex:Int = 0 @objc var lastClickedReferencesGroup = [WMFReference]() @objc weak internal var appearanceDelegate: WMFReferencePageViewAppearanceDelegate? @objc public var pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) @IBOutlet fileprivate var containerView: UIView! var theme = Theme.standard func apply(theme: Theme) { self.theme = theme backgroundView.apply(theme: theme) guard viewIfLoaded != nil else { return } } fileprivate lazy var pageControllers: [UIViewController] = { var controllers:[UIViewController] = [] for reference in self.lastClickedReferencesGroup { let panel = WMFReferencePanelViewController.wmf_viewControllerFromReferencePanelsStoryboard() panel.apply(theme: self.theme) panel.reference = reference controllers.append(panel) } return controllers }() @objc lazy var backgroundView: WMFReferencePageBackgroundView = { return WMFReferencePageBackgroundView() }() override func viewDidLoad() { super.viewDidLoad() addChildViewController(pageViewController) pageViewController.view.frame = containerView.bounds pageViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] containerView.addSubview(pageViewController.view) pageViewController.didMove(toParentViewController: self) pageViewController.dataSource = self let direction:UIPageViewControllerNavigationDirection = UIApplication.shared.wmf_isRTL ? .forward : .reverse let initiallyVisibleController = pageControllers[lastClickedReferencesIndex] pageViewController.setViewControllers([initiallyVisibleController], direction: direction, animated: true, completion: nil) addBackgroundView() if let scrollView = view.wmf_firstSubviewOfType(UIScrollView.self) { scrollView.clipsToBounds = false } apply(theme: theme) } fileprivate func addBackgroundView() { view.wmf_addSubviewWithConstraintsToEdges(backgroundView) view.sendSubview(toBack: backgroundView) } @objc internal func firstPanelView() -> UIView? { guard let viewControllers = pageViewController.viewControllers, let firstVC = viewControllers.first as? WMFReferencePanelViewController else { return nil } return firstVC.containerView } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) appearanceDelegate?.referencePageViewControllerWillAppear(self) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) appearanceDelegate?.referencePageViewControllerWillDisappear(self) } func presentationCount(for pageViewController: UIPageViewController) -> Int { return pageControllers.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { guard let viewControllers = pageViewController.viewControllers, let currentVC = viewControllers.first, let presentationIndex = pageControllers.index(of: currentVC) else { return 0 } return presentationIndex } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let index = pageControllers.index(of: viewController) else { return nil } return index >= pageControllers.count - 1 ? nil : pageControllers[index + 1] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = pageControllers.index(of: viewController) else { return nil } return index == 0 ? nil : pageControllers[index - 1] } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { super.willTransition(to: newCollection, with: coordinator) self.presentingViewController?.dismiss(animated: false, completion: nil) } }
mit
51d00722bc9dd8842805b3e8f076d30b
38.78125
178
0.709544
6.255528
false
false
false
false
andreswebde/BestApp
BestApps/SplashViewController.swift
1
1512
// // SplashViewController.swift // BestApps // // Created by Andres Guzman on 9/02/16. // Copyright © 2016 andres. All rights reserved. // import UIKit class SplashViewController: UIViewController { // MARK: UI Elements @IBOutlet weak var activityIndicator: UIActivityIndicatorView! // MARK: OVERRIDE METHODS override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBarHidden = true let helperMethod = GlobalClass.Instance activityIndicator.startAnimating() helperMethod.obtainMainService(helperMethod.mainServiceURL,currentController: self) } // 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?) { // Se realiza la navegación con la ayuda de segues en el storyboard. Dependiendo de su identificador se ejecutan las acciones pertinentes. if segue.identifier == "goToMenu"{ let targetVC = segue.destinationViewController as! CategoryTableViewController targetVC.appCategories = (DBHelper.Instance.managedObjectsByName("Category") as! [Category]) } else if segue.identifier == "goToMenu2"{ let targetVC = segue.destinationViewController as! CategoryCollectionViewController targetVC.categoriesRetrived = (DBHelper.Instance.managedObjectsByName("Category") as! [Category]) } } }
mit
5441231fbb3bcdb6e64cdc895f4debde
34.116279
144
0.723841
4.855305
false
false
false
false
vitormesquita/Malert
Example/Malert/examples/example9/Example9View.swift
1
2004
// // Example9View.swift // Malert_Example // // Created by Vitor Mesquita on 29/08/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit class Example9View: UIView { private var tableViewContraints = [NSLayoutConstraint]() private lazy var tableView: UITableView = { let tableView = UITableView() tableView.translatesAutoresizingMaskIntoConstraints = false tableView.delegate = self tableView.dataSource = self tableView.register(UINib(nibName: "Example9TableViewCell", bundle: nil), forCellReuseIdentifier: "Example9TableViewCell") tableView.estimatedRowHeight = 44 return tableView }() init() { super.init(frame: .zero) addTableView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addTableView() } private func addTableView() { self.addSubview(tableView) tableViewContraints = [ tableView.leadingAnchor.constraint(equalTo: self.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: self.trailingAnchor), tableView.topAnchor.constraint(equalTo: self.topAnchor), tableView.bottomAnchor.constraint(equalTo: self.bottomAnchor), tableView.heightAnchor.constraint(equalToConstant: 200) // You need to setup a fixed Height cause tableView can not calculate it own size. ] NSLayoutConstraint.activate(tableViewContraints) } } extension Example9View: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Example9TableViewCell", for: indexPath) as! Example9TableViewCell cell.label.text = "Rox \(indexPath.row + 1)" return cell } }
mit
ccbb4537aab2ff3291fb9735eba98eb0
31.836066
150
0.689466
5.109694
false
false
false
false
mrdepth/Neocom
Neocom/Neocom/Fitting/Actions/DamagePatterns.swift
2
1873
// // DamagePatterns.swift // Neocom // // Created by Artem Shimanski on 3/19/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import Dgmpp import CoreData struct DamagePatterns: View { var completion: (DGMDamageVector) -> Void @State private var isNpcPickerPresented = false @Environment(\.self) private var environment @EnvironmentObject private var sharedState: SharedState var npcPicker: some View { NavigationView { NPCPickerGroup(parent: nil) { type in self.completion(type.npcDPS?.normalized ?? .omni) self.isNpcPickerPresented = false } .navigationBarItems(leading: BarButtonItems.close { self.isNpcPickerPresented = false }) } .modifier(ServicesViewModifier(environment: environment, sharedState: sharedState)) .navigationViewStyle(StackNavigationViewStyle()) } var body: some View { List { Button(action: {self.isNpcPickerPresented = true}) { Text("Select NPC").frame(maxWidth: .infinity, alignment: .center).frame(height: 30)}.contentShape(Rectangle()) DamagePatternsCustom(onSelect: completion) DamagePatternsPredefined(onSelect: completion) }.listStyle(GroupedListStyle()) .navigationBarTitle(Text("Damage Patterns")) .navigationBarItems(trailing: EditButton()) .sheet(isPresented: $isNpcPickerPresented) {self.npcPicker} } } #if DEBUG struct DamagePatterns_Previews: PreviewProvider { static var previews: some View { let gang = DGMGang.testGang() return NavigationView { DamagePatterns { _ in } } .environmentObject(gang) .modifier(ServicesViewModifier.testModifier()) } } #endif
lgpl-2.1
a4202323ff478e5d380a6824d578b86e
31.275862
126
0.642628
4.763359
false
false
false
false
nathantannar4/NTComponents
NTComponents/UI Kit/Alerts/NTProgressLineIndicator.swift
1
4008
// // NTProgressLineIndicator.swift // NTComponents // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 5/17/17. // public enum NTProgressIndicatorState { case standby, loading, canceled, completed } open class NTProgressLineIndicator: UIView { let progressLine: UIView = { let view = UIView() view.backgroundColor = Color.Default.Tint.View return view }() open var state: NTProgressIndicatorState = .standby // MARK: - Initialization public override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear } public convenience init() { var bounds = UIScreen.main.bounds bounds.origin.y = bounds.height - 4 bounds.size.height = 4 self.init(frame: bounds) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func prepare() { guard let parent = parentViewController else { return } anchor(parent.view.topAnchor, left: parent.view.leftAnchor, bottom: nil, right: parent.view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 4) addSubview(progressLine) progressLine.frame = CGRect(x: -100, y: 0, width: 100, height: 4) } open func invalidate() { state = .canceled removeFromSuperview() } open func updateProgress(percentage: CGFloat) { if state != .loading { prepare() } state = .loading UIView.animate(withDuration: 2, animations: { self.progressLine.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width * percentage, height: 4) }) { (success) in if percentage >= 100 { self.state = .completed self.progressDidComplete() } } } open func autoComplete(withDuration duration: Double) { if state != .loading { prepare() } state = .loading UIView.animate(withDuration: duration, animations: { self.progressLine.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 4) }) { (success) in self.state = .completed self.progressDidComplete() } } open func progressDidComplete() { if state == .completed { UIView.animate(withDuration: 0.4, animations: { self.frame.origin = CGPoint(x: 0, y: self.frame.origin.y - 4) }, completion: { (success) in if success { self.removeFromSuperview() } }) } else { Log.write(.warning, "NTProgressIndicator has not completed") } } }
mit
f3e931719a37f861c844003a7584073a
33.247863
219
0.619166
4.548241
false
false
false
false
thewebapprookie/MenuSerializationAPI-iOS
MenuSerializationAPI/MenuSerializationAPI/SampleViewController.swift
1
28307
// Some elements from SCLAlertView were used in this view, values were edited for customized appearance but not the functions nor the classes conformally to The MIT License (MIT) // SampleViewController.swift // MenuSerializationAPI // // Created by Fouad Medjekdoud on 9/6/15. // Copyright (c) 2015 TheWebAppRookie. All rights reserved. // import UIKit import CoreData import SCLAlertView class SampleViewController: UIViewController{ // let formatter = NSDateFormatter() var menu : UIView = UIView(frame: CGRectMake(0,0, 0, 0)) var menuViewCounter : Int = 0 override func viewWillAppear(animated: Bool) { if(menuViewCounter % 2 != 0){ menuViewCounter++ var menuFrame: CGRect = CGRectMake (self.view.frame.width, self.view.frame.height, 0, 0) menu.frame = menuFrame } } override func viewDidLoad() { super.viewDidLoad() //setting up NSUserDefaults data let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults() let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int if(isLoggedIn == 0){ println("Not Logged In") } if(prefs.stringForKey("data1") == nil){ prefs.setObject("100", forKey: "data1")} if(prefs.stringForKey("data2") == nil){ prefs.setObject("200", forKey: "data2")} prefs.synchronize() var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate) var context: NSManagedObjectContext = appDel.managedObjectContext! let enProject = NSEntityDescription.entityForName("Projects", inManagedObjectContext: context) var newProject = Project(entity: enProject!, insertIntoManagedObjectContext: context) newProject.project_name = "a chosen name" newProject.username = "you" newProject.data1 = "100" newProject.data2 = "200" context.save(nil) println("Data On Device\n\(newProject)") } ////////////////////// @IBAction func menuPopUp(sender: AnyObject) { menuViewCounter++ if(menuViewCounter % 2 == 0){ var menuFrame: CGRect = CGRectMake (self.view.frame.width, self.view.frame.height, 0, 0) menu.frame = menuFrame } else{ var menuFrame: CGRect = CGRectMake (self.view.frame.width - 160, self.view.frame.height - 264, 160, 264) menu.frame = menuFrame menu.backgroundColor = UIColor(red: 242/255.0, green: 242/255.0, blue: 242/255.0, alpha: 1.0) // menu.layer.cornerRadius = 10 menu.layer.masksToBounds = true menu.layer.borderWidth = 0.5 menu.layer.borderColor = UIColor.darkGrayColor().CGColor //reset calendar contents to 0 var deleteAllCalendar = UIButton.buttonWithType(UIButtonType.System) as! UIButton deleteAllCalendar.frame = CGRectMake(5, 10, 150, 25) deleteAllCalendar.setTitle("Clear Objects", forState: UIControlState.Normal) deleteAllCalendar.titleLabel?.font = UIFont(name: "Futura", size: 14) setBorderForMenuButton(deleteAllCalendar) deleteAllCalendar.addTarget(self, action: "deleteAllCalendar:", forControlEvents: UIControlEvents.TouchUpInside) //send to server button var sendServerButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton sendServerButton.frame = CGRectMake(5, 45, 150, 25) sendServerButton.setTitle("Backup to Server", forState: UIControlState.Normal) sendServerButton.titleLabel?.font = UIFont(name: "Futura", size: 14) setBorderForMenuButton(sendServerButton) sendServerButton.addTarget(self, action: "sendToServer:", forControlEvents: UIControlEvents.TouchUpInside) //get from server button var getServerButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton getServerButton.frame = CGRectMake(5, 80, 150, 25) getServerButton.setTitle("Restore from Server", forState: UIControlState.Normal) getServerButton.titleLabel?.font = UIFont(name: "Futura", size: 14) setBorderForMenuButton(getServerButton) getServerButton.addTarget(self, action: "getFromServer:", forControlEvents: UIControlEvents.TouchUpInside) // aboutButton var aboutButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton aboutButton.frame = CGRectMake(5, 115, 150,25) aboutButton.titleLabel?.font = UIFont(name: "Futura", size: 14) aboutButton.setTitle("About", forState: UIControlState.Normal) setBorderForMenuButton(aboutButton) //aboutButton.setImage(UIImage(named: "icon_information"), forState: .Normal) aboutButton.addTarget(self, action: "aboutButtonTap:", forControlEvents: UIControlEvents.TouchUpInside) // logoutButton var logoutButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton logoutButton.frame = CGRectMake(5, 185, 150, 25) logoutButton.setTitle("Logout", forState: UIControlState.Normal) logoutButton.titleLabel?.font = UIFont(name: "Futura", size: 14) setBorderForMenuButton(logoutButton) logoutButton.addTarget(self, action: "logoutButtonTap:", forControlEvents: UIControlEvents.TouchUpInside) // helpButton var helpButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton helpButton.frame = CGRectMake(5, 150, 150, 25) helpButton.setTitle("Help", forState: UIControlState.Normal) helpButton.titleLabel?.font = UIFont(name: "Futura", size: 14) setBorderForMenuButton(helpButton) helpButton.addTarget(self, action: "helpButtonTap:", forControlEvents: UIControlEvents.TouchUpInside) // aboutButton.backgroundColor = UIColor.lightGrayColor() menu.addSubview(aboutButton) menu.addSubview(helpButton) menu.addSubview(logoutButton) menu.addSubview(sendServerButton) menu.addSubview(getServerButton) menu.addSubview(deleteAllCalendar) //menu.delete(self) self.view.addSubview(menu) } } //method that defines the borders of the menu buttons func setBorderForMenuButton(myTxtButt: UIButton){ myTxtButt.layer.cornerRadius = 6.0 myTxtButt.layer.masksToBounds = true var borderColor: UIColor = UIColor(red: 0x7F/255.0, green: 0x4C/255.0, blue: 0x76/255.0, alpha: 1.0) myTxtButt.layer.borderWidth = 1.0 myTxtButt.layer.borderColor = borderColor.CGColor myTxtButt.backgroundColor = borderColor myTxtButt.setTitleColor(UIColor.whiteColor(), forState: .Normal) } func deleteAllCalendar(sender: UIButton!){ // resets the calendar section to 0 let alertDeleteCalendar = SCLAlertView() alertDeleteCalendar.addButton("Yes, Delete all"){ var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate) var context: NSManagedObjectContext = appDel.managedObjectContext! //fetch from the entities to delete data from var frequestNotes = NSFetchRequest(entityName: "Projects") //delete the objects in the NotesTracker entity var delProjects = context.executeFetchRequest(frequestNotes, error: nil) as! [Project] for project in delProjects{ context.deleteObject(project) } context.save(nil) //Instantiate an NSUserDefaults reference and remove stored data let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults() let appDomain: NSString = NSBundle.mainBundle().bundleIdentifier! prefs.removePersistentDomainForName(appDomain as String) // clear NSUserDefaults data self.resetCounters(prefs) let alertConfirmation = SCLAlertView() alertConfirmation.showInfo("Cleared!", subTitle: "Calendar data deleted.", closeButtonTitle: "OK", colorStyle: 0x7F4C76) self.navigationController?.popToRootViewControllerAnimated(true) } alertDeleteCalendar.showTitle("Clear Calendar!", subTitle: "Are you sure you want to delete all existing data linked to the Calendar including goals, days and notes?",style: .Warning, closeButtonTitle: "No", colorStyle: 0x7F4C76) } //function to reset the values from the UserDefaults //a function that serialize the data and send it over the wire func sendToServer(sender:UIButton!) { //sendToServerHTTP let alertBackUp = SCLAlertView() alertBackUp.addButton("Yes, BackUp"){ //creating a function that transforms the data into JSON let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults() //initializers let data1 = prefs.stringForKey("data1") let data2 = prefs.stringForKey("data2") ////////////TRANSFORMING ALL THE DATA INTO A JSON STRING BEFORE SENDING IT THROUGH THE WIRE /////// let jsonStart = "{" let jsonEnd = "}" let constantArray = "'constants': {'data1': '\(data1)', 'data2': '\(data2)'}" var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate) var context: NSManagedObjectContext = appDel.managedObjectContext! var projects = [Project]() var frequestProject = NSFetchRequest(entityName: "Projects") var frequestNotes = NSFetchRequest(entityName: "NotesTracker") var frequestDay = NSFetchRequest(entityName: "WriteDay") frequestProject.returnsObjectsAsFaults=false frequestNotes.returnsObjectsAsFaults=false frequestDay.returnsObjectsAsFaults=false var stringBuilder: String = "" // I will be transforming all the data into a JSON string var stringBuilderProjects: String = "" var num: Int = 0 //excecute fetch for Projects projects = context.executeFetchRequest(frequestProject, error: nil) as! [Project] var err: NSError? if(projects.count > 0){ stringBuilder += ", 'Projects': {" for project in projects{ if (num == projects.count-1){ // if the last project in storage is reached ////treating special characters that can corrupt the data (i.e: \, " and ' )//////// //the case of an apustrophe on a stored string (') var name = project.project_name.stringByReplacingOccurrencesOfString("'", withString: "Xxapustrophe-storage-solutionxX") //replaced it with a a string that will not interfear with the data. //the case of an doublequotes on a stored string (") name = name.stringByReplacingOccurrencesOfString("\"", withString: "Xxdoublequotes-storage-solutionxX") //replaced it with a a string that will not interfear with the data. //the case of a backslash on a stored string (\) name = name.stringByReplacingOccurrencesOfString("\\", withString: "Xxslash-storage-solutionxX") //Building up the string to have JSON structure stringBuilderProjects += "'\(num)': {'username': '\(project.username)', 'project_name': '\(name)', 'data1': '\(project.data1)', 'data2': '\(project.data2)'}}" //closed with }} because there is an open { a little above ( 'Projects': { ) }else{ //same as above but end the string with "}," instead of "}}" to add the next data var name = project.project_name.stringByReplacingOccurrencesOfString("'", withString: "Xxapustrophe-storage-solutionxX") name = name.stringByReplacingOccurrencesOfString("\"", withString: "Xxdoublequotes-storage-solutionxX") name = name.stringByReplacingOccurrencesOfString("\\", withString: "Xxslash-storage-solutionxX") stringBuilderProjects += "'\(num)': {'username': '\(project.username)', 'project_name': '\(name)', 'data1': '\(project.data1)', 'data2': '\(project.data2)'}, " } //counter of the number of objects serialized num++ } } stringBuilder += stringBuilderProjects stringBuilderProjects = "" // initialize to use for next fetch num = 0 // initialize for next fetch //excecute fetch for NotesTracker stringBuilder += stringBuilderProjects // In my case, the storage on the server was in the form (Storage: storedString) where stored string contains all the data of a user. let preJSON: String = "{\"storage\": \"" let afterJSON: String = "\"}" var finalJson = preJSON + jsonStart + constantArray + stringBuilder + jsonEnd + afterJSON println(finalJson) let paramsNSstring: NSString = finalJson as NSString let params = paramsNSstring.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) var url:NSURL = NSURL(string:"API_URL")! var session = NSURLSession.sharedSession() var request:NSMutableURLRequest = NSMutableURLRequest(URL: url) //var err: NSError? request.HTTPMethod = "POST" request.HTTPBody = params request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let token = KeychainWrapper.stringForKey("API_TOKEN") //securing the Token using KeychainWrapper request.addValue("Token \(token)", forHTTPHeaderField: "Authorization") //show loading... let alertWaiting = SCLAlertView() alertWaiting.showWait("Connecting!", subTitle: "Please wait...", closeButtonTitle: nil, colorStyle: 0x7F4C76) var alertMessage: String = "" var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in dispatch_async(dispatch_get_main_queue(), { println("Response: \(response)") if(response != nil){ var strData = NSString(data: data, encoding: NSUTF8StringEncoding) println("Body: \(strData)") var err: NSError? let res = response as! NSHTTPURLResponse! ///success if (res.statusCode >= 200 && res.statusCode < 300) { alertMessage = "Data sent successfully" }else{ alertMessage = "Unable to send data!" } alertWaiting.hideView() let alertConfirmation = SCLAlertView() alertConfirmation.showInfo("Connection!", subTitle: "\(alertMessage)", closeButtonTitle: "OK", colorStyle: 0x7F4C76) self.navigationController?.popToRootViewControllerAnimated(true) } else{ alertWaiting.hideView() let alertConfirmation = SCLAlertView() alertConfirmation.showInfo("Failed!", subTitle: "Could not connect to the server", closeButtonTitle: "OK", colorStyle: 0x7F4C76) } }) }) task.resume() } // alertBackUp.showTitle("Backup!", subTitle: "The data on your device will replace the previous online Backup. Are you sure you want to proceed?",style: .Warning, closeButtonTitle: "Cancel", colorStyle: 0x7F4C76) println("sendToServerTapped") // println("just a try {" + "{another one") } //get the data from the server and store it into CoreData func getFromServer(sender:UIButton!) {//getFromServerHTTP let alertRestore = SCLAlertView() alertRestore.addButton("Yes, Restore"){ var url:NSURL = NSURL(string:"API_URL")! var session = NSURLSession.sharedSession() var request:NSMutableURLRequest = NSMutableURLRequest(URL: url) //var err: NSError? request.HTTPMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") //call the token for a secure location let token = KeychainWrapper.stringForKey("API_TOKEN") request.addValue("Token \(token)", forHTTPHeaderField: "Authorization") //show loading... let alertWaiting = SCLAlertView() alertWaiting.showWait("Connecting!", subTitle: "Please wait...", closeButtonTitle: nil, colorStyle: 0x7F4C76) var alertMessage: String = "No Data!" var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in dispatch_async(dispatch_get_main_queue(), { println("Response: \(response)") if (response != nil){ let res = response as? NSHTTPURLResponse ///success if (res!.statusCode >= 200 && res!.statusCode < 300){ var strData : NSString = NSString(data: data, encoding: NSUTF8StringEncoding)! println("Body: \(strData)") var err: NSError? let string: String = strData as! String //the data coming from the server has the form of "{'column': {'row1', 'row2'...}}" But I want it to have JSON format so //first I replace all the ' with " var replacement = string.stringByReplacingOccurrencesOfString("'", withString: "\"") //then I take away the " at the beginning of the string replacement = dropFirst(replacement) //then I take away the " at the end of the string replacement = dropLast(replacement) //now that the string has JSON structure, convert it inot NSData var newData: NSString = replacement println(newData) let data2 = newData.dataUsingEncoding(NSUTF8StringEncoding) //then serialize it let json = NSJSONSerialization.JSONObjectWithData(data2!, options: nil, error: &err) as! NSDictionary // distributing the data to the CoreData var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate) var context: NSManagedObjectContext = appDel.managedObjectContext! var frequestProject = NSFetchRequest(entityName: "Projects") //deleting the previous content from entities var delProjects = context.executeFetchRequest(frequestProject, error: nil) as! [Project] for project in delProjects{ context.deleteObject(project) } context.save(nil) let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults() let appDomain: NSString = NSBundle.mainBundle().bundleIdentifier! prefs.removePersistentDomainForName(appDomain as String) //initializers //reset the login tools //deploying constants self.resetCounters(prefs) //deserialization if let jsonT: AnyObject = json.objectForKey("Projects") { let projList = json.objectForKey("Projects") as! NSDictionary println(projList) for (var i = 0; i < projList.count; i++) { let enProject = NSEntityDescription.entityForName("Projects", inManagedObjectContext: context) var newProject = Project(entity: enProject!, insertIntoManagedObjectContext: context) let formatter = NSDateFormatter() newProject.username = (projList.objectForKey("\(i)") as! NSDictionary).valueForKey("username") as! String var replacementName = ((projList.objectForKey("\(i)") as! NSDictionary).valueForKey("project_name") as! String ) //Restoring the \, ', " to their original values replacementName = replacementName.stringByReplacingOccurrencesOfString("Xxapustrophe-storage-solutionxX", withString: "'") replacementName = replacementName.stringByReplacingOccurrencesOfString("Xxslash-storage-solutionxX", withString: "\\") replacementName = replacementName.stringByReplacingOccurrencesOfString("Xxdoublequotes-storage-solutionxX", withString: "\"") println("replacementName: \(replacementName)") newProject.project_name = replacementName newProject.data1 = (projList.objectForKey("\(i)") as! NSDictionary).valueForKey("data1") as! String newProject.data2 = (projList.objectForKey("\(i)") as! NSDictionary).valueForKey("data2") as! String } } context.save(nil) //self.viewDidAppear(true) //self.viewDidLoad() //;; alertMessage = "Data received successfully!" } alertWaiting.hideView() let alertConfirmation = SCLAlertView() alertConfirmation.showInfo("Connection!", subTitle: "\(alertMessage)", closeButtonTitle: "OK", colorStyle: 0x7F4C76) self.navigationController?.popToRootViewControllerAnimated(true) } else{ alertWaiting.hideView() let alertConfirmation = SCLAlertView() alertConfirmation.showInfo("Failure!", subTitle: "Could not connect to the server", closeButtonTitle: "OK", colorStyle: 0x7F4C76) }}) }) task.resume() } alertRestore.showTitle("Restore!", subTitle: "The data on your device will be erased and replaced by the previous online Backup. Are you sure you want to proceed?",style: .Warning, closeButtonTitle: "No", colorStyle: 0x7F4C76) println("getFromServerTapped") } func aboutButtonTap(sender:UIButton!) { println("about tapped") } func helpButtonTap(sender:UIButton!) { println("help tapped") } func logoutButtonTap(sender:UIButton!) { let alertConfirmation = SCLAlertView() alertConfirmation.addButton("Yes, Log out"){ let appDomain = NSBundle.mainBundle().bundleIdentifier NSUserDefaults.standardUserDefaults().removeObjectForKey("ISLOGGEDIN") println("logged out") self.navigationController?.popToRootViewControllerAnimated(true) } alertConfirmation.showInfo("Log out!", subTitle: "Are you sure you want to log out?", closeButtonTitle: "No", colorStyle: 0x7F4C76) println("logout tapped") } //function depends on what data do you use func resetCounters(prefs : NSUserDefaults){ prefs.setInteger(1, forKey: "ISLOGGEDIN") prefs.setObject(String(0), forKey: "data") prefs.setObject(String(0), forKey: "data2") prefs.synchronize() } }
mit
e3c350bfd102f1b42dd7ac256717813c
46.735245
259
0.522026
6.172481
false
false
false
false
DesenvolvimentoSwift/Taster
Taster/GeonamesPOIXMLParserDelegate.swift
1
1812
// // GeonamesPOI+XML.swift // pt.fca.Taster // // © 2016 Luis Marcelino e Catarina Silva // Desenvolvimento em Swift para iOS // FCA - Editora de Informática // import Foundation import CoreLocation class GeonamesPOIXMLParserDelegate: NSObject, XMLParserDelegate { var POIs:[GeonamesPOI]? var currentTag:String? var values = [String:String]() func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { currentTag = elementName } func parser(_ parser: XMLParser, foundCharacters string: String) { guard let tag = currentTag else { return; } if let currentValue = values[tag] { values[tag] = currentValue + string } else { values[tag] = string } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if elementName == "poi" { if let name = values["name"] { if let typeName = values["typeName"] { if let latStr = values["lat"] { if let lngStr = values["lng"] { let poi = GeonamesPOI(name: name, typeName: typeName, coordinate: CLLocationCoordinate2D(latitude: Double(latStr)!, longitude: Double(lngStr)!)) if POIs == nil { POIs = [] } POIs!.append(poi) } } } } values = [:] // limpar os valores extraidos } else { currentTag = nil } } }
mit
c4c1ddc1a63ae5fd29ca30de6e362992
30.206897
173
0.529834
4.826667
false
false
false
false
MilanNosal/InteractiveTransitioningContainer
InteractiveTransitioningContainer/SwipeToSlideTabBarChildController.swift
1
998
// // SwipeToSlideTabBarChildController.swift // InteractiveTransitioningContainer // // Created by Milan Nosáľ on 06/03/2017. // Copyright © 2017 Svagant. All rights reserved. // import Foundation public struct SwipeToSlideTabBarItem { let title: String let image: UIImage let backgroundColor: UIColor public init(title: String, image: UIImage, backgroundColor: UIColor) { self.title = title self.image = image self.backgroundColor = backgroundColor } } public struct SwipeToSlideTabBarChildController { let tabBarItem: SwipeToSlideTabBarItem let childViewController: UIViewController public init(tabBarItemTitle: String, tabBarItemImage: UIImage, tabBarBackgroundColor: UIColor, childViewController: UIViewController) { self.tabBarItem = SwipeToSlideTabBarItem(title: tabBarItemTitle, image: tabBarItemImage, backgroundColor: tabBarBackgroundColor) self.childViewController = childViewController } }
mit
f27d28d009cfe4dff69510d8de0254d2
31.096774
139
0.749749
4.877451
false
false
false
false
khizkhiz/swift
test/type/types.swift
2
4330
// RUN: %target-parse-verify-swift var a : Int func test() { var y : a // expected-error {{use of undeclared type 'a'}} expected-note {{here}} var z : y // expected-error {{'y' is not a type}} } var b : Int -> Int = { $0 } var c2 : (field : Int) // expected-error {{cannot create a single-element tuple with an element label}}{{11-19=}} var d2 : () -> Int = { 4 } var d3 : () -> Float = { 4 } var d4 : () -> Int = { d2 } // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}} {{26-26=()}} var e0 : [Int] e0[] // expected-error {{cannot subscript a value of type '[Int]' with an index of type '()'}} // expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (Int), (Range<Int>), (Range<Self.Index>)}} var f0 : [Float] var f1 : [(Int,Int)] var g : Swift // expected-error {{use of undeclared type 'Swift'}} expected-note {{cannot use module 'Swift' as a type}} var h0 : Int? _ = h0 == nil // no-warning var h1 : Int?? _ = h1! == nil // no-warning var h2 : [Int?] var h3 : [Int]? var h3a : [[Int?]] var h3b : [Int?]? var h4 : ([Int])? var h5 : ([([[Int??]])?])? var h7 : (Int,Int)? var h8 : (Int -> Int)? var h9 : Int? -> Int? var h10 : Int?.Type?.Type var i = Int?(42) var bad_io : (Int) -> (inout Int, Int) // expected-error {{'inout' is only valid in parameter lists}} func bad_io2(a: (inout Int, Int)) {} // expected-error {{'inout' is only valid in parameter lists}} // <rdar://problem/15588967> Array type sugar default construction syntax doesn't work func test_array_construct<T>(_: T) { _ = [T]() // 'T' is a local name _ = [Int]() // 'Int is a global name' _ = [UnsafeMutablePointer<Int>]() // UnsafeMutablePointer<Int> is a specialized name. _ = [UnsafeMutablePointer<Int?>]() // Nesting. _ = [([UnsafeMutablePointer<Int>])]() _ = [(String, Float)]() } extension Optional { init() { self = .none } } // <rdar://problem/15295763> default constructing an optional fails to typecheck func test_optional_construct<T>(_: T) { _ = T?() // Local name. _ = Int?() // Global name _ = (Int?)() // Parenthesized name. } // Test disambiguation of generic parameter lists in expression context. struct Gen<T> {} var y0 : Gen<Int?> var y1 : Gen<Int??> var y2 : Gen<[Int?]> var y3 : Gen<[Int]?> var y3a : Gen<[[Int?]]> var y3b : Gen<[Int?]?> var y4 : Gen<([Int])?> var y5 : Gen<([([[Int??]])?])?> var y7 : Gen<(Int,Int)?> var y8 : Gen<(Int -> Int)?> var y8a : Gen<[[Int]? -> Int]> var y9 : Gen<Int? -> Int?> var y10 : Gen<Int?.Type?.Type> var y11 : Gen<Gen<Int>?> var y12 : Gen<Gen<Int>?>? var y13 : Gen<Gen<Int?>?>? var y14 : Gen<Gen<Int?>>? var y15 : Gen<Gen<Gen<Int?>>?> var y16 : Gen<Gen<Gen<Int?>?>> var y17 : Gen<Gen<Gen<Int?>?>>? var z0 = Gen<Int?>() var z1 = Gen<Int??>() var z2 = Gen<[Int?]>() var z3 = Gen<[Int]?>() var z3a = Gen<[[Int?]]>() var z3b = Gen<[Int?]?>() var z4 = Gen<([Int])?>() var z5 = Gen<([([[Int??]])?])?>() var z7 = Gen<(Int,Int)?>() var z8 = Gen<(Int -> Int)?>() var z8a = Gen<[[Int]? -> Int]>() var z9 = Gen<Int? -> Int?>() var z10 = Gen<Int?.Type?.Type>() var z11 = Gen<Gen<Int>?>() var z12 = Gen<Gen<Int>?>?() var z13 = Gen<Gen<Int?>?>?() var z14 = Gen<Gen<Int?>>?() var z15 = Gen<Gen<Gen<Int?>>?>() var z16 = Gen<Gen<Gen<Int?>?>>() var z17 = Gen<Gen<Gen<Int?>?>>?() y0 = z0 y1 = z1 y2 = z2 y3 = z3 y3a = z3a y3b = z3b y4 = z4 y5 = z5 y7 = z7 y8 = z8 y8a = z8a y9 = z9 y10 = z10 y11 = z11 y12 = z12 y13 = z13 y14 = z14 y15 = z15 y16 = z16 y17 = z17 // Type repr formation. // <rdar://problem/20075582> Swift does not support short form of dictionaries with tuples (not forming TypeExpr) let tupleTypeWithNames = (age:Int, count:Int)(4, 5) let dictWithTuple = [String: (age:Int, count:Int)]() // <rdar://problem/21684837> typeexpr not being formed for postfix ! let bb2 = [Int!](repeating: nil, count: 2) // <rdar://problem/21560309> inout allowed on function return type func r21560309<U>(body: (_: inout Int) -> inout U) {} // expected-error {{'inout' is only valid in parameter lists}} r21560309 { x in x } // <rdar://problem/21949448> Accepts-invalid: 'inout' shouldn't be allowed on stored properties class r21949448 { var myArray: inout [Int] = [] // expected-error {{'inout' is only valid in parameter lists}} }
apache-2.0
0eab566f67d21dbeb187ec261e92033f
26.579618
146
0.595381
2.750953
false
false
false
false
Finb/V2ex-Swift
View/V2PhotoBrowser/V2PhotoBrowserTransionPresent.swift
1
2209
// // V2PhotoBrowserTransionPresent.swift // V2ex-Swift // // Created by huangfeng on 2/26/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit class V2PhotoBrowserTransionPresent:NSObject,UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as! V2PhotoBrowser let container = transitionContext.containerView container.addSubview(toVC.view) //给引导动画赋值 if let delegate = toVC.delegate{ toVC.guideImageView.frame = delegate.guideFrameInPhotoBrowser(toVC, index: toVC.currentPageIndex) toVC.guideImageView.image = delegate.guideImageInPhotoBrowser(toVC, index: toVC.currentPageIndex) toVC.guideImageView.contentMode = delegate.guideContentModeInPhotoBrowser(toVC, index: toVC.currentPageIndex) } //显示引导动画的imageView toVC.guideImageViewHidden(false) UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: UIView.AnimationOptions(), animations: { () -> Void in toVC.view.backgroundColor = UIColor(white: 0, alpha: 1) toVC.guideImageView.frame = toVC.view.bounds //如果图片过小,则直接中间原图显示 ,否则fit if let width = toVC.guideImageView.originalImage?.size.width, let height = toVC.guideImageView.originalImage?.size.height, width > SCREEN_WIDTH || height > SCREEN_HEIGHT { toVC.guideImageView.contentMode = .scaleAspectFit } else{ toVC.guideImageView.contentMode = .center } }) { (finished: Bool) -> Void in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) //隐藏引导动画 toVC.guideImageViewHidden(true) } } }
mit
7794a3712ec253da14ddd9b52018d90c
43.375
184
0.673709
5.144928
false
false
false
false
garygriswold/Bible.js
OBSOLETE/YourBible/plugins/com-shortsands-aws/src/ios/AWS/AwsS3.swift
1
16714
// // AwsS3.swift // AWS_S3_Prototype // // Created by Gary Griswold on 5/15/17. // Copyright © 2017 ShortSands. All rights reserved. // import Foundation import AWSCore public class AwsS3 { private let region: AwsS3Region private let transfer: AWSS3TransferUtility private var userAgent: String? = nil public init(region: AwsS3Region) { self.region = region let endpoint = AWSEndpoint(region: region.type, service: AWSServiceType.S3, useUnsafeURL: false)! let credentialProvider = Credentials.AWS_BIBLE_APP let configuration = AWSServiceConfiguration(region: region.type, endpoint: endpoint, credentialsProvider: credentialProvider) let transferUtility = AWSS3TransferUtilityConfiguration() AWSS3TransferUtility.register( with: configuration!, transferUtilityConfiguration: transferUtility, forKey: self.region.name ) self.transfer = AWSS3TransferUtility.s3TransferUtility(forKey: self.region.name) } deinit { print("****** deinit AwsS3 ******") } /** * A Unit Test Method */ public func echo3(message: String) -> String { return message; } ///////////////////////////////////////////////////////////////////////// // URL signing Functions ///////////////////////////////////////////////////////////////////////// /** * This method produces a presigned URL for a GET from an AWS S3 bucket */ public func preSignedUrlGET(s3Bucket: String, s3Key: String, expires: Int, complete: @escaping (_ url:URL?) -> Void) { let request = AWSS3GetPreSignedURLRequest() request.httpMethod = AWSHTTPMethod.GET request.bucket = s3Bucket request.key = s3Key request.expires = Date(timeIntervalSinceNow: TimeInterval(expires)) presignURL(request: request, complete: complete) } /** * This method produces a presigned URL for a PUT to an AWS S3 bucket */ public func preSignedUrlPUT(s3Bucket: String, s3Key: String, expires: Int, contentType: String, complete: @escaping (_ url:URL?) -> Void) { let request = AWSS3GetPreSignedURLRequest() request.httpMethod = AWSHTTPMethod.PUT request.bucket = s3Bucket request.key = s3Key request.expires = Date(timeIntervalSinceNow: TimeInterval(expires)) request.contentType = contentType presignURL(request: request, complete: complete) } /** * This private method is the actual preSignedURL call */ private func presignURL(request: AWSS3GetPreSignedURLRequest, complete: @escaping (_ url:URL?) -> Void) { let builder = AWSS3PreSignedURLBuilder.default() builder.getPreSignedURL(request).continueWith { (task) -> URL? in if let error = task.error { print("Error: \(error)") complete(nil) } else { let presignedURL = task.result! complete(presignedURL as URL) } return nil } } ///////////////////////////////////////////////////////////////////////// // Download Functions ///////////////////////////////////////////////////////////////////////// /** * Download Text to String object */ public func downloadText(s3Bucket: String, s3Key: String, complete: @escaping (_ error:Error?, _ data:String?) -> Void) { let completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock = {(task, url, data, error) -> Void in DispatchQueue.main.async(execute: { if let err = error { print("ERROR in s3.downloadText \(s3Bucket) \(s3Key) Error: \(err)") } else { print("SUCCESS in s3.downloadText \(s3Bucket) \(s3Key)") } let datastring = (data != nil) ? String(data: data!, encoding: String.Encoding.utf8) as String? : "" complete(error, datastring) }) } self.transfer.downloadData(fromBucket: s3Bucket, key: s3Key, expression: nil, completionHandler: completionHandler) } /** * Download Binary object to Data, receiving code might need to convert it needed form */ public func downloadData(s3Bucket: String, s3Key: String, complete: @escaping (_ error:Error?, _ data:Data?) -> Void) { let completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock = {(task, url, data, error) -> Void in DispatchQueue.main.async(execute: { if let err = error { print("ERROR in s3.downloadData \(s3Bucket) \(s3Key) Error: \(err)") } else { print("SUCCESS in s3.downloadData \(s3Bucket) \(s3Key)") } complete(error, data) }) } self.transfer.downloadData(fromBucket: s3Bucket, key: s3Key, expression: nil, completionHandler: completionHandler) } /** * Download File. This works for binary and text files. This method does not use * TransferUtility.fileDownload, because it is unable to provide accurate errors * when the file IO fails. */ public func downloadFile(s3Bucket: String, s3Key: String, filePath: URL, complete: @escaping (_ error:Error?) -> Void) { let completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock = {(task, url, data, error) in DispatchQueue.main.async(execute: { if let err = error { print("ERROR in s3.downloadFile \(s3Bucket) \(s3Key) Error: \(err)") } else { print("SUCCESS in s3.downloadFile \(s3Bucket) \(s3Key)") } complete(error) }) } self.transfer.download(to: filePath, bucket: s3Bucket, key: s3Key, expression: nil, completionHandler: completionHandler) //.continueWith has been dropped, because it did not report errors } /** * Download zip file and unzip it. When the optional view parameter is set a deterministic * progress circle is displayed. */ public func downloadZipFile(s3Bucket: String, s3Key: String, filePath: URL, view: UIView?, complete: @escaping (_ error:Error?) -> Void) { let bucket = regionalizeBucket(bucket: s3Bucket) let temporaryDirectory: URL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) print("Temp Zip File Directory \(temporaryDirectory.absoluteString)") // Identify temp file for zip file download let tempZipURL = temporaryDirectory.appendingPathComponent(NSUUID().uuidString + ".zip") print("temp URL to store file \(tempZipURL.absoluteString)") let expression = AWSS3TransferUtilityDownloadExpression() expression.setValue(self.getUserAgent(), forRequestHeader: "User-Agent") let progressCircle = ProgressCircle() if let vue = view { progressCircle.addToParentAndCenter(view: vue) expression.progressBlock = {(task, progress) in DispatchQueue.main.async(execute: { progressCircle.progress = CGFloat(progress.fractionCompleted) if progress.isFinished || progress.isCancelled { progressCircle.remove() } })} } let completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock = {(task, url, data, error) -> Void in DispatchQueue.main.async(execute: { if let err = error { print("ERROR in s3.downloadZipFile \(bucket) \(s3Key) Error: \(err)") progressCircle.remove() complete(err) } else { print("Download SUCCESS in s3.downloadZipFile \(bucket) \(s3Key)") do { var unzippedURL: URL = URL(fileURLWithPath: "") // unzip zip file try Zip.unzipFile(tempZipURL, destination: temporaryDirectory, overwrite: true, password: nil, progress: nil, fileOutputHandler: { unzippedFile in print("Unipped File \(unzippedFile)") unzippedURL = URL(fileURLWithPath: unzippedFile.absoluteString) } ) // remove unzipped file if it already exists self.removeItemNoThrow(at: filePath) // move unzipped file to destination try FileManager.default.moveItem(at: unzippedURL, to: filePath) print("SUCCESS in s3.downloadZipFile \(bucket) \(s3Key)") complete(nil) } catch let cotError { print("ERROR in s3.downloadZipFile \(bucket) \(s3Key) Error: \(cotError)") progressCircle.remove() complete(cotError) } self.removeItemNoThrow(at: tempZipURL) } }) } self.transfer.download(to: tempZipURL, bucket: bucket, key: s3Key, expression: expression, completionHandler: completionHandler) //.continueWith has been dropped, because it did not report errors } private func removeItemNoThrow(at: URL) -> Void { do { try FileManager.default.removeItem(at: at) } catch let error { print("Deleteion of \(at) Failed \(error.localizedDescription)") } } ///////////////////////////////////////////////////////////////////////// // Upload Functions ///////////////////////////////////////////////////////////////////////// /** * Upload Analytics from a Dictionary, that is converted to JSON. */ public func uploadAnalytics(sessionId: String, timestamp: String, prefix: String, dictionary: [String: String], complete: @escaping (_ error: Error?) -> Void) { var message: Data do { message = try JSONSerialization.data(withJSONObject: dictionary, options: JSONSerialization.WritingOptions.prettyPrinted) } catch let jsonError { print("ERROR while converting message to JSON \(jsonError)") let errorMessage = "{\"Error\": \"AwsS3.uploadAnalytics \(jsonError.localizedDescription)\"}" message = errorMessage.data(using: String.Encoding.utf8)! } // debug print("message \(String(describing: String(data: message, encoding: String.Encoding.utf8)))") uploadAnalytics(sessionId: sessionId, timestamp: timestamp, prefix: prefix, json: message, complete: complete) } /** * Upload Analytics from a JSON text String in Data form. This one is intended for the Cordova Plugin to use */ public func uploadAnalytics(sessionId: String, timestamp: String, prefix: String, json: Data, complete: @escaping (_ error: Error?) -> Void) { //let s3Bucket = "analytics-" + self.endpoint.regionName + "-shortsands" let s3Bucket = "analytics-" + self.region.name + "-shortsands" let s3Key = sessionId + "-" + timestamp let jsonPrefix = "{\"" + prefix + "\": " let jsonSuffix = "}" var message: Data = jsonPrefix.data(using: String.Encoding.utf8)! message.append(json) message.append(jsonSuffix.data(using: String.Encoding.utf8)!) uploadData(s3Bucket: s3Bucket, s3Key: s3Key, data: message, contentType: "application/json", complete: complete) } /** * Upload string object to bucket */ public func uploadText(s3Bucket: String, s3Key: String, data: String, contentType: String, complete: @escaping (_ error: Error?) -> Void) { let textData = data.data(using: String.Encoding.utf8) uploadData(s3Bucket: s3Bucket, s3Key: s3Key, data: textData!, contentType: contentType, complete: complete) } /** * Upload object in Data form to bucket. Data must be prepared to correct form * before calling this function. */ public func uploadData(s3Bucket: String, s3Key: String, data: Data, contentType: String, complete: @escaping (_ error: Error?) -> Void) { let completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock = {(task, error) -> Void in DispatchQueue.main.async(execute: { if let err = error { print("ERROR in s3.uploadData \(s3Bucket) \(s3Key) Error: \(err)") } else { print("SUCCESS in s3.uploadData \(s3Bucket) \(s3Key)") } complete(error) }) } self.transfer.uploadData(data, bucket: s3Bucket, key: s3Key, contentType: contentType, expression: nil, completionHandler: completionHandler) //.continueWith has been dropped, because it did not report errors } /** * Upload file to bucket, this works for text or binary files * Warning: This method is only included to permit symmetric testing of download/upload * It does not use the uploadFile method of TransferUtility, but uploads data. * So, it should not be used for large object unless it is fixed. I was not * able to get the uploadFile method of TransferUtility to work */ public func uploadFile(s3Bucket: String, s3Key: String, filePath: URL, contentType: String, complete: @escaping (_ error: Error?) -> Void) { do { let data = try Data(contentsOf: filePath, options: Data.ReadingOptions.uncached) uploadData(s3Bucket: s3Bucket, s3Key: s3Key, data: data, contentType: contentType, complete: complete) } catch let cotError { print("ERROR in s3.uploadFile, while reading file \(s3Bucket) \(s3Key) \(cotError.localizedDescription)") complete(cotError) } } private func getUserAgent() -> String { if (self.userAgent == nil) { var result: [String] = [] result.append("v1") result.append(Locale.current.identifier) result.append(Locale.preferredLanguages.joined(separator: ",")) let device = UIDevice.current result.append("Apple") result.append(device.model) result.append("ios") result.append(device.systemVersion) let info = Bundle.main.infoDictionary result.append(info?["CFBundleIdentifier"] as? String ?? "") result.append(info?["CFBundleShortVersionString"] as? String ?? "") self.userAgent = result.joined(separator: ":") } return self.userAgent! } private func regionalizeBucket(bucket: String) -> String { let bucket2: NSString = bucket as NSString if bucket2.contains("oldregion") { switch(self.region.type) { case AWSRegionType.USEast1: return bucket2.replacingOccurrences(of: "oldregion", with: "na-va") case AWSRegionType.EUWest1: return bucket2.replacingOccurrences(of: "oldregion", with: "eu-ie") case AWSRegionType.APNortheast1: return bucket2.replacingOccurrences(of: "oldregion", with: "as-jp") case AWSRegionType.APSoutheast1: return bucket2.replacingOccurrences(of: "oldregion", with: "as-sg") case AWSRegionType.APSoutheast2: return bucket2.replacingOccurrences(of: "oldregion", with: "oc-au") default: return bucket2.replacingOccurrences(of: "oldregion", with: "na-va") } } if bucket2.contains("region") { return bucket2.replacingOccurrences(of: "region", with: self.region.name) } return bucket } }
mit
c4c60aa610b1ad5361a934453cacf885
46.078873
120
0.563214
4.930088
false
false
false
false
taqun/HBR
HBR/Classes/ViewController/MyBookmarksTableViewController.swift
1
5807
// // MyBookmarksTableViewController.swift // HBR // // Created by taqun on 2015/05/02. // Copyright (c) 2015年 envoixapp. All rights reserved. // import UIKit import CoreData class MyBookmarksTableViewController: SegmentedDisplayTableViewController, NSFetchedResultsControllerDelegate, UIAlertViewDelegate { private var fetchedResultController: NSFetchedResultsController! // MARK: - Initialize override func viewDidLoad() { super.viewDidLoad() // navigation bar let backBtn = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: self, action: nil) self.navigationItem.backBarButtonItem = backBtn // tableview self.clearsSelectionOnViewWillAppear = true self.tableView.registerNib(UINib(nibName: "MyBookmarksTableViewCell", bundle: nil), forCellReuseIdentifier: "MyBookmarksCell") self.refreshControl = UIRefreshControl() self.refreshControl?.addTarget(self, action: Selector("didRefreshControlChanged"), forControlEvents: UIControlEvents.ValueChanged) NSFetchedResultsController.deleteCacheWithName("MyBookmarksCache") self.initFetchedResultsController() var error:NSError? if !self.fetchedResultController.performFetch(&error) { println(error) } } // MARK: - Private Method private func initFetchedResultsController() { if self.fetchedResultController != nil{ return } let channel = ModelManager.sharedInstance.myBookmarksChannel var fetchRequest = Item.requestAllSortBy("date", ascending: false) fetchRequest.predicate = NSPredicate(format: "ANY channels = %@", channel) let context = CoreDataManager.sharedInstance.managedObjectContext! self.fetchedResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: "MyBookmarksCache") self.fetchedResultController.delegate = self } private func updateVisibleCells() { var cells = self.tableView.visibleCells() as! [FeedTableViewCell] for cell: FeedTableViewCell in cells { cell.updateView() } } @objc private func didRefreshControlChanged() { UserManager.sharedInstance.loadMyBookmarks() } @objc private func myBookmarksLoaded() { self.refreshControl?.endRefreshing() let channel = ModelManager.sharedInstance.myBookmarksChannel self.allItemNum = channel.items.count self.tableView.reloadData() } // MARK: - UIViewController Method override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let username = UserManager.sharedInstance.username { self.title = username + "のブックマーク" } else { self.title = "ブックマーク" } // tableView self.updateVisibleCells() let channel = ModelManager.sharedInstance.myBookmarksChannel self.allItemNum = channel.items.count NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("myBookmarksLoaded"), name: Notification.MY_BOOKMARKS_LOADED, object: nil) Logger.sharedInstance.track("MyBookmarkItemListView") } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if !UserManager.sharedInstance.isLoggedIn { let alert = UIAlertView(title: "はてなブックーマークに\nログインしていません。", message: "設定画面からログインしてください。", delegate: self, cancelButtonTitle: "OK") alert.show() } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - UITableViewDataSource Protocol override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("MyBookmarksCell") as! MyBookmarksTableViewCell! if cell == nil { cell = MyBookmarksTableViewCell() } let item = self.fetchedResultController.objectAtIndexPath(indexPath) as! Item cell.setFeedItem(item) return cell } // MARK: - UITableViewDelegate Protocol override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let item = self.fetchedResultController.objectAtIndexPath(indexPath) as! Item let webViewController = WebViewController(item: item) self.navigationController?.pushViewController(webViewController, animated: true) } // MARK: - NSFetchedResultsControllerDelegate Protocol func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } // MARK: - UIAlertViewDelegate Protocol func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { self.navigationController?.popViewControllerAnimated(true) } }
mit
9a42c0cc3d283884f450fa0558225a43
32.535294
180
0.672864
5.799593
false
false
false
false
openhab/openhab.ios
openHABWatch Extension/NotificationController.swift
1
1671
// Copyright (c) 2010-2022 Contributors to the openHAB project // // See the NOTICE file(s) distributed with this work for additional // information. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0 // // SPDX-License-Identifier: EPL-2.0 import SwiftUI import UserNotifications import WatchKit class NotificationController: WKUserNotificationHostingController<NotificationView> { var title: String? var message: String? let openHABMessageIndexKey = "openHABMessageIndex" override var body: NotificationView { NotificationView(customTextLabel: title, customDetailTextLabel: message) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } override func didReceive(_ notification: UNNotification) { // This method is called when a notification needs to be presented. _ = UserData() let notificationData = notification.request.content.userInfo as? [String: Any] let aps = notificationData?["aps"] as? [String: Any] let alert = aps?["alert"] as? [String: Any] title = alert?["title"] as? String message = alert?["body"] as? String // if let index = notificationData?[openHABMessageIndexKey] as? Int { // landmark = userData.landmarks[index] // } } }
epl-1.0
855cad77d66ebf1f2482ce07353d0d7b
29.944444
90
0.687014
4.641667
false
false
false
false
SnapBlog/iOS-Development
Основы Swift от SnapBlog.playground/Pages/Перечисления и Структуры.xcplaygroundpage/Contents.swift
1
5567
//: # Курс "Swift-Drift" от [SnapBlog](http://snapblog.ru) //: //: ## Перечисления и Структуры //: //: Классы не являются единственным способом определения типов данных в Swift. Перечисления и структуры имеют аналогичные возможности классов, но могут быть более полезными в различных случаях. //: //: _Перечисления_ определяют общий тип для группы связанных значений и позволяют работать с этими значениями в типобезопасном режиме в вашем коде. Перечисления могут иметь методы, связанные с ними. //: //: Используйте `enum` для создания перечисления. //: enum Rank: Int { case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queen" case .King: return "king" default: return String(self.rawValue) } } } let ace = Rank.Ace let aceRawValue = ace.rawValue //: В приведенном выше примере, начальное значение (rawValue - “сырое” значение) перечисления является `Int`, так что вы должны указать только первое начальное значение. Остальные начальные значения присваиваются по порядку (мы указали для Ace = 1, далее Two будет равно 2, Three = 3 и т.д.). Вы также можете использовать строку или число с плавающей точной в качестве начального значения перечисления. Используйте свойство `rawValue` для доступа к начальному значению члена перечисления. //: //: Используйте `init?(rawValue:)` инициализатор, чтобы создать экземпляр перечисления из начального значения. //: if let convertedRank = Rank(rawValue: 3) { let threeDescription = convertedRank.simpleDescription() } //: Значения членов перечисления являются фактическими значениями, а не еще одним способом записи их начальных значений. В самом деле, в тех случаях, когда нет смысла в начальном значении, вы не должны его предоставлять. //: enum Suit { case Spades, Hearts, Diamonds, Clubs func simpleDescription() -> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } } let hearts = Suit.Hearts let heartsDescription = hearts.simpleDescription() //: Обратите внимание на два пути обращения к члену перечисления `Hearts`: когда значение присваивается константе `hearts`, обращение (ссылка) к члену перечисления `Suit.Hearts` осуществляется по полному имени, потому что константа не имеет явно указанного типа. Внутри switch, обращение к члену перечисления осуществляется в сокровенной форме `.Hearts`, потому что `self` значение уже известно. Вы можете использовать сокращенную форму в любое время, когда известен тип значения. //: //: _Структуры_ очень похожи на классы, включая методы и инициализаторы. Одно из наиболее важных различий между структурами и классами это то, что структуры всегда копируются, если они где-то передаются в вашем коде, а передача классов осуществляется по ссылке (они не копируются). Структуры отлично подходят для определения легких типов данных, которым не нужны такие возможности, как наследование и приведение типов. //: //: Используйте `struct` для создания структуры. //: struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } } let threeOfSpades = Card(rank: .Three, suit: .Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription() //: //: //: [Назад](@previous) | [Далее](@next) //: //: [SnapBlog](http://snapblog.ru)
mit
ae99f361c89782bb5d73c0cf86970147
46.246914
488
0.697152
2.787327
false
false
false
false
MadAppGang/SmartLog
iOS/Pods/CoreStore/Sources/SaveResult.swift
2
2671
// // SaveResult.swift // CoreStore // // Copyright © 2014 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation // MARK: - SaveResult @available(*, deprecated, message: "Use the new DataStack.perform(asynchronous:...) and DataStack.perform(synchronous:...) family of APIs") public enum SaveResult: Hashable { case success(hasChanges: Bool) case failure(CoreStoreError) public var boolValue: Bool { switch self { case .success: return true case .failure: return false } } // MARK: Equatable public static func == (lhs: SaveResult, rhs: SaveResult) -> Bool { switch (lhs, rhs) { case (.success(let hasChanges1), .success(let hasChanges2)): return hasChanges1 == hasChanges2 case (.failure(let error1), .failure(let error2)): return error1 == error2 default: return false } } // MARK: Hashable public var hashValue: Int { switch self { case .success(let hasChanges): return self.boolValue.hashValue ^ hasChanges.hashValue case .failure(let error): return self.boolValue.hashValue ^ error.hashValue } } // MARK: Internal internal init(hasChanges: Bool) { self = .success(hasChanges: hasChanges) } internal init(_ error: CoreStoreError) { self = .failure(error) } }
mit
fd03810781f61b67d1d4c71cb35cf3c4
28.340659
139
0.62809
4.845735
false
false
false
false
modocache/FutureKit
FutureKit/Executor.swift
3
23338
// // Executor.swift // FutureKit // // Created by Michael Gray on 4/13/15. // 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) import UIKit #else import Foundation #endif import CoreData public extension NSQualityOfService { public var qos_class : qos_class_t { get { switch self { case UserInteractive: return QOS_CLASS_USER_INTERACTIVE case .UserInitiated: return QOS_CLASS_USER_INITIATED case .Default: return QOS_CLASS_DEFAULT case .Utility: return QOS_CLASS_UTILITY case .Background: return QOS_CLASS_BACKGROUND } } } } private func make_dispatch_block<T>(q: dispatch_queue_t, block: (T) -> Void) -> ((T) -> Void) { let newblock = { (t:T) -> Void in dispatch_async(q) { block(t) } } return newblock } private func make_dispatch_block<T>(q: NSOperationQueue, block: (T) -> Void) -> ((T) -> Void) { let newblock = { (t:T) -> Void in q.addOperationWithBlock({ () -> Void in block(t) }) } return newblock } public enum SerialOrConcurrent: Int { case Serial case Concurrent public var q_attr : dispatch_queue_attr_t { switch self { case .Serial: return DISPATCH_QUEUE_SERIAL case .Concurrent: return DISPATCH_QUEUE_CONCURRENT } } } // remove in Swift 2.0 extension qos_class_t { var rawValue : UInt32 { return self.value } } public enum Executor { case Primary // use the default configured executor. Current set to Immediate. // There are deep philosphical arguments about Immediate vs Async. // So whenever we figure out what's better we will set the Primary to that! case Main // will use MainAsync or MainImmediate based on MainStrategy case Async // Always performs an Async Dispatch to some non-main q (usually Default) // If you want to put all of these in a custom queue, you can set AsyncStrategy to .Queue(q) case Current // Will try to use the current Executor. // If the current block isn't running in an Executor, will return Main if running in the main thread, otherwise .Async case Immediate // Never performs an Async Dispatch, Ok for simple mappings. But use with care! // Blocks using the Immediate executor can run in ANY Block case StackCheckingImmediate // Will try to perform immediate, but does some stack checking. Safer than Immediate // But is less efficient. // Maybe useful if an Immediate handler is somehow causing stack overflow issues case MainAsync // will always do a dispatch_async to the mainQ case MainImmediate // will try to avoid dispatch_async if already on the MainQ case UserInteractive // QOS_CLASS_USER_INTERACTIVE case UserInitiated // QOS_CLASS_USER_INITIATED case Default // QOS_CLASS_DEFAULT case Utility // QOS_CLASS_UTILITY case Background // QOS_CLASS_BACKGROUND case Queue(dispatch_queue_t) // Dispatch to a Queue of your choice! // Use this for your own custom queues case OperationQueue(NSOperationQueue) // Dispatch to a Queue of your choice! // Use this for your own custom queues case ManagedObjectContext(NSManagedObjectContext) // block will run inside the managed object's context via context.performBlock() case Custom(CustomCallBackBlock) // Don't like any of these? Bake your own Executor! public typealias customFutureHandlerBlockOld = ((Any) -> Void) public typealias customFutureHandlerBlock = (() -> Void) // define a Block with the following signature. // we give you some taskInfo and a block called callBack // just call "callBack(data)" in your execution context of choice. public typealias CustomCallBackBlockOld = ((data:Any,callBack:customFutureHandlerBlock) -> Void) public typealias CustomCallBackBlock = ((callback:customFutureHandlerBlock) -> Void) // TODO - should these be configurable? Eventually I guess. public static var PrimaryExecutor = Executor.Current { willSet(newValue) { switch newValue { case .Primary: assertionFailure("Nope. Nope. Nope.") case .Main,.MainAsync,MainImmediate: NSLog("it's probably a bad idea to set .Primary to the Main Queue. You have been warned") default: break } } } public static var MainExecutor = Executor.MainImmediate { willSet(newValue) { switch newValue { case .MainImmediate, .MainAsync, .Custom: break default: assertionFailure("MainStrategy must be either .MainImmediate or .MainAsync") } } } public static var AsyncExecutor = Executor.Default { willSet(newValue) { switch newValue { case .Immediate, .StackCheckingImmediate,.MainImmediate: assertionFailure("AsyncStrategy can't be Immediate!") case .Async, .Main, .Primary, .Current: assertionFailure("Nope. Nope. Nope.") case .MainAsync: NSLog("it's probably a bad idea to set .Async to the Main Queue. You have been warned") case let .Queue(q): assert(q != dispatch_get_main_queue(), "Async is not for the mainq") default: break } } } private static let mainQ = dispatch_get_main_queue() private static let userInteractiveQ = dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE,0) private static let userInitiatedQ = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0) private static let defaultQ = dispatch_get_global_queue(QOS_CLASS_DEFAULT,0) private static let utilityQ = dispatch_get_global_queue(QOS_CLASS_UTILITY,0) private static let backgroundQ = dispatch_get_global_queue(QOS_CLASS_BACKGROUND,0) init(qos: NSQualityOfService) { switch qos { case .UserInteractive: self = .UserInteractive case .UserInitiated: self = .UserInitiated case .Default: self = .Default case .Utility: self = .Utility case .Background: self = .Background } } init(qos_class: qos_class_t) { switch qos_class.rawValue { case QOS_CLASS_USER_INTERACTIVE.rawValue: self = .UserInteractive case QOS_CLASS_USER_INITIATED.rawValue: self = .UserInitiated case QOS_CLASS_DEFAULT.rawValue: self = .Default case QOS_CLASS_UTILITY.rawValue: self = .Utility case QOS_CLASS_BACKGROUND.rawValue: self = .Background case QOS_CLASS_UNSPECIFIED.rawValue: self = .Default default: assertionFailure("invalid argument \(qos_class)") self = .Default } } init(queue: dispatch_queue_t) { self = .Queue(queue) } init(opqueue: NSOperationQueue) { self = .OperationQueue(opqueue) } public static func createQueue(label: String?, type : SerialOrConcurrent, qos : NSQualityOfService = .Default, relative_priority: Int32 = 0) -> Executor { let qos_class = qos.qos_class let q_attr = type.q_attr let c_attr = dispatch_queue_attr_make_with_qos_class(q_attr,qos_class, relative_priority) let q : dispatch_queue_t if let l = label { q = dispatch_queue_create(l, c_attr) } else { q = dispatch_queue_create(nil, c_attr) } return .Queue(q) } public static func createOperationQueue(name: String?, maxConcurrentOperationCount : Int) -> Executor { let oq = NSOperationQueue() oq.name = name return .OperationQueue(oq) } public static func createConcurrentQueue(_ label : String? = nil,qos : NSQualityOfService = .Default) -> Executor { return self.createQueue(label, type: .Concurrent, qos: qos, relative_priority: 0) } public static func createConcurrentQueue() -> Executor { return self.createQueue(nil, type: .Concurrent, qos: .Default, relative_priority: 0) } public static func createSerialQueue(_ label : String? = nil,qos : NSQualityOfService = .Default) -> Executor { return self.createQueue(label, type: .Serial, qos: qos, relative_priority: 0) } public static func createSerialQueue() -> Executor { return self.createQueue(nil, type: .Serial, qos: .Default, relative_priority: 0) } // immediately 'dispatches' and executes a block on an Executor // example: // // Executor.Background.execute { // // insert code to run in the QOS_CLASS_BACKGROUND queue! // } // public func execute(block b: dispatch_block_t) { let executionBlock = self.callbackBlockFor(b) executionBlock() } public func executeAfterDelay(nanosecs n: Int64, block b: dispatch_block_t) { let executionBlock = self.callbackBlockFor(b) let popTime = dispatch_time(DISPATCH_TIME_NOW, n) let q = self.underlyingQueue ?? Executor.defaultQ dispatch_after(popTime, q, { executionBlock() }); } public func executeAfterDelay(secs : NSTimeInterval,block b: dispatch_block_t) { let nanosecsDouble = secs * NSTimeInterval(NSEC_PER_SEC) let nanosecs = Int64(nanosecsDouble) self.executeAfterDelay(nanosecs:nanosecs,block: b) } // This returns the underlyingQueue (if there is one). // Not all executors have an underlyingQueue. // .Custom will always return nil, even if the implementation may include one. // var underlyingQueue: dispatch_queue_t? { get { switch self { case .Primary: return Executor.PrimaryExecutor.underlyingQueue case .Main, MainImmediate, MainAsync: return Executor.mainQ case .Async: return Executor.AsyncExecutor.underlyingQueue case UserInteractive: return Executor.userInteractiveQ case UserInitiated: return Executor.userInitiatedQ case Default: return Executor.defaultQ case Utility: return Executor.utilityQ case Background: return Executor.backgroundQ case let .Queue(q): return q case let .OperationQueue(opQueue): return opQueue.underlyingQueue case let .ManagedObjectContext(context): if (context.concurrencyType == .MainQueueConcurrencyType) { return Executor.mainQ } else { return nil } default: return nil } } } static var SmartCurrent : Executor { // should always return a 'real_executor', never a virtual one! get { if let current = getCurrentExecutor() { return current } if (NSThread.isMainThread()) { return self.MainExecutor.real_executor } return .Async } } public static func getCurrentExecutor() -> Executor? { let threadDict = NSThread.currentThread().threadDictionary let r = threadDict[GLOBAL_PARMS.CURRENT_EXECUTOR_PROPERTY] as? Result<Executor> return r?.result } public static func getCurrentQueue() -> dispatch_queue_t? { return getCurrentExecutor()?.underlyingQueue } public func isEqualTo(e:Executor) -> Bool { switch self { case .Primary: switch e { case .Primary: return true default: return false } case .Main: switch e { case .Main: return true default: return false } case .Async: switch e { case .Async: return true default: return false } case .Current: switch e { case .Current: return true default: return false } case .MainImmediate: switch e { case .MainImmediate: return true default: return false } case .MainAsync: switch e { case .MainAsync: return true default: return false } case UserInteractive: switch e { case .UserInteractive: return true default: return false } case UserInitiated: switch e { case .UserInitiated: return true default: return false } case Default: switch e { case .Default: return true default: return false } case Utility: switch e { case .Utility: return true default: return false } case Background: switch e { case .Background: return true default: return false } case let .Queue(q): switch e { case let .Queue(q2): return (q == q2) default: return false } case let .OperationQueue(opQueue): switch e { case let .OperationQueue(opQueue2): return (opQueue == opQueue2) default: return false } case let .ManagedObjectContext(context): switch e { case let .ManagedObjectContext(context2): return (context == context2) default: return false } case .Immediate: switch e { case .Immediate: return true default: return false } case .StackCheckingImmediate: switch e { case .StackCheckingImmediate: return true default: return false } case .Custom: switch e { case .Custom: NSLog("we can't compare Custom Executors! isTheCurrentlyRunningExecutor may fail on .Custom types") return false default: return false } } } var isTheCurrentlyRunningExecutor : Bool { if let e = Executor.getCurrentExecutor() { return self.isEqualTo(e) } return false } // returns the previous Executor private static func setCurrentExecutor(e:Executor?) -> Executor? { let threadDict = NSThread.currentThread().threadDictionary let key = GLOBAL_PARMS.CURRENT_EXECUTOR_PROPERTY let current = threadDict[key] as? Result<Executor> if let ex = e { threadDict.setObject(Result<Executor>(ex), forKey: key) } else { threadDict.removeObjectForKey(key) } return current?.result } public func callbackBlockFor<T>(block: (T) -> Void) -> ((T) -> Void) { let currentExecutor = self.real_executor switch currentExecutor { case .Immediate,.StackCheckingImmediate: return currentExecutor.getblock_for_callbackBlockFor(block) default: let wrappedBlock = { (t:T) -> Void in let previous = Executor.setCurrentExecutor(currentExecutor) block(t) Executor.setCurrentExecutor(previous) } return currentExecutor.getblock_for_callbackBlockFor(wrappedBlock) } } /* we need to figure out what the real executor will be used 'unwraps' the virtual Executors like .Primary,.Main,.Async,.Current */ private var real_executor : Executor { switch self { case .Primary: return Executor.PrimaryExecutor.real_executor case .Main: return Executor.MainExecutor.real_executor case .Async: return Executor.AsyncExecutor.real_executor case .Current: return Executor.SmartCurrent case let .ManagedObjectContext(context): if (context.concurrencyType == .MainQueueConcurrencyType) { return Executor.MainExecutor.real_executor } else { return self } default: return self } } private func getblock_for_callbackBlockFor<T>(block: (T) -> Void) -> ((T) -> Void) { switch self { case .Primary: return Executor.PrimaryExecutor.getblock_for_callbackBlockFor(block) case .Main: return Executor.MainExecutor.getblock_for_callbackBlockFor(block) case .Async: return Executor.AsyncExecutor.getblock_for_callbackBlockFor(block) case .Current: return Executor.SmartCurrent.getblock_for_callbackBlockFor(block) case .MainImmediate: let newblock = { (t:T) -> Void in if (NSThread.isMainThread()) { block(t) } else { dispatch_async(Executor.mainQ) { block(t) } } } return newblock case .MainAsync: return make_dispatch_block(Executor.mainQ,block) case UserInteractive: return make_dispatch_block(Executor.userInteractiveQ,block) case UserInitiated: return make_dispatch_block(Executor.userInitiatedQ,block) case Default: return make_dispatch_block(Executor.defaultQ,block) case Utility: return make_dispatch_block(Executor.utilityQ,block) case Background: return make_dispatch_block(Executor.backgroundQ,block) case let .Queue(q): return make_dispatch_block(q,block) case let .OperationQueue(opQueue): return make_dispatch_block(opQueue,block) case let .ManagedObjectContext(context): if (context.concurrencyType == .MainQueueConcurrencyType) { return Executor.MainExecutor.getblock_for_callbackBlockFor(block) } else { let newblock = { (t:T) -> Void in context.performBlock { block(t) } } return newblock } case .Immediate: return block case .StackCheckingImmediate: let b = { (t:T) -> Void in var currentDepth : NSNumber let threadDict = NSThread.currentThread().threadDictionary if let c = threadDict[GLOBAL_PARMS.STACK_CHECKING_PROPERTY] as? NSNumber { currentDepth = c } else { currentDepth = 0 } if (currentDepth.integerValue > GLOBAL_PARMS.STACK_CHECKING_MAX_DEPTH) { let b = Executor.AsyncExecutor.callbackBlockFor(block) b(t) } else { let newDepth = NSNumber(int:currentDepth.integerValue+1) threadDict[GLOBAL_PARMS.STACK_CHECKING_PROPERTY] = newDepth block(t) threadDict[GLOBAL_PARMS.STACK_CHECKING_PROPERTY] = currentDepth } } return b case let .Custom(customCallBack): let b = { (t:T) -> Void in customCallBack(callback: { () -> Void in block(t) }) } return b } } } let example_of_a_Custom_Executor_That_Is_The_Same_As_MainAsync = Executor.Custom { (callback) -> Void in dispatch_async(dispatch_get_main_queue()) { callback() } } let example_Of_a_Custom_Executor_That_Is_The_Same_As_Immediate = Executor.Custom { (callback) -> Void in callback() } let example_Of_A_Custom_Executor_That_has_unneeded_dispatches = Executor.Custom { (callback) -> Void in Executor.Background.execute { Executor.Async.execute { Executor.Background.execute { callback() } } } } let example_Of_A_Custom_Executor_Where_everthing_takes_5_seconds = Executor.Custom { (callback) -> Void in Executor.Primary.executeAfterDelay(5) { callback() } }
mit
cdce0d48e179d02a4a6b765c8366f3d0
33.070073
154
0.54859
5.021084
false
false
false
false
EdwaRen/Med-Sync
Med-Sync/MedSync4.0/MedSync4.0/ContactsVC.swift
1
2680
// // ContactsVC.swift // MedSync4.0 // // Created by - on 2017/03/21. // Copyright © 2017 Danth. All rights reserved. // import UIKit class ContactsVC: UIViewController, UITableViewDelegate, UITableViewDataSource, FetchData { //@IBOutlet weak var myTable: UITableView! @IBOutlet weak var myTable: UITableView! private let CELL_ID = "Cell"; private let CHAT_SEGUE = "ChatSegue"; private var contacts = [Contact](); override func viewDidLoad() { super.viewDidLoad() DBProvider.Instance.delegate = self; DBProvider.Instance.getContacts(); } func dataReceived(contacts: [Contact]) { self.contacts = contacts; for contact in contacts { if contact.id == AuthProvider.Instance.userID() { AuthProvider.Instance.userName = contact.name; } } myTable.reloadData(); } func numberOfSections(in tableView: UITableView) -> Int { return 1; } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contacts.count; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath); cell.textLabel?.text = contacts[indexPath.row].name; return cell; } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: CHAT_SEGUE, sender: nil); } @IBAction func logout(_ sender: Any) { dismiss(animated: true, completion: nil); if AuthProvider.Instance.logOut() { dismiss(animated: true, completion: nil); } else { alertTheUser(title: "Could Not Log Out", message: "We could not log out at the moment. Please try again."); } } /* @IBAction func logout(_ sender: Any) { dismiss(animated: true, completion: nil); if AuthProvider.Instance.logOut() { dismiss(animated: true, completion: nil); } else { alertTheUser(title: "Could Not Log Out", message: "We could not log out at the moment. Please try again."); } } */ private func alertTheUser(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert); let ok = UIAlertAction(title: "OK", style: .default, handler: nil); alert.addAction(ok); present(alert, animated: true, completion: nil); } }
mit
edfbc0bb2b8f7abb9f9cbdafb117cc40
29.443182
119
0.608436
4.675393
false
false
false
false
criticalmaps/criticalmaps-ios
CriticalMapsKit/Sources/AppFeature/AppFeatureCore.swift
1
14003
import ApiClient import ChatFeature import ComposableArchitecture import ComposableCoreLocation import L10n import Logger import MapFeature import MapKit import NextRideFeature import SettingsFeature import SharedDependencies import SharedModels import SocialFeature import TwitterFeedFeature public struct AppFeature: ReducerProtocol { public init() {} @Dependency(\.fileClient) public var fileClient @Dependency(\.locationAndChatService) public var locationsAndChatDataService @Dependency(\.uuid) public var uuid @Dependency(\.date) public var date @Dependency(\.userDefaultsClient) public var userDefaultsClient @Dependency(\.nextRideService) public var nextRideService @Dependency(\.idProvider) public var idProvider @Dependency(\.mainQueue) public var mainQueue @Dependency(\.locationManager) public var locationManager @Dependency(\.uiApplicationClient) public var uiApplicationClient @Dependency(\.setUserInterfaceStyle) public var setUserInterfaceStyle @Dependency(\.pathMonitorClient) public var pathMonitorClient @Dependency(\.isNetworkAvailable) public var isNetworkAvailable // MARK: State public struct State: Equatable { public init( locationsAndChatMessages: TaskResult<LocationAndChatMessages>? = nil, didResolveInitialLocation: Bool = false, mapFeatureState: MapFeature.State = .init( riders: [], userTrackingMode: UserTrackingFeature.State(userTrackingMode: .follow) ), socialState: SocialFeature.State = .init(), settingsState: SettingsFeature.State = .init(), nextRideState: NextRideFeature.State = .init(), requestTimer: RequestTimer.State = .init(), route: AppRoute? = nil, chatMessageBadgeCount: UInt = 0 ) { self.locationsAndChatMessages = locationsAndChatMessages self.didResolveInitialLocation = didResolveInitialLocation self.mapFeatureState = mapFeatureState self.socialState = socialState self.settingsState = settingsState self.nextRideState = nextRideState self.requestTimer = requestTimer self.route = route self.chatMessageBadgeCount = chatMessageBadgeCount } public var locationsAndChatMessages: TaskResult<LocationAndChatMessages>? public var didResolveInitialLocation = false // Children states public var mapFeatureState = MapFeature.State( riders: [], userTrackingMode: UserTrackingFeature.State(userTrackingMode: .follow) ) public var socialState = SocialFeature.State() public var settingsState = SettingsFeature.State() public var nextRideState = NextRideFeature.State() public var requestTimer = RequestTimer.State() public var connectionObserverState = NetworkConnectionObserver.State() // Navigation public var route: AppRoute? public var isChatViewPresented: Bool { route == .chat } public var isRulesViewPresented: Bool { route == .rules } public var isSettingsViewPresented: Bool { route == .settings } public var chatMessageBadgeCount: UInt = 0 @BindableState public var presentEventsBottomSheet = false public var alert: AlertState<Action>? } // MARK: Actions public enum Action: Equatable, BindableAction { case binding(BindingAction<State>) case appDelegate(AppDelegate.Action) case onAppear case onDisappear case fetchData case fetchDataResponse(TaskResult<LocationAndChatMessages>) case userSettingsLoaded(TaskResult<UserSettings>) case setEventsBottomSheet(Bool) case setNavigation(tag: AppRoute.Tag?) case dismissSheetView case presentObservationModeAlert case setObservationMode(Bool) case dismissAlert case map(MapFeature.Action) case nextRide(NextRideFeature.Action) case requestTimer(RequestTimer.Action) case settings(SettingsFeature.Action) case social(SocialFeature.Action) case connectionObserver(NetworkConnectionObserver.Action) } // MARK: Reducer struct ObserveConnectionIdentifier: Hashable {} public var body: some ReducerProtocol<State, Action> { BindingReducer() Scope(state: \.connectionObserverState, action: /AppFeature.Action.connectionObserver) { NetworkConnectionObserver() } Scope(state: \.requestTimer, action: /AppFeature.Action.requestTimer) { RequestTimer() } Scope(state: \.mapFeatureState, action: /AppFeature.Action.map) { MapFeature() } Scope(state: \.nextRideState, action: /AppFeature.Action.nextRide) { NextRideFeature() .dependency(\.isNetworkAvailable, isNetworkAvailable) } Scope(state: \.settingsState, action: /AppFeature.Action.settings) { SettingsFeature() } Scope(state: \.socialState, action: /AppFeature.Action.social) { SocialFeature() .dependency(\.isNetworkAvailable, isNetworkAvailable) } /// Holds the logic for the AppFeature to update state and execute side effects Reduce<State, Action> { state, action in switch action { case .binding: return .none case .appDelegate: return .none case .onAppear: var effects: [Effect<Action, Never>] = [ Effect(value: .fetchData), Effect(value: .connectionObserver(.observeConnection)), .task { await .userSettingsLoaded( TaskResult { try await fileClient.loadUserSettings() } ) }, Effect(value: .map(.onAppear)), Effect(value: .requestTimer(.startTimer)) ] if !userDefaultsClient.didShowObservationModePrompt { effects.append( Effect.run { send in try? await mainQueue.sleep(for: .seconds(3)) await send.send(.presentObservationModeAlert) } ) } return .merge(effects) case .onDisappear: return Effect.cancel(id: ObserveConnectionIdentifier()) case .fetchData: struct GetLocationsId: Hashable {} let postBody = SendLocationAndChatMessagesPostBody( device: idProvider.id(), location: state.settingsState.userSettings.enableObservationMode ? nil : Location(state.mapFeatureState.location) ) guard isNetworkAvailable else { logger.info("AppAction.fetchData not executed. Not connected to internet") return .none } return .task { await .fetchDataResponse( TaskResult { try await locationsAndChatDataService.getLocationsAndSendMessages(postBody) } ) } case let .fetchDataResponse(.success(response)): state.locationsAndChatMessages = .success(response) state.socialState.chatFeautureState.chatMessages = .results(response.chatMessages) state.mapFeatureState.riderLocations = response.riderLocations if !state.isChatViewPresented { let cachedMessages = response.chatMessages .values .sorted(by: \.timestamp) let unreadMessagesCount = UInt( cachedMessages .filter { $0.timestamp > userDefaultsClient.chatReadTimeInterval } .count ) state.chatMessageBadgeCount = unreadMessagesCount } return .none case let .fetchDataResponse(.failure(error)): logger.info("FetchData failed: \(error)") state.locationsAndChatMessages = .failure(error) return .none case let .map(mapFeatureAction): switch mapFeatureAction { case let .locationManager(locationManagerAction): switch locationManagerAction { case .didUpdateLocations: // synchronize with nextRideState state.nextRideState.userLocation = Coordinate(state.mapFeatureState.location) if !state.didResolveInitialLocation { state.didResolveInitialLocation.toggle() if let coordinate = Coordinate(state.mapFeatureState.location), state.settingsState.userSettings.rideEventSettings.isEnabled { return Effect.concatenate( Effect(value: .fetchData), Effect(value: .nextRide(.getNextRide(coordinate))) ) } else { return Effect(value: .fetchData) } } else { return .none } default: return .none } case .focusNextRide: if state.presentEventsBottomSheet { return Effect(value: .setEventsBottomSheet(false)) } else { return .none } default: return .none } case let .nextRide(nextRideAction): switch nextRideAction { case let .setNextRide(ride): state.mapFeatureState.nextRide = ride return Effect.run { send in await send.send(.map(.setNextRideBannerVisible(true))) try? await mainQueue.sleep(for: .seconds(1)) await send.send(.map(.setNextRideBannerExpanded(true))) try? await mainQueue.sleep(for: .seconds(8)) await send.send(.map(.setNextRideBannerExpanded(false))) } default: return .none } case let .userSettingsLoaded(result): state.settingsState.userSettings = (try? result.value) ?? UserSettings() let style = state.settingsState.userSettings.appearanceSettings.colorScheme.userInterfaceStyle return .merge( .fireAndForget { await setUserInterfaceStyle(style) } ) case let .setNavigation(tag: tag): switch tag { case .chat: state.route = .chat case .rules: state.route = .rules case .settings: state.route = .settings case .none: state.route = .none } return .none case let .setEventsBottomSheet(value): if value { state.mapFeatureState.rideEvents = state.nextRideState.rideEvents } else { state.mapFeatureState.rideEvents = [] state.mapFeatureState.eventCenter = nil } state.presentEventsBottomSheet = value return .none case .dismissSheetView: state.route = .none return .none case let .requestTimer(timerAction): switch timerAction { case .timerTicked: return Effect(value: .fetchData) default: return .none } case .presentObservationModeAlert: state.alert = .viewingModeAlert return .none case let .setObservationMode(value): state.settingsState.userSettings.enableObservationMode = value let userSettings = state.settingsState.userSettings return .fireAndForget { await withThrowingTaskGroup(of: Void.self) { group in group.addTask { try await fileClient.saveUserSettings(userSettings: userSettings) } group.addTask { await userDefaultsClient.setDidShowObservationModePrompt(true) } } } case .dismissAlert: state.alert = nil return .none case let .social(socialAction): switch socialAction { case .chat(.onAppear): state.chatMessageBadgeCount = 0 return .none default: return .none } case let .settings(settingsAction): switch settingsAction { case let .rideevent(.setRideEventsEnabled(isEnabled)): if !isEnabled { return Effect(value: .map(.setNextRideBannerVisible(false))) } else { guard let coordinate = Coordinate(state.mapFeatureState.location), state.settingsState.userSettings.rideEventSettings.isEnabled else { return .none } struct RideEventSettingsChange: Hashable {} return Effect(value: .nextRide(.getNextRide(coordinate))) .debounce(id: RideEventSettingsChange(), for: 1.5, scheduler: mainQueue) } default: return .none } case .connectionObserver: return .none } } } } // MARK: - Helper extension SharedModels.Location { /// Creates a Location object from an optional ComposableCoreLocation.Location init?(_ location: ComposableCoreLocation.Location?) { guard let location = location else { return nil } self = SharedModels.Location( coordinate: Coordinate( latitude: location.coordinate.latitude, longitude: location.coordinate.longitude ), timestamp: location.timestamp.timeIntervalSince1970 ) } } extension SharedModels.Coordinate { /// Creates a Location object from an optional ComposableCoreLocation.Location init?(_ location: ComposableCoreLocation.Location?) { guard let location = location else { return nil } self = Coordinate( latitude: location.coordinate.latitude, longitude: location.coordinate.longitude ) } } public extension AlertState where Action == AppFeature.Action { static let viewingModeAlert = Self( title: .init(L10n.Settings.Observationmode.title), message: .init(L10n.AppCore.ViewingModeAlert.message), buttons: [ .default(.init(L10n.AppCore.ViewingModeAlert.riding), action: .send(.setObservationMode(false))), .default(.init(L10n.AppCore.ViewingModeAlert.watching), action: .send(.setObservationMode(true))) ] ) }
mit
9db2f4d68e29fe260d08e5807dc7b2a1
31.489559
140
0.637221
5.029813
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/System/Coordinators/ReaderCoordinator.swift
2
6334
import UIKit @objc class ReaderCoordinator: NSObject { let readerNavigationController: UINavigationController var failureBlock: (() -> Void)? = nil @objc init(readerNavigationController: UINavigationController) { self.readerNavigationController = readerNavigationController super.init() } func showReaderTab() { WPTabBarController.sharedInstance().showReaderTab() } func showDiscover() { WPTabBarController.sharedInstance().switchToDiscover() } func showSearch() { WPTabBarController.sharedInstance().navigateToReaderSearch() } func showA8C() { WPTabBarController.sharedInstance()?.switchToTopic(where: { topic in return (topic as? ReaderTeamTopic)?.slug == ReaderTeamTopic.a8cSlug }) } func showP2() { WPTabBarController.sharedInstance()?.switchToTopic(where: { topic in return (topic as? ReaderTeamTopic)?.slug == ReaderTeamTopic.p2Slug }) } func showMyLikes() { WPTabBarController.sharedInstance().switchToMyLikes() } func showManageFollowing() { WPTabBarController.sharedInstance()?.switchToFollowedSites() } func showList(named listName: String, forUser user: String) { let context = ContextManager.sharedInstance().mainContext let service = ReaderTopicService(managedObjectContext: context) guard let topic = service.topicForList(named: listName, forUser: user) else { failureBlock?() return } WPTabBarController.sharedInstance()?.switchToTopic(where: { $0 == topic }) } func showTag(named tagName: String) { let remote = ReaderTopicServiceRemote(wordPressComRestApi: WordPressComRestApi.anonymousApi(userAgent: WPUserAgent.wordPress())) let slug = remote.slug(forTopicName: tagName) ?? tagName.lowercased() getTagTopic(tagSlug: slug) { result in guard let topic = try? result.get() else { return } WPTabBarController.sharedInstance()?.navigateToReaderTag(topic) } } private func getTagTopic(tagSlug: String, completion: @escaping (Result<ReaderTagTopic, Error>) -> Void) { let service = ReaderTopicService(managedObjectContext: ContextManager.sharedInstance().mainContext) service.tagTopicForTag(withSlug: tagSlug, success: { objectID in guard let objectID = objectID, let topic = try? ContextManager.sharedInstance().mainContext.existingObject(with: objectID) as? ReaderTagTopic else { DDLogError("Reader: Error retriving tag topic - invalid tag slug") return } completion(.success(topic)) }, failure: { error in let defaultError = NSError(domain: "readerTagTopicError", code: -1, userInfo: nil) DDLogError("Reader: Error retriving tag topic - " + (error?.localizedDescription ?? "unknown failure reason")) completion(.failure(error ?? defaultError)) }) } func showStream(with siteID: Int, isFeed: Bool) { getSiteTopic(siteID: NSNumber(value: siteID), isFeed: isFeed) { result in guard let topic = try? result.get() else { return } WPTabBarController.sharedInstance()?.navigateToReaderSite(topic) } } private func getSiteTopic(siteID: NSNumber, isFeed: Bool, completion: @escaping (Result<ReaderSiteTopic, Error>) -> Void) { let service = ReaderTopicService(managedObjectContext: ContextManager.sharedInstance().mainContext) service.siteTopicForSite(withID: siteID, isFeed: isFeed, success: { objectID, isFollowing in guard let objectID = objectID, let topic = try? ContextManager.sharedInstance().mainContext.existingObject(with: objectID) as? ReaderSiteTopic else { DDLogError("Reader: Error retriving site topic - invalid Site Id") return } completion(.success(topic)) }, failure: { error in let defaultError = NSError(domain: "readerSiteTopicError", code: -1, userInfo: nil) DDLogError("Reader: Error retriving site topic - " + (error?.localizedDescription ?? "unknown failure reason")) completion(.failure(error ?? defaultError)) }) } func showPost(with postID: Int, for feedID: Int, isFeed: Bool) { showPost(in: ReaderDetailViewController .controllerWithPostID(postID as NSNumber, siteID: feedID as NSNumber, isFeed: isFeed)) } func showPost(with url: URL) { showPost(in: ReaderDetailViewController.controllerWithPostURL(url)) } private func showPost(in detailViewController: ReaderDetailViewController) { let postLoadFailureBlock = { [weak self, failureBlock] in self?.readerNavigationController.popToRootViewController(animated: false) failureBlock?() } detailViewController.postLoadFailureBlock = postLoadFailureBlock WPTabBarController.sharedInstance().navigateToReader(detailViewController) } } extension ReaderTopicService { /// Returns an existing topic for the specified list, or creates one if one /// doesn't already exist. /// func topicForList(named listName: String, forUser user: String) -> ReaderListTopic? { let remote = ReaderTopicServiceRemote(wordPressComRestApi: WordPressComRestApi.anonymousApi(userAgent: WPUserAgent.wordPress())) let sanitizedListName = remote.slug(forTopicName: listName) ?? listName.lowercased() let sanitizedUser = user.lowercased() let path = remote.path(forEndpoint: "read/list/\(sanitizedUser)/\(sanitizedListName)/posts", withVersion: ._1_2) if let existingTopic = findContainingPath(path) as? ReaderListTopic { return existingTopic } let topic = ReaderListTopic(context: managedObjectContext) topic.title = listName topic.slug = sanitizedListName topic.owner = user topic.path = path return topic } }
gpl-2.0
fa4b96b213804a4dd954cfdeb7aadf4d
37.621951
137
0.646511
5.282736
false
false
false
false
apple/swift-nio
Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift
1
3374
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore /// A simple channel handler that catches errors emitted by parsing HTTP requests /// and sends 400 Bad Request responses. /// /// This channel handler provides the basic behaviour that the majority of simple HTTP /// servers want. This handler does not suppress the parser errors: it allows them to /// continue to pass through the pipeline so that other handlers (e.g. logging ones) can /// deal with the error. public final class HTTPServerProtocolErrorHandler: ChannelDuplexHandler, RemovableChannelHandler { public typealias InboundIn = HTTPServerRequestPart public typealias InboundOut = HTTPServerRequestPart public typealias OutboundIn = HTTPServerResponsePart public typealias OutboundOut = HTTPServerResponsePart private var hasUnterminatedResponse: Bool = false public init() {} public func errorCaught(context: ChannelHandlerContext, error: Error) { guard error is HTTPParserError else { context.fireErrorCaught(error) return } // Any HTTPParserError is automatically fatal, and we don't actually need (or want) to // provide that error to the client: we just want to tell it that it screwed up and then // let the rest of the pipeline shut the door in its face. However, we can only send an // HTTP error response if another response hasn't started yet. // // A side note here: we cannot block or do any delayed work. ByteToMessageDecoder is going // to come along and close the channel right after we return from this function. if !self.hasUnterminatedResponse { let headers = HTTPHeaders([("Connection", "close"), ("Content-Length", "0")]) let head = HTTPResponseHead(version: .http1_1, status: .badRequest, headers: headers) context.write(self.wrapOutboundOut(.head(head)), promise: nil) context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) } // Now pass the error on in case someone else wants to see it. context.fireErrorCaught(error) } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) { let res = self.unwrapOutboundIn(data) switch res { case .head(let head) where head.isInformational: precondition(!self.hasUnterminatedResponse) case .head: precondition(!self.hasUnterminatedResponse) self.hasUnterminatedResponse = true case .body: precondition(self.hasUnterminatedResponse) case .end: precondition(self.hasUnterminatedResponse) self.hasUnterminatedResponse = false } context.write(data, promise: promise) } } #if swift(>=5.6) @available(*, unavailable) extension HTTPServerProtocolErrorHandler: Sendable {} #endif
apache-2.0
43d8f34b7d655a201ab46f01477ba9fb
42.25641
103
0.664197
4.983752
false
false
false
false
apple/swift-nio
Sources/NIOPosix/BaseSocketChannel.swift
1
52906
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore import NIOConcurrencyHelpers import Atomics private struct SocketChannelLifecycleManager { // MARK: Types private enum State { case fresh case preRegistered // register() has been run but the selector doesn't know about it yet case fullyRegistered // fully registered, ie. the selector knows about it case activated case closed } private enum Event { case activate case beginRegistration case finishRegistration case close } // MARK: properties private let eventLoop: EventLoop // this is queried from the Channel, ie. must be thread-safe internal let isActiveAtomic: ManagedAtomic<Bool> // these are only to be accessed on the EventLoop // have we seen the `.readEOF` notification // note: this can be `false` on a deactivated channel, we might just have torn it down. var hasSeenEOFNotification: Bool = false // Should we support transition from `active` to `active`, used by datagram sockets. let supportsReconnect: Bool private var currentState: State = .fresh { didSet { self.eventLoop.assertInEventLoop() switch (oldValue, self.currentState) { case (_, .activated): self.isActiveAtomic.store(true, ordering: .relaxed) case (.activated, _): self.isActiveAtomic.store(false, ordering: .relaxed) default: () } } } // MARK: API // isActiveAtomic needs to be injected as it's accessed from arbitrary threads and `SocketChannelLifecycleManager` is usually held mutable internal init( eventLoop: EventLoop, isActiveAtomic: ManagedAtomic<Bool>, supportReconnect: Bool ) { self.eventLoop = eventLoop self.isActiveAtomic = isActiveAtomic self.supportsReconnect = supportReconnect } // this is called from Channel's deinit, so don't assert we're on the EventLoop! internal var canBeDestroyed: Bool { return self.currentState == .closed } @inline(__always) // we need to return a closure here and to not suffer from a potential allocation for that this must be inlined internal mutating func beginRegistration() -> ((EventLoopPromise<Void>?, ChannelPipeline) -> Void) { return self.moveState(event: .beginRegistration) } @inline(__always) // we need to return a closure here and to not suffer from a potential allocation for that this must be inlined internal mutating func finishRegistration() -> ((EventLoopPromise<Void>?, ChannelPipeline) -> Void) { return self.moveState(event: .finishRegistration) } @inline(__always) // we need to return a closure here and to not suffer from a potential allocation for that this must be inlined internal mutating func close() -> ((EventLoopPromise<Void>?, ChannelPipeline) -> Void) { return self.moveState(event: .close) } @inline(__always) // we need to return a closure here and to not suffer from a potential allocation for that this must be inlined internal mutating func activate() -> ((EventLoopPromise<Void>?, ChannelPipeline) -> Void) { return self.moveState(event: .activate) } // MARK: private API @inline(__always) // we need to return a closure here and to not suffer from a potential allocation for that this must be inlined private mutating func moveState(event: Event) -> ((EventLoopPromise<Void>?, ChannelPipeline) -> Void) { self.eventLoop.assertInEventLoop() switch (self.currentState, event) { // origin: .fresh case (.fresh, .beginRegistration): self.currentState = .preRegistered return { promise, pipeline in promise?.succeed(()) pipeline.syncOperations.fireChannelRegistered() } case (.fresh, .close): self.currentState = .closed return { (promise, _: ChannelPipeline) in promise?.succeed(()) } // origin: .preRegistered case (.preRegistered, .finishRegistration): self.currentState = .fullyRegistered return { (promise, _: ChannelPipeline) in promise?.succeed(()) } // origin: .fullyRegistered case (.fullyRegistered, .activate): self.currentState = .activated return { promise, pipeline in promise?.succeed(()) pipeline.syncOperations.fireChannelActive() } // origin: .preRegistered || .fullyRegistered case (.preRegistered, .close), (.fullyRegistered, .close): self.currentState = .closed return { promise, pipeline in promise?.succeed(()) pipeline.syncOperations.fireChannelUnregistered() } // origin: .activated case (.activated, .close): self.currentState = .closed return { promise, pipeline in promise?.succeed(()) pipeline.syncOperations.fireChannelInactive() pipeline.syncOperations.fireChannelUnregistered() } // origin: .activated case (.activated, .activate) where self.supportsReconnect: return { promise, pipeline in promise?.succeed(()) } // bad transitions case (.fresh, .activate), // should go through .registered first (.preRegistered, .activate), // need to first be fully registered (.preRegistered, .beginRegistration), // already registered (.fullyRegistered, .beginRegistration), // already registered (.activated, .activate), // already activated (.activated, .beginRegistration), // already fully registered (and activated) (.activated, .finishRegistration), // already fully registered (and activated) (.fullyRegistered, .finishRegistration), // already fully registered (.fresh, .finishRegistration), // need to register lazily first (.closed, _): // already closed self.badTransition(event: event) } } private func badTransition(event: Event) -> Never { preconditionFailure("illegal transition: state=\(self.currentState), event=\(event)") } // MARK: convenience properties internal var isActive: Bool { self.eventLoop.assertInEventLoop() return self.currentState == .activated } internal var isPreRegistered: Bool { self.eventLoop.assertInEventLoop() switch self.currentState { case .fresh, .closed: return false case .preRegistered, .fullyRegistered, .activated: return true } } internal var isRegisteredFully: Bool { self.eventLoop.assertInEventLoop() switch self.currentState { case .fresh, .closed, .preRegistered: return false case .fullyRegistered, .activated: return true } } /// Returns whether the underlying file descriptor is open. This property will always be true (even before registration) /// until the Channel is closed. internal var isOpen: Bool { self.eventLoop.assertInEventLoop() return self.currentState != .closed } } /// The base class for all socket-based channels in NIO. /// /// There are many types of specialised socket-based channel in NIO. Each of these /// has different logic regarding how exactly they read from and write to the network. /// However, they share a great deal of common logic around the managing of their /// file descriptors. /// /// For this reason, `BaseSocketChannel` exists to provide a common core implementation of /// the `SelectableChannel` protocol. It uses a number of private functions to provide hooks /// for subclasses to implement the specific logic to handle their writes and reads. class BaseSocketChannel<SocketType: BaseSocketProtocol>: SelectableChannel, ChannelCore { typealias SelectableType = SocketType.SelectableType struct AddressCache { // deliberately lets because they must always be updated together (so forcing `init` is useful). let local: Optional<SocketAddress> let remote: Optional<SocketAddress> init(local: SocketAddress?, remote: SocketAddress?) { self.local = local self.remote = remote } } // MARK: - Stored Properties // MARK: Constants & atomics (accessible everywhere) public let parent: Channel? internal let socket: SocketType private let closePromise: EventLoopPromise<Void> internal let selectableEventLoop: SelectableEventLoop private let _offEventLoopLock = NIOLock() private let isActiveAtomic: ManagedAtomic<Bool> = .init(false) // just a thread-safe way of having something to print about the socket from any thread internal let socketDescription: String // MARK: Variables, on EventLoop thread only var readPending = false var pendingConnect: Optional<EventLoopPromise<Void>> var recvAllocator: RecvByteBufferAllocator var maxMessagesPerRead: UInt = 4 private var inFlushNow: Bool = false // Guard against re-entrance of flushNow() method. private var autoRead: Bool = true // MARK: Variables that are really constants private var _pipeline: ChannelPipeline! = nil // this is really a constant (set in .init) but needs `self` to be constructed and therefore a `var`. Do not change as this needs to accessed from arbitrary threads // MARK: Special variables, please read comments. // For reads guarded by _either_ `self._offEventLoopLock` or the EL thread // Writes are guarded by _offEventLoopLock _and_ the EL thread. // PLEASE don't use these directly and use the non-underscored computed properties instead. private var _addressCache = AddressCache(local: nil, remote: nil) // please use `self.addressesCached` instead private var _bufferAllocatorCache: ByteBufferAllocator // please use `self.bufferAllocatorCached` instead. // MARK: - Computed properties // This is called from arbitrary threads. internal var addressesCached: AddressCache { get { if self.eventLoop.inEventLoop { return self._addressCache } else { return self._offEventLoopLock.withLock { return self._addressCache } } } set { self.eventLoop.preconditionInEventLoop() self._offEventLoopLock.withLock { self._addressCache = newValue } } } // This is called from arbitrary threads. private var bufferAllocatorCached: ByteBufferAllocator { get { if self.eventLoop.inEventLoop { return self._bufferAllocatorCache } else { return self._offEventLoopLock.withLock { return self._bufferAllocatorCache } } } set { self.eventLoop.preconditionInEventLoop() self._offEventLoopLock.withLock { self._bufferAllocatorCache = newValue } } } // We start with the invalid empty set of selector events we're interested in. This is to make sure we later on // (in `becomeFullyRegistered0`) seed the initial event correctly. internal var interestedEvent: SelectorEventSet = [] { didSet { assert(self.interestedEvent.contains(.reset), "impossible to unregister for reset") } } private var lifecycleManager: SocketChannelLifecycleManager { didSet { self.eventLoop.assertInEventLoop() } } private var bufferAllocator: ByteBufferAllocator = ByteBufferAllocator() { didSet { self.eventLoop.assertInEventLoop() self.bufferAllocatorCached = self.bufferAllocator } } public final var _channelCore: ChannelCore { return self } // This is `Channel` API so must be thread-safe. public final var localAddress: SocketAddress? { return self.addressesCached.local } // This is `Channel` API so must be thread-safe. public final var remoteAddress: SocketAddress? { return self.addressesCached.remote } /// `false` if the whole `Channel` is closed and so no more IO operation can be done. var isOpen: Bool { self.eventLoop.assertInEventLoop() return self.lifecycleManager.isOpen } var isRegistered: Bool { self.eventLoop.assertInEventLoop() return self.lifecycleManager.isPreRegistered } // This is `Channel` API so must be thread-safe. public var isActive: Bool { return self.isActiveAtomic.load(ordering: .relaxed) } // This is `Channel` API so must be thread-safe. public final var closeFuture: EventLoopFuture<Void> { return self.closePromise.futureResult } public final var eventLoop: EventLoop { return selectableEventLoop } // This is `Channel` API so must be thread-safe. public var isWritable: Bool { return true } // This is `Channel` API so must be thread-safe. public final var allocator: ByteBufferAllocator { return self.bufferAllocatorCached } // This is `Channel` API so must be thread-safe. public final var pipeline: ChannelPipeline { return self._pipeline } // MARK: Methods to override in subclasses. func writeToSocket() throws -> OverallWriteResult { fatalError("must be overridden") } /// Read data from the underlying socket and dispatch it to the `ChannelPipeline` /// /// - returns: `true` if any data was read, `false` otherwise. @discardableResult func readFromSocket() throws -> ReadResult { fatalError("this must be overridden by sub class") } // MARK: - Datatypes /// Indicates if a selectable should registered or not for IO notifications. enum IONotificationState { /// We should be registered for IO notifications. case register /// We should not be registered for IO notifications. case unregister } enum ReadResult { /// Nothing was read by the read operation. case none /// Some data was read by the read operation. case some } /// Returned by the `private func readable0()` to inform the caller about the current state of the underlying read stream. /// This is mostly useful when receiving `.readEOF` as we then need to drain the read stream fully (ie. until we receive EOF or error of course) private enum ReadStreamState: Equatable { /// Everything seems normal case normal(ReadResult) /// We saw EOF. case eof /// A read error was received. case error } /// Begin connection of the underlying socket. /// /// - parameters: /// - to: The `SocketAddress` to connect to. /// - returns: `true` if the socket connected synchronously, `false` otherwise. func connectSocket(to address: SocketAddress) throws -> Bool { fatalError("this must be overridden by sub class") } /// Make any state changes needed to complete the connection process. func finishConnectSocket() throws { fatalError("this must be overridden by sub class") } /// Returns if there are any flushed, pending writes to be sent over the network. func hasFlushedPendingWrites() -> Bool { fatalError("this must be overridden by sub class") } /// Buffer a write in preparation for a flush. func bufferPendingWrite(data: NIOAny, promise: EventLoopPromise<Void>?) { fatalError("this must be overridden by sub class") } /// Mark a flush point. This is called when flush is received, and instructs /// the implementation to record the flush. func markFlushPoint() { fatalError("this must be overridden by sub class") } /// Called when closing, to instruct the specific implementation to discard all pending /// writes. func cancelWritesOnClose(error: Error) { fatalError("this must be overridden by sub class") } // MARK: Common base socket logic. init( socket: SocketType, parent: Channel?, eventLoop: SelectableEventLoop, recvAllocator: RecvByteBufferAllocator, supportReconnect: Bool ) throws { self._bufferAllocatorCache = self.bufferAllocator self.socket = socket self.selectableEventLoop = eventLoop self.closePromise = eventLoop.makePromise() self.parent = parent self.recvAllocator = recvAllocator // As the socket may already be connected we should ensure we start with the correct addresses cached. self._addressCache = .init(local: try? socket.localAddress(), remote: try? socket.remoteAddress()) self.lifecycleManager = SocketChannelLifecycleManager( eventLoop: eventLoop, isActiveAtomic: self.isActiveAtomic, supportReconnect: supportReconnect ) self.socketDescription = socket.description self.pendingConnect = nil self._pipeline = ChannelPipeline(channel: self) } deinit { assert(self.lifecycleManager.canBeDestroyed, "leak of open Channel, state: \(String(describing: self.lifecycleManager))") } public final func localAddress0() throws -> SocketAddress { self.eventLoop.assertInEventLoop() guard self.isOpen else { throw ChannelError.ioOnClosedChannel } return try self.socket.localAddress() } public final func remoteAddress0() throws -> SocketAddress { self.eventLoop.assertInEventLoop() guard self.isOpen else { throw ChannelError.ioOnClosedChannel } return try self.socket.remoteAddress() } /// Flush data to the underlying socket and return if this socket needs to be registered for write notifications. /// /// This method can be called re-entrantly but it will return immediately because the first call is responsible /// for sending all flushed writes, even the ones that are accumulated whilst `flushNow()` is running. /// /// - returns: If this socket should be registered for write notifications. Ie. `IONotificationState.register` if /// _not_ all data could be written, so notifications are necessary; and `IONotificationState.unregister` /// if everything was written and we don't need to be notified about writability at the moment. func flushNow() -> IONotificationState { self.eventLoop.assertInEventLoop() // Guard against re-entry as data that will be put into `pendingWrites` will just be picked up by // `writeToSocket`. guard !self.inFlushNow else { return .unregister } assert(!self.inFlushNow) self.inFlushNow = true defer { self.inFlushNow = false } var newWriteRegistrationState: IONotificationState = .unregister do { while newWriteRegistrationState == .unregister && self.hasFlushedPendingWrites() && self.isOpen { assert(self.lifecycleManager.isActive) let writeResult = try self.writeToSocket() switch writeResult.writeResult { case .couldNotWriteEverything: newWriteRegistrationState = .register case .writtenCompletely: newWriteRegistrationState = .unregister } if writeResult.writabilityChange { // We went from not writable to writable. self.pipeline.syncOperations.fireChannelWritabilityChanged() } } } catch let err { // If there is a write error we should try drain the inbound before closing the socket as there may be some data pending. // We ignore any error that is thrown as we will use the original err to close the channel and notify the user. if self.readIfNeeded0() { assert(self.lifecycleManager.isActive) // We need to continue reading until there is nothing more to be read from the socket as we will not have another chance to drain it. var readAtLeastOnce = false while let read = try? self.readFromSocket(), read == .some { readAtLeastOnce = true } if readAtLeastOnce && self.lifecycleManager.isActive { self.pipeline.fireChannelReadComplete() } } self.close0(error: err, mode: .all, promise: nil) // we handled all writes return .unregister } assert((newWriteRegistrationState == .register && self.hasFlushedPendingWrites()) || (newWriteRegistrationState == .unregister && !self.hasFlushedPendingWrites()), "illegal flushNow decision: \(newWriteRegistrationState) and \(self.hasFlushedPendingWrites())") return newWriteRegistrationState } public final func setOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> EventLoopFuture<Void> { if eventLoop.inEventLoop { let promise = eventLoop.makePromise(of: Void.self) executeAndComplete(promise) { try self.setOption0(option, value: value) } return promise.futureResult } else { return eventLoop.submit { try self.setOption0(option, value: value) } } } func setOption0<Option: ChannelOption>(_ option: Option, value: Option.Value) throws { self.eventLoop.assertInEventLoop() guard isOpen else { throw ChannelError.ioOnClosedChannel } switch option { case let option as ChannelOptions.Types.SocketOption: try self.setSocketOption0(level: option.optionLevel, name: option.optionName, value: value) case _ as ChannelOptions.Types.AllocatorOption: bufferAllocator = value as! ByteBufferAllocator case _ as ChannelOptions.Types.RecvAllocatorOption: recvAllocator = value as! RecvByteBufferAllocator case _ as ChannelOptions.Types.AutoReadOption: let auto = value as! Bool let old = self.autoRead self.autoRead = auto // We only want to call read0() or pauseRead0() if we already registered to the EventLoop if not this will be automatically done // once register0 is called. Beside this we also only need to do it when the value actually change. if self.lifecycleManager.isPreRegistered && old != auto { if auto { read0() } else { pauseRead0() } } case _ as ChannelOptions.Types.MaxMessagesPerReadOption: maxMessagesPerRead = value as! UInt default: fatalError("option \(option) not supported") } } public func getOption<Option: ChannelOption>(_ option: Option) -> EventLoopFuture<Option.Value> { if eventLoop.inEventLoop { do { return self.eventLoop.makeSucceededFuture(try self.getOption0(option)) } catch { return self.eventLoop.makeFailedFuture(error) } } else { return self.eventLoop.submit { try self.getOption0(option) } } } func getOption0<Option: ChannelOption>(_ option: Option) throws -> Option.Value { self.eventLoop.assertInEventLoop() guard isOpen else { throw ChannelError.ioOnClosedChannel } switch option { case let option as ChannelOptions.Types.SocketOption: return try self.getSocketOption0(level: option.optionLevel, name: option.optionName) case _ as ChannelOptions.Types.AllocatorOption: return bufferAllocator as! Option.Value case _ as ChannelOptions.Types.RecvAllocatorOption: return recvAllocator as! Option.Value case _ as ChannelOptions.Types.AutoReadOption: return autoRead as! Option.Value case _ as ChannelOptions.Types.MaxMessagesPerReadOption: return maxMessagesPerRead as! Option.Value default: fatalError("option \(option) not supported") } } /// Triggers a `ChannelPipeline.read()` if `autoRead` is enabled.` /// /// - returns: `true` if `readPending` is `true`, `false` otherwise. @discardableResult func readIfNeeded0() -> Bool { self.eventLoop.assertInEventLoop() if !self.lifecycleManager.isActive { return false } if !readPending && autoRead { self.pipeline.syncOperations.read() } return readPending } // Methods invoked from the HeadHandler of the ChannelPipeline public func bind0(to address: SocketAddress, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() guard self.isOpen else { promise?.fail(ChannelError.ioOnClosedChannel) return } executeAndComplete(promise) { try socket.bind(to: address) self.updateCachedAddressesFromSocket(updateRemote: false) } } public final func write0(_ data: NIOAny, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() guard self.isOpen else { // Channel was already closed, fail the promise and not even queue it. promise?.fail(ChannelError.ioOnClosedChannel) return } guard self.lifecycleManager.isActive else { promise?.fail(ChannelError.inappropriateOperationForState) return } bufferPendingWrite(data: data, promise: promise) } private func registerForWritable() { self.eventLoop.assertInEventLoop() guard !self.interestedEvent.contains(.write) else { // nothing to do if we were previously interested in write return } self.safeReregister(interested: self.interestedEvent.union(.write)) } func unregisterForWritable() { self.eventLoop.assertInEventLoop() guard self.interestedEvent.contains(.write) else { // nothing to do if we were not previously interested in write return } self.safeReregister(interested: self.interestedEvent.subtracting(.write)) } public final func flush0() { self.eventLoop.assertInEventLoop() guard self.isOpen else { return } self.markFlushPoint() guard self.lifecycleManager.isActive else { return } if !isWritePending() && flushNow() == .register { assert(self.lifecycleManager.isPreRegistered) registerForWritable() } } public func read0() { self.eventLoop.assertInEventLoop() guard self.isOpen else { return } readPending = true if self.lifecycleManager.isPreRegistered { registerForReadable() } } private final func pauseRead0() { self.eventLoop.assertInEventLoop() if self.lifecycleManager.isPreRegistered { unregisterForReadable() } } private final func registerForReadable() { self.eventLoop.assertInEventLoop() assert(self.lifecycleManager.isRegisteredFully) guard !self.lifecycleManager.hasSeenEOFNotification else { // we have seen an EOF notification before so there's no point in registering for reads return } guard !self.interestedEvent.contains(.read) else { return } self.safeReregister(interested: self.interestedEvent.union(.read)) } private final func registerForReadEOF() { self.eventLoop.assertInEventLoop() assert(self.lifecycleManager.isRegisteredFully) guard !self.lifecycleManager.hasSeenEOFNotification else { // we have seen an EOF notification before so there's no point in registering for reads return } guard !self.interestedEvent.contains(.readEOF) else { return } self.safeReregister(interested: self.interestedEvent.union(.readEOF)) } internal final func unregisterForReadable() { self.eventLoop.assertInEventLoop() assert(self.lifecycleManager.isRegisteredFully) guard self.interestedEvent.contains(.read) else { return } self.safeReregister(interested: self.interestedEvent.subtracting(.read)) } /// Closes the this `BaseChannelChannel` and fulfills `promise` with the result of the _close_ operation. /// So unless either the deregistration or the close itself fails, `promise` will be succeeded regardless of /// `error`. `error` is used to fail outstanding writes (if any) and the `connectPromise` if set. /// /// - parameters: /// - error: The error to fail the outstanding (if any) writes/connect with. /// - mode: The close mode, must be `.all` for `BaseSocketChannel` /// - promise: The promise that gets notified about the result of the deregistration/close operations. public func close0(error: Error, mode: CloseMode, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() guard self.isOpen else { promise?.fail(ChannelError.alreadyClosed) return } guard mode == .all else { promise?.fail(ChannelError.operationUnsupported) return } // === BEGIN: No user callouts === // this is to register all error callouts as all the callouts must happen after we transition out state var errorCallouts: [(ChannelPipeline) -> Void] = [] self.interestedEvent = .reset do { try selectableEventLoop.deregister(channel: self) } catch let err { errorCallouts.append { pipeline in pipeline.syncOperations.fireErrorCaught(err) } } let p: EventLoopPromise<Void>? do { try socket.close() p = promise } catch { errorCallouts.append { (_: ChannelPipeline) in promise?.fail(error) // Set p to nil as we want to ensure we pass nil to becomeInactive0(...) so we not try to notify the promise again. } p = nil } // Transition our internal state. let callouts = self.lifecycleManager.close() // === END: No user callouts (now that our state is reconciled, we can call out to user code.) === // this must be the first to call out as it transitions the PendingWritesManager into the closed state // and we assert elsewhere that the PendingWritesManager has the same idea of 'open' as we have in here. self.cancelWritesOnClose(error: error) // this should be a no-op as we shouldn't have any errorCallouts.forEach { $0(self.pipeline) } if let connectPromise = self.pendingConnect { self.pendingConnect = nil connectPromise.fail(error) } callouts(p, self.pipeline) eventLoop.execute { // ensure this is executed in a delayed fashion as the users code may still traverse the pipeline self.removeHandlers(pipeline: self.pipeline) self.closePromise.succeed(()) // Now reset the addresses as we notified all handlers / futures. self.unsetCachedAddressesFromSocket() } } public final func register0(promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() guard self.isOpen else { promise?.fail(ChannelError.ioOnClosedChannel) return } guard !self.lifecycleManager.isPreRegistered else { promise?.fail(ChannelError.inappropriateOperationForState) return } guard self.selectableEventLoop.isOpen else { let error = EventLoopError.shutdown self.pipeline.syncOperations.fireErrorCaught(error) // `close0`'s error is about the result of the `close` operation, ... self.close0(error: error, mode: .all, promise: nil) // ... therefore we need to fail the registration `promise` separately. promise?.fail(error) return } // we can't fully register yet as epoll would give us EPOLLHUP if bind/connect wasn't called yet. self.lifecycleManager.beginRegistration()(promise, self.pipeline) } public final func registerAlreadyConfigured0(promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() assert(self.isOpen) assert(!self.lifecycleManager.isActive) let registerPromise = self.eventLoop.makePromise(of: Void.self) self.register0(promise: registerPromise) registerPromise.futureResult.whenFailure { (_: Error) in self.close(promise: nil) } registerPromise.futureResult.cascadeFailure(to: promise) if self.lifecycleManager.isPreRegistered { // we expect kqueue/epoll registration to always succeed which is basically true, except for errors that // should be fatal (EBADF, EFAULT, ESRCH, ENOMEM) and a two 'table full' (EMFILE, ENFILE) error kinds which // we don't handle yet but might do in the future (#469). try! becomeFullyRegistered0() if self.lifecycleManager.isRegisteredFully { self.becomeActive0(promise: promise) } } } public final func triggerUserOutboundEvent0(_ event: Any, promise: EventLoopPromise<Void>?) { promise?.fail(ChannelError.operationUnsupported) } // Methods invoked from the EventLoop itself public final func writable() { self.eventLoop.assertInEventLoop() assert(self.isOpen) self.finishConnect() // If we were connecting, that has finished. switch self.flushNow() { case .unregister: // Everything was written or connect was complete, let's unregister from writable. self.finishWritable() case .register: assert(!self.isOpen || self.interestedEvent.contains(.write)) () // nothing to do because given that we just received `writable`, we're still registered for writable. } } private func finishConnect() { self.eventLoop.assertInEventLoop() assert(self.lifecycleManager.isPreRegistered) if let connectPromise = self.pendingConnect { assert(!self.lifecycleManager.isActive) do { try self.finishConnectSocket() } catch { assert(!self.lifecycleManager.isActive) // close0 fails the connectPromise itself so no need to do it here self.close0(error: error, mode: .all, promise: nil) return } // now this has succeeded, becomeActive0 will actually fulfill this. self.pendingConnect = nil // We already know what the local address is. self.updateCachedAddressesFromSocket(updateLocal: false, updateRemote: true) self.becomeActive0(promise: connectPromise) } else { assert(self.lifecycleManager.isActive) } } private func finishWritable() { self.eventLoop.assertInEventLoop() if self.isOpen { assert(self.lifecycleManager.isPreRegistered) assert(!self.hasFlushedPendingWrites()) self.unregisterForWritable() } } func writeEOF() { fatalError("\(self) received writeEOF which is unexpected") } func readEOF() { assert(!self.lifecycleManager.hasSeenEOFNotification) self.lifecycleManager.hasSeenEOFNotification = true // we can't be not active but still registered here; this would mean that we got a notification about a // channel before we're ready to receive them. assert(self.lifecycleManager.isRegisteredFully, "illegal state: \(self): active: \(self.lifecycleManager.isActive), registered: \(self.lifecycleManager.isRegisteredFully)") self.readEOF0() assert(!self.interestedEvent.contains(.read)) assert(!self.interestedEvent.contains(.readEOF)) } final func readEOF0() { if self.lifecycleManager.isRegisteredFully { // we're unregistering from `readEOF` here as we want this to be one-shot. We're then synchronously // reading all input until the EOF that we're guaranteed to see. After that `readEOF` becomes uninteresting // and would anyway fire constantly. self.safeReregister(interested: self.interestedEvent.subtracting(.readEOF)) loop: while self.lifecycleManager.isActive { switch self.readable0() { case .eof: // on EOF we stop the loop and we're done with our processing for `readEOF`. // we could both be registered & active (if our channel supports half-closure) or unregistered & inactive (if it doesn't). break loop case .error: // we should be unregistered and inactive now (as `readable0` would've called close). assert(!self.lifecycleManager.isActive) assert(!self.lifecycleManager.isPreRegistered) break loop case .normal(.none): preconditionFailure("got .readEOF and read returned not reading any bytes, nor EOF.") case .normal(.some): // normal, note that there is no guarantee we're still active (as the user might have closed in callout) continue loop } } } } // this _needs_ to synchronously cause the fd to be unregistered because we cannot unregister from `reset`. In // other words: Failing to unregister the whole selector will cause NIO to spin at 100% CPU constantly delivering // the `reset` event. final func reset() { self.readEOF0() if self.socket.isOpen { assert(self.lifecycleManager.isPreRegistered) let error: IOError // if the socket is still registered (and therefore open), let's try to get the actual socket error from the socket do { let result: Int32 = try self.socket.getOption(level: .socket, name: .so_error) if result != 0 { // we have a socket error, let's forward // this path will be executed on Linux (EPOLLERR) & Darwin (ev.fflags != 0) error = IOError(errnoCode: result, reason: "connection reset (error set)") } else { // we don't have a socket error, this must be connection reset without an error then // this path should only be executed on Linux (EPOLLHUP, no EPOLLERR) #if os(Linux) let message: String = "connection reset (no error set)" #else let message: String = "BUG IN SwiftNIO (possibly #572), please report! Connection reset (no error set)." #endif error = IOError(errnoCode: ECONNRESET, reason: message) } self.close0(error: error, mode: .all, promise: nil) } catch { self.close0(error: error, mode: .all, promise: nil) } } assert(!self.lifecycleManager.isPreRegistered) } public final func readable() { assert(!self.lifecycleManager.hasSeenEOFNotification, "got a read notification after having already seen .readEOF") self.readable0() } @discardableResult private final func readable0() -> ReadStreamState { self.eventLoop.assertInEventLoop() assert(self.lifecycleManager.isActive) defer { if self.isOpen && !self.readPending { unregisterForReadable() } } let readResult: ReadResult do { readResult = try self.readFromSocket() } catch let err { let readStreamState: ReadStreamState // ChannelError.eof is not something we want to fire through the pipeline as it just means the remote // peer closed / shutdown the connection. if let channelErr = err as? ChannelError, channelErr == ChannelError.eof { readStreamState = .eof // Directly call getOption0 as we are already on the EventLoop and so not need to create an extra future. // getOption0 can only fail if the channel is not active anymore but we assert further up that it is. If // that's not the case this is a precondition failure and we would like to know. if self.lifecycleManager.isActive, try! self.getOption0(ChannelOptions.allowRemoteHalfClosure) { // If we want to allow half closure we will just mark the input side of the Channel // as closed. assert(self.lifecycleManager.isActive) self.pipeline.syncOperations.fireChannelReadComplete() if self.shouldCloseOnReadError(err) { self.close0(error: err, mode: .input, promise: nil) } self.readPending = false return .eof } } else { readStreamState = .error self.pipeline.syncOperations.fireErrorCaught(err) } // Call before triggering the close of the Channel. if readStreamState != .error, self.lifecycleManager.isActive { self.pipeline.syncOperations.fireChannelReadComplete() } if self.shouldCloseOnReadError(err) { self.close0(error: err, mode: .all, promise: nil) } return readStreamState } // This assert needs to be disabled for io_uring, as the io_uring backend does not have the implicit synchronisation between // modifications to the poll mask and the actual returned events on the completion queue that kqueue and epoll has. // For kqueue and epoll, there is an implicit synchronisation point such that after a modification of the poll mask has been // issued, the next call to reap events will be sure to not include events which does not match the new poll mask. // Specifically for this assert, it means that we will be guaranteed to never receive a POLLIN notification unless there are // bytes available to read. // For a fully asynchronous backend like io_uring, there are no such implicit synchronisation point, so after we have // submitted the asynchronous event to change the poll mask, we may still reap pending asynchronous replies for the old // poll mask, and thus receive a POLLIN even though we have modified the mask visavi the kernel. // Which would trigger the assert. // The only way to avoid that race, would be to use heavy handed synchronisation primitives like IOSQE_IO_DRAIN (basically // flushing all pending requests and wait for a fake event result to sync up) which would be awful for performance, // so better skip the assert() for io_uring instead. #if !SWIFTNIO_USE_IO_URING assert(readResult == .some) #endif if self.lifecycleManager.isActive { self.pipeline.syncOperations.fireChannelReadComplete() } self.readIfNeeded0() return .normal(readResult) } /// Returns `true` if the `Channel` should be closed as result of the given `Error` which happened during `readFromSocket`. /// /// - parameters: /// - err: The `Error` which was thrown by `readFromSocket`. /// - returns: `true` if the `Channel` should be closed, `false` otherwise. func shouldCloseOnReadError(_ err: Error) -> Bool { return true } internal final func updateCachedAddressesFromSocket(updateLocal: Bool = true, updateRemote: Bool = true) { self.eventLoop.assertInEventLoop() assert(updateLocal || updateRemote) let cached = self.addressesCached let local = updateLocal ? try? self.localAddress0() : cached.local let remote = updateRemote ? try? self.remoteAddress0() : cached.remote self.addressesCached = AddressCache(local: local, remote: remote) } internal final func unsetCachedAddressesFromSocket() { self.eventLoop.assertInEventLoop() self.addressesCached = AddressCache(local: nil, remote: nil) } public final func connect0(to address: SocketAddress, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() guard self.isOpen else { promise?.fail(ChannelError.ioOnClosedChannel) return } guard pendingConnect == nil else { promise?.fail(ChannelError.connectPending) return } guard self.lifecycleManager.isPreRegistered else { promise?.fail(ChannelError.inappropriateOperationForState) return } do { if try !self.connectSocket(to: address) { // We aren't connected, we'll get the remote address later. self.updateCachedAddressesFromSocket(updateLocal: true, updateRemote: false) if promise != nil { self.pendingConnect = promise } else { self.pendingConnect = eventLoop.makePromise() } try self.becomeFullyRegistered0() self.registerForWritable() } else { self.updateCachedAddressesFromSocket() self.becomeActive0(promise: promise) } } catch let error { assert(self.lifecycleManager.isPreRegistered) // We would like to have this assertion here, but we want to be able to go through this // code path in cases where connect() is being called on channels that are already active. //assert(!self.lifecycleManager.isActive) // We're going to set the promise as the pending connect promise, and let close0 fail it for us. self.pendingConnect = promise self.close0(error: error, mode: .all, promise: nil) } } public func channelRead0(_ data: NIOAny) { // Do nothing by default // note: we can't assert that we're active here as TailChannelHandler will call this on channelRead } public func errorCaught0(error: Error) { // Do nothing } private func isWritePending() -> Bool { return self.interestedEvent.contains(.write) } private final func safeReregister(interested: SelectorEventSet) { self.eventLoop.assertInEventLoop() assert(self.lifecycleManager.isRegisteredFully) guard self.isOpen else { assert(self.interestedEvent == .reset, "interestedEvent=\(self.interestedEvent) even though we're closed") return } if interested == interestedEvent { // we don't need to update and so cause a syscall if we already are registered with the correct event return } interestedEvent = interested do { try selectableEventLoop.reregister(channel: self) } catch let err { self.pipeline.syncOperations.fireErrorCaught(err) self.close0(error: err, mode: .all, promise: nil) } } private func safeRegister(interested: SelectorEventSet) throws { self.eventLoop.assertInEventLoop() assert(!self.lifecycleManager.isRegisteredFully) guard self.isOpen else { throw ChannelError.ioOnClosedChannel } self.interestedEvent = interested do { try self.selectableEventLoop.register(channel: self) } catch { self.pipeline.syncOperations.fireErrorCaught(error) self.close0(error: error, mode: .all, promise: nil) throw error } } final func becomeFullyRegistered0() throws { self.eventLoop.assertInEventLoop() assert(self.lifecycleManager.isPreRegistered) assert(!self.lifecycleManager.isRegisteredFully) // The initial set of interested events must not contain `.readEOF` because when connect doesn't return // synchronously, kevent might send us a `readEOF` because the `writable` event that marks the connect as completed. // See SocketChannelTest.testServerClosesTheConnectionImmediately for a regression test. try self.safeRegister(interested: [.reset]) self.lifecycleManager.finishRegistration()(nil, self.pipeline) } final func becomeActive0(promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() assert(self.lifecycleManager.isPreRegistered) if !self.lifecycleManager.isRegisteredFully { do { try self.becomeFullyRegistered0() assert(self.lifecycleManager.isRegisteredFully) } catch { self.close0(error: error, mode: .all, promise: promise) return } } self.lifecycleManager.activate()(promise, self.pipeline) guard self.lifecycleManager.isOpen else { // in the user callout for `channelActive` the channel got closed. return } self.registerForReadEOF() self.readIfNeeded0() } func register(selector: Selector<NIORegistration>, interested: SelectorEventSet) throws { fatalError("must override") } func deregister(selector: Selector<NIORegistration>, mode: CloseMode) throws { fatalError("must override") } func reregister(selector: Selector<NIORegistration>, interested: SelectorEventSet) throws { fatalError("must override") } } extension BaseSocketChannel { public struct SynchronousOptions: NIOSynchronousChannelOptions { @usableFromInline // should be private internal let _channel: BaseSocketChannel<SocketType> @inlinable // should be fileprivate internal init(_channel channel: BaseSocketChannel<SocketType>) { self._channel = channel } @inlinable public func setOption<Option: ChannelOption>(_ option: Option, value: Option.Value) throws { try self._channel.setOption0(option, value: value) } @inlinable public func getOption<Option: ChannelOption>(_ option: Option) throws -> Option.Value { return try self._channel.getOption0(option) } } public final var syncOptions: NIOSynchronousChannelOptions? { return SynchronousOptions(_channel: self) } } /// Execute the given function and synchronously complete the given `EventLoopPromise` (if not `nil`). func executeAndComplete<Value>(_ promise: EventLoopPromise<Value>?, _ body: () throws -> Value) { do { let result = try body() promise?.succeed(result) } catch let e { promise?.fail(e) } }
apache-2.0
ae2cf8ea2f18451818a62a7c45c18811
38.247774
214
0.627471
4.991603
false
false
false
false
lenssss/whereAmI
Whereami/Controller/Personal/PersonalSettingsViewController.swift
1
7225
// // PersonalSettingsViewController.swift // Whereami // // Created by A on 16/5/23. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit import FBSDKLoginKit import Kingfisher import MBProgressHUD import SDWebImage class PersonalSettingsViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { typealias cacheCompletion = (Double) -> Void var tableView:UITableView? = nil var cacheSize:Double? = 0 override func viewDidLoad() { super.viewDidLoad() self.setConfig() self.calculateDiskCacheSizeWithCompletionHandler { (size) in self.cacheSize = size self.tableView?.reloadData() } self.setUI() } func setUI(){ let backBtn = TheBackBarButton.initWithAction({ let viewControllers = self.navigationController?.viewControllers let index = (viewControllers?.count)! - 2 let viewController = viewControllers![index] self.navigationController?.popToViewController(viewController, animated: true) }) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn) self.tableView = UITableView(frame: self.view.bounds) self.tableView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0) self.tableView?.delegate = self self.tableView?.dataSource = self self.tableView?.tableFooterView = UIView() self.view.addSubview(tableView!) self.tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell") } func numberOfSectionsInTableView(tableView: UITableView) -> Int{ return 5 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 || section == 2 || section == 3 || section == 4 { return 1 } else{ return 2 } } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == 4 { return 0 } else{ return 13 } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50 } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let view = UIView() view.backgroundColor = UIColor.clearColor() return view } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath) cell.selectionStyle = .None cell.accessoryType = .DisclosureIndicator if indexPath.section == 0 { cell.textLabel?.text = "Account and Security" } else if indexPath.section == 1 { if indexPath.row == 0 { cell.textLabel?.text = "Message Notification" } else{ cell.textLabel?.text = "Sound" } } else if indexPath.section == 2 { let cacheString = String(format: "%.2fM", cacheSize!) cell.textLabel?.text = "Clear cache(\(cacheString))" } else if indexPath.section == 3 { cell.textLabel?.text = "About us" } else{ cell.accessoryType = .None let button = UIButton() button.frame = cell.bounds button.backgroundColor = UIColor(red: 246/255.0, green: 137/255.0, blue: 140/255.0, alpha: 1) button.setTitle("Sign out", forState: .Normal) button.setTitleColor(UIColor.whiteColor(), forState: .Normal) button.rac_signalForControlEvents(.TouchUpInside).subscribeNext({ (button) in self.logOut() }) cell.contentView.addSubview(button) } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 0 { let viewController = PersonalEditViewController() self.navigationController?.pushViewController(viewController, animated: true) } else if indexPath.section == 1 { if indexPath.row == 0 { self.present2setting() } else{ self.present2setting() } } else if indexPath.section == 2 { SDImageCache.sharedImageCache().clearDisk() KingfisherManager.sharedManager.cache.clearDiskCache() self.calculateDiskCacheSizeWithCompletionHandler { (size) in self.cacheSize = size self.tableView?.reloadData() } } else{ } } func calculateDiskCacheSizeWithCompletionHandler(completion:cacheCompletion){ var imageSize = 0 let cache = KingfisherManager.sharedManager.cache cache.calculateDiskCacheSizeWithCompletionHandler { (size) in imageSize += Int(size) let SDCache = SDImageCache.sharedImageCache() SDCache.calculateSizeWithCompletionBlock({ (fileCount, totalSize) in imageSize += Int(totalSize) let size = Double(imageSize)/(1024.0*1024) completion(size) }) } } func logOut(){ if FBSDKAccessToken.currentAccessToken() != nil { let manager = FBSDKLoginManager() manager.logOut() // let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage() // let httpCookies = cookies.cookiesForURL(NSURL(string: "http://login.facebook.com")!) // for cookie in httpCookies! { // cookies.deleteCookie(cookie) // } // let httpsCookies = cookies.cookiesForURL(NSURL(string: "https://login.facebook.com")!) // for cookie in httpsCookies! { // cookies.deleteCookie(cookie) // } } let userDefaults = LUserDefaults() userDefaults.removeObjectForKey("sessionId") userDefaults.removeObjectForKey("uniqueId") userDefaults.synchronize() SocketManager.sharedInstance.disconnection() SocketManager.sharedInstance.connection { (ifConnected:Bool) in if ifConnected { } } JPUSHService.setAlias("", callbackSelector: nil, object: nil) let currentWindow = (LApplication().delegate!.window)! currentWindow!.rootViewController = LoginNavViewController(rootViewController: ChooseLoginItemViewController()) } func present2setting(){ let url = NSURL(string: UIApplicationOpenSettingsURLString) if LApplication().canOpenURL(url!){ LApplication().openURL(url!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
dd3ffce54d6316a20ce8c4957ff0f7bc
33.721154
119
0.599834
5.525631
false
false
false
false
stephentyrone/swift
test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-struct-1argument-1distinct_use.swift
3
4364
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main9NamespaceV5ValueOySS_SiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main9NamespaceV5ValueOySS_SiGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 513, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main9NamespaceV5ValueOMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ), // CHECK-SAME: %swift.type* @"$sSSN", // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] struct Namespace<Arg> { enum Value<First> { case first(First) } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}}, // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main9NamespaceV5ValueOySS_SiGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ) // CHECK-SAME: ) // CHECK: } func doit() { consume( Namespace<String>.Value.first(13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceV5ValueOMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8* // CHECK: br label %[[TYPE_COMPARISON_1:[0-9]+]] // CHECK: [[TYPE_COMPARISON_1]]: // CHECK: [[EQUAL_TYPE_1_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSSN" to i8*), [[ERASED_TYPE_1]] // CHECK: [[EQUAL_TYPES_1_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_1_1]] // CHECK: [[EQUAL_TYPE_1_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_2]] // CHECK: [[EQUAL_TYPES_1_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_1]], [[EQUAL_TYPE_1_2]] // CHECK: br i1 [[EQUAL_TYPES_1_2]], label %[[EXIT_PRESPECIALIZED_1:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]] // CHECK: [[EXIT_PRESPECIALIZED_1]]: // CHECK: ret %swift.metadata_response { // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main9NamespaceV5ValueOySS_SiGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ), // CHECK-SAME: [[INT]] 0 // CHECK-SAME: } // CHECK: [[EXIT_NORMAL]]: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( // CHECK-SAME: [[INT]] %0, // CHECK-SAME: i8* [[ERASED_TYPE_1]], // CHECK-SAME: i8* [[ERASED_TYPE_2]], // CHECK-SAME: i8* undef, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main9NamespaceV5ValueOMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ) // CHECK-SAME: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
b770a6f697bb3d844c6878f7d0ae613f
40.169811
157
0.574473
2.932796
false
false
false
false
mirai418/leaflet-ios
leaflet/CircleView.swift
1
2309
// // CircleView.swift // leaflet // // Created by Cindy Zeng on 4/25/15. // Copyright (c) 2015 parks-and-rec. All rights reserved. // import UIKit class CircleView: UIView { var circleLayer: CAShapeLayer! var progress: CGFloat! override init(frame: CGRect) { super.init(frame: frame) self.progress = 0.0 self.backgroundColor = UIColor.clearColor() // Use UIBezierPath as an easy way to create the CGPath for the layer. // The path should be the entire circle. let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true) // Setup the CAShapeLayer with the path, colors, and line width circleLayer = CAShapeLayer() circleLayer.path = circlePath.CGPath circleLayer.fillColor = UIColor.clearColor().CGColor circleLayer.lineWidth = 5.0 circleLayer.strokeColor = UIColor.whiteColor().CGColor // Don't draw the circle initially circleLayer.strokeEnd = 0.0 // Add the circleLayer to the view's layer's sublayers layer.addSublayer(circleLayer) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func animateCircle(duration: NSTimeInterval) { // We want to animate the strokeEnd property of the circleLayer let animation = CABasicAnimation(keyPath: "strokeEnd") // Set the animation duration appropriately animation.duration = duration // Animate from 0 (no circle) to 1 (full circle) animation.fromValue = 0 animation.toValue = self.progress // Do a linear animation (i.e. the speed of the animation stays the same) animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) // Set the circleLayer's strokeEnd property to 1.0 now so that it's the // right value when the animation ends. circleLayer.strokeEnd = self.progress // Do the actual animation circleLayer.addAnimation(animation, forKey: "animateCircle") } }
mit
56dcd757047f86bcba6ffbc086337f2d
35.078125
212
0.641403
4.751029
false
false
false
false
larryhou/swift
URLoadingSystem/URLoadingSystem/ViewController.swift
1
1293
// // ViewController.swift // URLoadingSystem // // Created by larryhou on 3/23/15. // Copyright (c) 2015 larryhou. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() performSessionTask() } func performSessionTask() { var proxy: [NSObject: AnyObject] = [:] proxy.updateValue(kCFProxyTypeHTTP, forKey: kCFProxyTypeKey) proxy.updateValue("proxy.tencent.com", forKey: kCFProxyHostNameKey) proxy.updateValue("8080", forKey: kCFProxyPortNumberKey) let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: NSOperationQueue.mainQueue()) session.downloadTaskWithURL(NSURL(string: "https://www.baidu.com/")!, completionHandler: { (url: NSURL!, response: NSURLResponse!, _: NSError!) in let cfencoding = CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue) let nsencoding = CFStringConvertEncodingToNSStringEncoding(cfencoding) let contents = NSString(data: NSData(contentsOfURL: url)!, encoding: nsencoding) println(contents) println(response) }).resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
9ca0e090a12c0505d2c54571cefe826a
29.069767
160
0.755607
4.157556
false
true
false
false
cikelengfeng/SQLighter
SQLighter/SQLighter/main.swift
1
2372
// // main.swift // SQLighter // // Created by 徐 东 on 16/9/11. // Copyright © 2016年 Dean Xu Lab. All rights reserved. // import Foundation let str = "xxxxxxxxxxxxxxxx" let int = 1 //let select = SQLStmt() // .select("*") // .from("tbl_tags") // .where_( // [User.name.like("3"), // OR, // User.id.not().in_("x", 1, 3)], // [User.creationDate == "x", // User.id < int], // OR, // [ID("c") != "ono", // OR, // ID("d").in_(paramArr: ["1","b","c","123"])]) // .orderBy(("c1", Order.ASC), ("c2", Order.DESC)) // .offset(42) // .limit(22) // //print(select.assemble()) //print(select.parameters()) let select2 = SQLStmt() .select("c1","c3") .from("tbl_tags") .where_( ID("a") == "x", ID("b") < 1, ID("c") != "ono", ID("d").in_("1","b","c", 123)) .orderBy(orderArr: [("c1", Order.ASC), ("c2", Order.DESC)]) .offset(42) .limit(22) //let un = UNION(select, rhs: select2) //print(un.assemble()) //print(un.parameters()) let insert = SQLStmt() .insert() .table("tbl_tags") .columns(["c1","c2"]) .values([["x1","x2"],["y1","y2"]]) print(insert.assemble()) print(insert.parameters()) let update = SQLStmt() .update() .table("tbl_people") .set(["c1":"x1","c2":"x2"]) .where_( ID("a") == "x", ID("b") < "y", OR, ID("c") <> "ono", ID("d").not().in_("1","b","c","123")) print(update.assemble()) print(update.parameters()) let delete = SQLStmt() .delete() .from("tbl_medias") .where_( [[ID("a") == "x", ID("x").not().in_("x1","x2")], [ID("b") < "y",ID("y") & "y1"]], OR, ID("c") <> "ono", ID("d").in_("1","b","c","123") ) print(delete.assemble()) print(delete.parameters()) let sql = SQLStatment(plainSQL: "", parameters: []) print(sql.insert().context) print(sql.insert().complete().test().context)
mit
8554b922fbbd70500f73b6fad4bfc3de
25.875
75
0.396195
3.393113
false
false
false
false
SPECURE/rmbt-ios-client
Sources/MapServer.swift
1
8393
/***************************************************************************************************** * Copyright 2016 SPECURE GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************************************/ import Foundation import CoreLocation import Alamofire import AlamofireObjectMapper import ObjectMapper /// open class MapServer { /// public static let sharedMapServer = MapServer() /// private let alamofireManager: Alamofire.Session /// private let settings = RMBTSettings.sharedSettings /// private var baseUrl: String? { return ControlServer.sharedControlServer.mapServerBaseUrl // don't store in variable, could be changed in settings } /// private init() { alamofireManager = ServerHelper.configureAlamofireManager() } /// deinit { alamofireManager.session.invalidateAndCancel() } // MARK: MapServer /// open func getMapFilterOperators(for countryCode: String = "all", type: OperatorsRequest.ProviderType = .all, success successCallback: @escaping (_ response: OperatorsResponse) -> (), error failure: @escaping ErrorCallback) { request(.post, path: "/tiles/mapFilterOperators", requestObject: OperatorsRequest(countryCode: countryCode, type: type), success: { (response: OperatorsResponse) in successCallback(response) } , error: failure) } /// open func getMapOptions(success successCallback: @escaping (_ response: MapOptionResponse) -> (), error failure: @escaping ErrorCallback) { request(.post, path: "/tiles/info", requestObject: BasicRequest(), success: { (response: MapOptionResponse) in successCallback(response) } , error: failure) } /// open func getMeasurementsAtCoordinate(_ coordinate: CLLocationCoordinate2D, zoom: Int, params: [String: Any], success successCallback: @escaping (_ response: [SpeedMeasurementResultResponse]) -> (), error failure: @escaping ErrorCallback) { let mapMeasurementRequest = MapMeasurementRequest() mapMeasurementRequest.coords = MapMeasurementRequest.CoordObject() mapMeasurementRequest.coords?.latitude = coordinate.latitude mapMeasurementRequest.coords?.longitude = coordinate.longitude mapMeasurementRequest.coords?.zoom = zoom mapMeasurementRequest.options = params["options"] as? [String : AnyObject] mapMeasurementRequest.filter = params["filter"] as? [String : AnyObject] mapMeasurementRequest.prioritizeUuid = mapMeasurementRequest.clientUuid // add highlight filter (my measurements filter) //mapMeasurementRequest.filter?["highlight"] = ControlServer.sharedControlServer.uuid // submit client_uuid to get measurement_uuid if tapped on an own measurement mapMeasurementRequest.clientUuid = ControlServer.sharedControlServer.uuid request(.post, path: "/tiles/markers", requestObject: mapMeasurementRequest, success: { (response: MapMeasurementResponse) in if let measurements = response.measurements { successCallback(measurements) } else { failure(NSError(domain: "no measurements", code: -12543, userInfo: nil)) } }, error: failure) } open func getTileUrlForMapBoxOverlayType(_ overlayType: String, params: [String: Any]?) -> String? { if let base = baseUrl { // baseUrl and layer var urlString = base + "/tiles/\(overlayType)/{z}/{x}/{y}.png?v=1" // add uuid for highlight if let uuid = ControlServer.sharedControlServer.uuid { urlString += "&highlight=\(uuid)" } // add params if let p = params, p.count > 0 { let paramString = p.map({ (key, value) in let escapedKey = key.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) var escapedValue: String? if let v = value as? String { escapedValue = v.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) // TODO: does this need a cast to string? } else if let numValue = value as? NSNumber { escapedValue = String(describing: numValue) } return "\(escapedKey ?? key)=\(escapedValue ?? value as! String)" }).joined(separator: "&") urlString += "&" + paramString } Log.logger.debug("Generated tile url: \(urlString)") print(urlString) return urlString } return nil } /// open func getTileUrlForMapOverlayType(_ overlayType: String, x: UInt, y: UInt, zoom: UInt, params: [String: Any]?) -> URL? { if let base = baseUrl { // baseUrl and layer var urlString = base + "/tiles/\(overlayType)?path=\(zoom)/\(x)/\(y)" // add uuid for highlight if let uuid = ControlServer.sharedControlServer.uuid { urlString += "&highlight=\(uuid)" } // add params if let p = params, p.count > 0 { let paramString = p.map({ (key, value) in let escapedKey = key.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) var escapedValue: String? if let v = value as? String { escapedValue = v.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) // TODO: does this need a cast to string? } else if let numValue = value as? NSNumber { escapedValue = String(describing: numValue) } return "\(escapedKey ?? key)=\(escapedValue ?? value as! String)" }).joined(separator: "&") urlString += "&" + paramString } Log.logger.debug("Generated tile url: \(urlString)") print(urlString) return URL(string: urlString) } return nil } /// open func getOpenTestUrl(_ openTestUuid: String, success successCallback: (_ response: String?) -> ()) { if let url = ControlServer.sharedControlServer.openTestBaseURL { let theURL = url+openTestUuid successCallback(theURL) } successCallback(nil) } // MARK: Private /// private func opentestURLForApp(_ openTestBaseURL: String) -> String { // hardcoded because @lb doesn't want to provide a good solution let r = openTestBaseURL.startIndex..<openTestBaseURL.endIndex let appOpenTestBaseURL = openTestBaseURL.replacingOccurrences(of: "/opentest", with: "/app/opentest", options: NSString.CompareOptions.literal, range: r) return appOpenTestBaseURL } /// private func requestArray<T: BasicResponse>(_ method: Alamofire.HTTPMethod, path: String, requestObject: BasicRequest?, success: @escaping (_ response: [T]) -> (), error failure: @escaping ErrorCallback) { ServerHelper.requestArray(alamofireManager, baseUrl: baseUrl, method: method, path: path, requestObject: requestObject, success: success, error: failure) } /// private func request<T: BasicResponse>(_ method: Alamofire.HTTPMethod, path: String, requestObject: BasicRequest?, success: @escaping (_ response: T) -> (), error failure: @escaping ErrorCallback) { ServerHelper.request(alamofireManager, baseUrl: baseUrl, method: method, path: path, requestObject: requestObject, success: success, error: failure) } }
apache-2.0
4d001146a6b188b52d063cbaa9474224
40.549505
244
0.609079
5.184064
false
true
false
false
spritekitbook/flappybird-swift
Chapter 9/Start/FloppyBird/FloppyBird/Tutorial.swift
5
1400
// // Tutorial.swift // FloppyBird // // Created by Jeremy Novak on 9/26/16. // Copyright © 2016 SpriteKit Book. All rights reserved. // import SpriteKit class Tutorial:SKSpriteNode { // MARK: - Init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(texture: SKTexture?, color: UIColor, size: CGSize) { super.init(texture: texture, color: color, size: size) } convenience init() { let texture = Textures.sharedInstance.textureWith(name: SpriteName.tutorial) self.init(texture: texture, color: SKColor.white, size: texture.size()) setup() setupPhysics() } // MARK: - Setup private func setup() { self.position = kScreenCenter } private func setupPhysics() { } // MARK: - Update func update(delta: TimeInterval) { } // MARK: - Actions private func animate() { } // MARK: - Tapped func tapepd() { let scaleUp = SKAction.scale(to: 1.1, duration: 0.25) let scaleDown = SKAction.scale(to: 0.0, duration: 0.5) let completion = SKAction.removeFromParent() let sequence = SKAction.sequence([scaleUp, scaleDown, completion]) self.run(sequence) self.run(Sound.sharedInstance.playSound(sound: .pop)) } }
apache-2.0
6828f0e67ff2087b4a86241a7c052173
22.711864
84
0.586848
4.139053
false
false
false
false
Mobilette/Swift-best-practices
Mobilette.playground/Sources/Alamofire.swift
1
1390
import Foundation public protocol URLRequestConvertible { var URLRequest: NSMutableURLRequest { get } } extension NSURLRequest: URLRequestConvertible { public var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest } } public class Alamofire { public enum Method: String { case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT } public enum ParameterEncoding { case JSON public func encode( URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSMutableURLRequest, NSError?) { let mutableURLRequest = URLRequest.URLRequest guard let parameters = parameters else { return (mutableURLRequest, nil) } var encodingError: NSError? = nil do { let options = NSJSONWritingOptions() let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError } return (mutableURLRequest, encodingError) } } }
mit
379b5dbd6edb3cd4aed2b6c4a8ebb17a
30.613636
99
0.592806
6.40553
false
false
false
false
arvedviehweger/swift
test/ClangImporter/enum-error.swift
1
4510
// REQUIRES: OS=macosx // RUN: %target-swift-frontend -DVALUE -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=VALUE // RUN: %target-swift-frontend -DEMPTYCATCH -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=EMPTYCATCH // RUN: %target-swift-frontend -DASQEXPR -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=ASQEXPR // RUN: %target-swift-frontend -DASBANGEXPR -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=ASBANGEXPR // RUN: %target-swift-frontend -DCATCHIS -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=CATCHIS // RUN: %target-swift-frontend -DCATCHAS -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=CATCHAS // RUN: %target-swift-frontend -DGENERICONLY -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=GENERICONLY // RUN: not %target-swift-frontend -DEXHAUSTIVE -emit-sil %s -import-objc-header %S/Inputs/enum-error.h 2>&1 | %FileCheck %s -check-prefix=EXHAUSTIVE // RUN: %target-swift-frontend -typecheck %s -import-objc-header %S/Inputs/enum-error.h -DERRORS -verify // RUN: echo '#include "enum-error.h"' > %t.m // RUN: %target-swift-ide-test -source-filename %s -print-header -header-to-print %S/Inputs/enum-error.h -import-objc-header %S/Inputs/enum-error.h -print-regular-comments --cc-args %target-cc-options -fsyntax-only %t.m -I %S/Inputs > %t.txt // RUN: %FileCheck -check-prefix=HEADER %s < %t.txt import Foundation func testDropCode(other: OtherError) -> OtherError.Code { return other.code } func testError() { let testErrorNSError = NSError(domain: TestErrorDomain, code: Int(TestError.TENone.rawValue), userInfo: nil) // Below are a number of test cases to make sure that various pattern and cast // expression forms are sufficient in pulling in the _NSBridgedError // conformance. #if VALUE // VALUE: TestError: _BridgedStoredNSError let terr = getErr(); terr #elseif EMPTYCATCH // EMPTYCATCH: TestError: _BridgedStoredNSError do { throw TestError(.TENone) } catch {} #elseif ASQEXPR // ASQEXPR: sil_witness_table shared [serialized] TestError: _BridgedStoredNSError module __ObjC let wasTestError = testErrorNSError as? TestError; wasTestError #elseif ASBANGEXPR // ASBANGEXPR: sil_witness_table shared [serialized] TestError: _BridgedStoredNSError module __ObjC let terr2 = testErrorNSError as! TestError; terr2 #elseif ISEXPR // ISEXPR: sil_witness_table shared [serialized] TestError: _BridgedStoredNSError module __ObjC if (testErrorNSError is TestError) { print("true") } else { print("false") } #elseif CATCHIS // CATCHIS: sil_witness_table shared [serialized] TestError: _BridgedStoredNSError module __ObjC do { throw TestError(.TETwo) } catch is TestError { } catch {} #elseif CATCHAS // CATCHAS: sil_witness_table shared [serialized] TestError: _BridgedStoredNSError module __ObjC do { throw TestError(.TETwo) } catch let err as TestError { err } catch {} #elseif GENERICONLY // GENERICONLY: TestError: _BridgedStoredNSError func dyncast<T, U>(_ x: T) -> U { return x as! U } let _ : TestError = dyncast(testErrorNSError) #elseif EXHAUSTIVE // CHECK: sil_witness_table shared [serialized] TestError: _BridgedStoredNSError module __ObjC let terr = getErr() switch (terr) { case .TENone, .TEOne, .TETwo: break } // ok switch (terr) { case .TENone, .TEOne: break } // EXHAUSTIVE: [[@LINE-1]]:{{.+}}: error: switch must be exhaustive, consider adding missing cases // EXHAUSTIVE: [[@LINE-2]]:{{.+}}: note: missing case: '.TETwo' let _ = TestError.Code(rawValue: 2)! do { throw TestError(.TEOne) } catch is TestError { } catch {} #endif } #if ERRORS class ObjCTest { @objc func foo() -> TestError {} // expected-error {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} expected-note {{Swift structs cannot be represented in Objective-C}} @objc func bar() -> TestError.Code {} // okay } #endif // HEADER: enum Code : Int32, _ErrorCodeProtocol { // HEADER: init?(rawValue: Int32) // HEADER: var rawValue: Int32 { get } // HEADER: typealias _ErrorType = TestError // HEADER: case TENone // HEADER: case TEOne // HEADER: case TETwo // HEADER: } // HEADER: func getErr() -> TestError.Code
apache-2.0
1ab98c930bd30f48bc17f6499efd59ab
38.561404
241
0.701996
3.330871
false
true
false
false
iadmir/Signal-iOS
Signal/src/views/DirectionalPanGestureRecognizer.swift
3
952
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import UIKit.UIGestureRecognizerSubclass @objc enum PanDirection: Int { case vertical case horizontal } @objc class PanDirectionGestureRecognizer: UIPanGestureRecognizer { let direction: PanDirection init(direction: PanDirection, target: AnyObject, action: Selector) { self.direction = direction super.init(target: target, action: action) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesMoved(touches, with: event) if state == .began { let vel = velocity(in: view) switch direction { case .horizontal where fabs(vel.y) > fabs(vel.x): state = .cancelled case .vertical where fabs(vel.x) > fabs(vel.y): state = .cancelled default: break } } } }
gpl-3.0
abe827d0af08ee9234673557cc9447b2
24.052632
78
0.602941
4.643902
false
false
false
false
OneBusAway/onebusaway-iphone
OneBusAway/ui/themes/DrawerApplicationUI.swift
2
9052
// // DrawerApplicationUI.swift // OneBusAway // // Created by Aaron Brethorst on 2/17/18. // Copyright © 2018 OneBusAway. All rights reserved. // import UIKit import FirebaseAnalytics import OBAKit @objc class DrawerApplicationUI: NSObject { var application: OBAApplication let tabBarController = UITabBarController.init() // MARK: - Map Tab var mapTableController: MapTableViewController var mapPulley: PulleyViewController let mapPulleyNav: UINavigationController var mapController: OBAMapViewController let drawerNavigation: UINavigationController // MARK: - Recents Tab let recentsController = OBARecentStopsViewController.init() lazy var recentsNavigation: UINavigationController = { return UINavigationController.init(rootViewController: recentsController) }() // MARK: - Bookmarks Tab let bookmarksController = OBABookmarksViewController.init() lazy var bookmarksNavigation: UINavigationController = { return UINavigationController.init(rootViewController: bookmarksController) }() // MARK: - Info Tab let infoController = OBAInfoViewController.init() lazy var infoNavigation: UINavigationController = { return UINavigationController.init(rootViewController: infoController) }() // MARK: - Init required init(application: OBAApplication) { self.application = application let useStopDrawer = application.userDefaults.bool(forKey: OBAUseStopDrawerDefaultsKey) mapTableController = MapTableViewController.init(application: application) drawerNavigation = UINavigationController(rootViewController: mapTableController) drawerNavigation.setNavigationBarHidden(true, animated: false) mapController = OBAMapViewController(application: application) mapController.standaloneMode = !useStopDrawer mapController.delegate = mapTableController mapPulley = PulleyViewController(contentViewController: mapController, drawerViewController: drawerNavigation) mapPulley.defaultCollapsedHeight = DrawerApplicationUI.calculateCollapsedHeightForCurrentDevice() mapPulley.initialDrawerPosition = .collapsed mapPulley.title = mapTableController.title mapPulley.tabBarItem.image = mapTableController.tabBarItem.image mapPulley.tabBarItem.selectedImage = mapTableController.tabBarItem.selectedImage mapPulleyNav = UINavigationController(rootViewController: mapPulley) super.init() mapPulley.delegate = self tabBarController.viewControllers = [mapPulleyNav, recentsNavigation, bookmarksNavigation, infoNavigation] tabBarController.delegate = self } } // MARK: - Pulley Delegate extension DrawerApplicationUI: PulleyDelegate { func drawerPositionDidChange(drawer: PulleyViewController, bottomSafeArea: CGFloat) { mapTableController.collectionView.isScrollEnabled = drawer.drawerPosition == .open } private static func calculateCollapsedHeightForCurrentDevice() -> CGFloat { let height = UIScreen.main.bounds.height var totalDrawerHeight: CGFloat if #available(iOS 11.0, *) { totalDrawerHeight = 0.0 } else { // PulleyLib seems to have a few layout bugs on iOS 10. // Given the very small number of users on this platform, I am not // super-excited about the prospect of debugging this issue and am // choosing instead to just work around it. totalDrawerHeight = 40.0 } if height >= 812.0 { // X, Xs, iPad, etc. totalDrawerHeight += 200.0 } else if height >= 736.0 { // Plus totalDrawerHeight += 150.0 } else if height >= 667.0 { // 6, 7, 8 totalDrawerHeight += 150.0 } else { // iPhone SE, etc. totalDrawerHeight += 120.0 } return totalDrawerHeight } } // MARK: - OBAApplicationUI extension DrawerApplicationUI: OBAApplicationUI { private static let kOBASelectedTabIndexDefaultsKey = "OBASelectedTabIndexDefaultsKey" public var rootViewController: UIViewController { return tabBarController } func performAction(for shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { var navigationTargetType: OBANavigationTargetType = .undefined var parameters: [AnyHashable: Any]? if shortcutItem.type == kApplicationShortcutRecents { navigationTargetType = .recentStops if let stopIDs = shortcutItem.userInfo?["stopIds"] as? NSArray, let firstObject = stopIDs.firstObject { parameters = [OBAStopIDNavigationTargetParameter: firstObject] } else if let stopID = shortcutItem.userInfo?["stopID"] as? String { parameters = [OBAStopIDNavigationTargetParameter: stopID] } } let target = OBANavigationTarget.init(navigationTargetType, parameters: parameters) self.navigate(toTargetInternal: target) completionHandler(true) } func applicationDidBecomeActive() { var selectedIndex = application.userDefaults.object(forKey: DrawerApplicationUI.kOBASelectedTabIndexDefaultsKey) as? Int ?? 0 // Users sometimes email us confused about what happened to their map. There really isn't any value // in having the user returned to the info tab when they reopen the app, so let's just stop persisting // it as a possible option. Instead, if the user has navigated to the info tab, we'll just default them // back to the map. // See: https://github.com/OneBusAway/onebusaway-iphone/issues/1410 if selectedIndex == 3 { selectedIndex = 0 } tabBarController.selectedIndex = selectedIndex let startingTab = [0: "OBAMapViewController", 1: "OBARecentStopsViewController", 2: "OBABookmarksViewController"][selectedIndex] ?? "Unknown" OBAAnalytics.shared().reportEvent(withCategory: OBAAnalyticsCategoryAppSettings, action: "startup", label: "Startup View: \(startingTab)", value: nil) Analytics.logEvent(OBAAnalyticsStartupScreen, parameters: ["startingTab": startingTab]) } func navigate(toTargetInternal navigationTarget: OBANavigationTarget) { let viewController: (UIViewController & OBANavigationTargetAware) let topController: UIViewController switch navigationTarget.target { case .map, .searchResults: viewController = mapTableController topController = mapPulleyNav case .recentStops: viewController = recentsController topController = recentsNavigation case .bookmarks: viewController = bookmarksController topController = bookmarksNavigation case .contactUs: viewController = infoController topController = infoNavigation case .undefined: // swiftlint:disable no_fallthrough_only fallthrough fallthrough // swiftlint:enable no_fallthrough_only fallthrough default: DDLogError("Unhandled target in #file #line: \(navigationTarget.target)") return } tabBarController.selectedViewController = topController viewController.setNavigationTarget(navigationTarget) if navigationTarget.parameters["stop"] != nil, let stopID = navigationTarget.parameters["stopID"] as? String { let vc = StopViewController.init(stopID: stopID) let nav = mapPulley.navigationController ?? drawerNavigation nav.pushViewController(vc, animated: true) } // update kOBASelectedTabIndexDefaultsKey, otherwise -applicationDidBecomeActive: will switch us away. if let selected = tabBarController.selectedViewController { tabBarController(tabBarController, didSelect: selected) } } } // MARK: - UITabBarControllerDelegate extension DrawerApplicationUI: UITabBarControllerDelegate { func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { application.userDefaults.set(tabBarController.selectedIndex, forKey: DrawerApplicationUI.kOBASelectedTabIndexDefaultsKey) } func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { guard let selectedController = tabBarController.selectedViewController, let controllers = tabBarController.viewControllers else { return true } let oldIndex = controllers.firstIndex(of: selectedController) let newIndex = controllers.firstIndex(of: viewController) if newIndex == 0 && oldIndex == 0 { mapController.recenterMap() } return true } }
apache-2.0
8a36927e0068f0c4066776482148afb6
38.697368
158
0.691857
5.40681
false
false
false
false
shajrawi/swift
validation-test/Evolution/test_protocol_add_requirements.swift
1
3886
// RUN: %target-resilience-test // REQUIRES: executable_test // Use swift-version 4. // UNSUPPORTED: swift_test_mode_optimize_none_with_implicit_dynamic import StdlibUnittest import protocol_add_requirements var ProtocolAddRequirementsTest = TestSuite("ProtocolAddRequirements") struct Halogen : ElementProtocol { var x: Int func increment() -> Halogen { return Halogen(x: x + 1) } } func ==(h1: Halogen, h2: Halogen) -> Bool { return h1.x == h2.x } struct AddMethods : AddMethodsProtocol { func importantOperation() -> Halogen { return Halogen(x: 0) } #if AFTER func unimportantOperation() -> Halogen { return Halogen(x: 10) } #endif } ProtocolAddRequirementsTest.test("AddMethodRequirements") { let result = doSomething(AddMethods()) #if BEFORE let expected = [0, 1, 2].map(Halogen.init) #else let expected = [0, 10, 11].map(Halogen.init) #endif } struct AddConstructors : AddConstructorsProtocol, Equatable { var name: String init(name: String) { self.name = name } } func ==(a1: AddConstructors, a2: AddConstructors) -> Bool { return a1.name == a2.name } ProtocolAddRequirementsTest.test("AddConstructorsProtocol") { // Would be nice if [T?] was Equatable... if getVersion() == 0 { let result = testConstructorProtocol(AddConstructors.self) expectEqual(result.count, 1) expectEqual(result[0], AddConstructors(name: "Puff")) } else { let result = testConstructorProtocol(AddConstructors.self) expectEqual(result.count, 3) expectEqual(result[0], AddConstructors(name: "Meow meow")) expectEqual(result[1], nil) expectEqual(result[2], AddConstructors(name: "Robster the Lobster")) } } class Box<T> { var value: T init(value: T) { self.value = value } } struct AddProperties : AddPropertiesProtocol { var speedBox: Box<Int> = Box<Int>(value: 160) var gearBox: Box<Int> = Box<Int>(value: 8000) var topSpeed: Int { get { return speedBox.value } nonmutating set { speedBox.value = newValue } } var maxRPM: Int { get { return gearBox.value } set { gearBox.value = newValue } } } ProtocolAddRequirementsTest.test("AddPropertyRequirements") { var x = AddProperties() do { let expected = (getVersion() == 0 ? [160, 8000] : [160, 8000, 80, 40, 6000]) expectEqual(getProperties(&x), expected) } setProperties(&x) do { let expected = (getVersion() == 0 ? [320, 15000] : [320, 15000, 160, 80, 13000]) expectEqual(getProperties(&x), expected) } } struct AddSubscript<Key : Hashable, Value> : AddSubscriptProtocol { var dict: [Key : Value] = [:] func get(key key: Key) -> Value { return dict[key]! } mutating func set(key key: Key, value: Value) { dict[key] = value } } ProtocolAddRequirementsTest.test("AddSubscriptRequirements") { var t = AddSubscript<String, Int>() t.set(key: "B", value: 20) doSomething(&t, k1: "A", k2: "B") expectEqual(t.get(key: "A"), 20) } struct AddAssociatedType<T> : AddAssocTypesProtocol { } ProtocolAddRequirementsTest.test("AddAssociatedTypeRequirements") { let addString = AddAssociatedType<String>() let stringResult = doSomethingWithAssocTypes(addString) if getVersion() == 0 { expectEqual("there are no associated types yet", stringResult) } else { expectEqual("Wrapper<AddAssociatedType<String>>", stringResult) } } ProtocolAddRequirementsTest.test("AddAssociatedConformanceRequirements") { let addString = AddAssociatedType<String>() let stringResult = doSomethingWithAssocConformances(addString) if getVersion() == 0 { expectEqual("there are no associated conformances yet", stringResult) } else { expectEqual("I am a wrapper for AddAssociatedType<String>", stringResult) } } runAllTests()
apache-2.0
42181a9ec795337412a1508567bbacee
21.593023
77
0.66984
3.608171
false
true
false
false
february29/Learning
swift/Fch_Contact/Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQBarButtonItem.swift
2
4783
// // IQBarButtonItem.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Foundation open class IQBarButtonItem: UIBarButtonItem { private static var _classInitialize: Void = classInitialize() public override init() { _ = IQBarButtonItem._classInitialize super.init() } public required init?(coder aDecoder: NSCoder) { _ = IQBarButtonItem._classInitialize super.init(coder: aDecoder) } private class func classInitialize() { let appearanceProxy = self.appearance() let states : [UIControlState] = [.normal,.highlighted,.disabled,.selected,.application,.reserved] for state in states { appearanceProxy.setBackgroundImage(nil, for: state, barMetrics: .default) appearanceProxy.setBackgroundImage(nil, for: state, style: .done, barMetrics: .default) appearanceProxy.setBackgroundImage(nil, for: state, style: .plain, barMetrics: .default) appearanceProxy.setBackButtonBackgroundImage(nil, for: state, barMetrics: .default) } appearanceProxy.setTitlePositionAdjustment(UIOffset.zero, for: .default) appearanceProxy.setBackgroundVerticalPositionAdjustment(0, for: .default) appearanceProxy.setBackButtonBackgroundVerticalPositionAdjustment(0, for: .default) } open override var tintColor: UIColor? { didSet { #if swift(>=4) var textAttributes = [NSAttributedStringKey : Any]() if let attributes = titleTextAttributes(for: .normal) { for (key, value) in attributes { textAttributes[NSAttributedStringKey.init(key)] = value } } textAttributes[NSAttributedStringKey.foregroundColor] = tintColor setTitleTextAttributes(textAttributes, for: .normal) #else var textAttributes = [String:Any]() if let attributes = titleTextAttributes(for: .normal) { textAttributes = attributes } textAttributes[NSForegroundColorAttributeName] = tintColor setTitleTextAttributes(textAttributes, for: .normal) #endif } } /** Boolean to know if it's a system item or custom item, we are having a limitation that we cannot override a designated initializer, so we are manually setting this property once in initialization */ @objc var isSystemItem = false // public override init(barButtonSystemItem systemItem: UIBarButtonSystemItem, target: Any?, action: Selector?) { // return super.init(barButtonSystemItem: systemItem, target: target, action: action) // } /** Additional target & action to do get callback action. Note that setting custom target & selector doesn't affect native functionality, this is just an additional target to get a callback. @param target Target object. @param action Target Selector. */ open func setTarget(_ target: AnyObject?, action: Selector?) { invocation = (target, action) } /** Customized Invocation to be called when button is pressed. invocation is internally created using setTarget:action: method. */ open var invocation : (target: AnyObject?, action: Selector?)? deinit { target = nil invocation?.target = nil invocation = nil } }
mit
9236148c742fb988312fcd379ace7e64
36.960317
199
0.652728
5.392334
false
false
false
false
urdnot-ios/ShepardAppearanceConverter
ShepardAppearanceConverter/ShepardAppearanceConverter/Models/Shepard/Shepard.Photo.swift
1
2636
// // Shepard.Photo.swift // ShepardAppearanceConverter // // Created by Emily Ivie on 8/16/15. // Copyright © 2015 Emily Ivie. All rights reserved. // import UIKit extension Shepard { public enum Photo { case DefaultMalePhoto case DefaultFemalePhoto case Custom(fileName: String) var stringValue: String { switch self { case .DefaultMalePhoto: return "BroShep Sample" case .DefaultFemalePhoto: return "FemShep Sample" case .Custom(let fileName): return "\(fileName)" } } func image() -> UIImage? { switch self { case .DefaultMalePhoto: if let photo = UIImage(named: self.stringValue, inBundle: NSBundle.currentAppBundle, compatibleWithTraitCollection: nil) { return photo } case .DefaultFemalePhoto: if let photo = UIImage(named: self.stringValue, inBundle: NSBundle.currentAppBundle, compatibleWithTraitCollection: nil) { return photo } case .Custom(let fileName): if let photo = UIImage(documentsFileName: fileName) { return photo } } return nil } public static func create(image: UIImage, forShepard shepard: Shepard) -> Photo? { let fileName = "MyShepardPhoto\(shepard.uuid)" if image.save(documentsFileName: fileName) { return Photo.Custom(fileName: fileName) } else { return nil } } } } extension Shepard.Photo: Equatable {} public func ==(a: Shepard.Photo, b: Shepard.Photo) -> Bool { switch (a, b) { case (.DefaultMalePhoto, .DefaultMalePhoto): return true case (.DefaultFemalePhoto, .DefaultFemalePhoto): return true case (.Custom(let a), .Custom(let b)) where a == b: return true default: return false } } //MARK: Save/Retrieve Data extension Shepard.Photo { /// special retriever for saved image public init?(data: SerializedData?) { if let fileName = data?.string { if fileName == Shepard.Photo.DefaultMalePhoto.stringValue { self = .DefaultMalePhoto } else if fileName == Shepard.Photo.DefaultFemalePhoto.stringValue { self = .DefaultFemalePhoto } else { self = Shepard.Photo.Custom(fileName: fileName) } return } return nil } }
mit
e1479e80543e8305ddd4d7b80c7a28bd
28.617978
138
0.559013
4.916045
false
false
false
false
Colrying/DouYuZB
DouYuZB/DouYuZB/Classes/Home/Controller/HomeViewController.swift
1
3337
// // HomeViewController.swift // DouYuZB // // Created by 皇坤鹏 on 17/4/11. // Copyright © 2017年 皇坤鹏. All rights reserved. // import UIKit private var kPageTitleViewH : CGFloat = 40 class HomeViewController: UIViewController { // MARK:- 懒加载属性 lazy var pageTitleView : PageTitleView = {[weak self] in let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: kPageTitleViewH) let titles = ["推荐", "游戏", "娱乐", "趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) titleView.delegate = self return titleView }() lazy var pageContentView : PageContentView = {[weak self] in let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kPageTitleViewH, width: kScreenW, height: kScreenH - kStatusBarH - kNavigationBarH - kPageTitleViewH - kTabbarH) var childVcs = [UIViewController]() childVcs.append(RecommendViewController()) childVcs.append(GameViewController()) for _ in 0..<2 { let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) childVcs.append(vc) } let pageContentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self) pageContentView.delegate = self return pageContentView }() // MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() setupUI(); } } // MARK:- 设置UI界面 extension HomeViewController { func setupUI() { // 0. 关闭scrollView自动设置内边距属性 automaticallyAdjustsScrollViewInsets = false // 1. 设置导航栏 setupNavigationBar(); // 2. 设置titleView view.addSubview(pageTitleView) // 3. 设置ContentView view.addSubview(pageContentView) } func setupNavigationBar() { // 1. 设置左侧item navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo"); // 2. 设置右侧item let size = CGSize(width: 40, height: 40); let hestoryItem = UIBarButtonItem(imageName: "image_my_history", hightImageName: "Image_my_history_click", size: size); let searchItem = UIBarButtonItem(imageName: "btn_search", hightImageName: "btn_search_clicked", size: size); let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", hightImageName: "Image_scan_click", size: size); navigationItem.rightBarButtonItems = [hestoryItem, searchItem, qrcodeItem]; } } // MARK:- pageTitleView代理方法 extension HomeViewController : PageTitleViewDelegate { func pageTitleView(titleView: PageTitleView, currentIndex index: Int) { pageContentView.setupPageOffset(index: index) } } // MARK:- pageContentViewDelegate代理方法 extension HomeViewController : PageContentViewDelegate { func contentView(progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setupTitleColorAndScrollLine(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
mit
42e394bfb3e3558f0156216d17f184fb
32.375
187
0.660112
4.891603
false
false
false
false
Piwigo/Piwigo-Mobile
piwigo/Image/ImageUtilities.swift
1
21128
// // ImageUtilities.swift // piwigo // // Created by Eddy Lelièvre-Berna on 27/07/2021. // Copyright © 2021 Piwigo.org. All rights reserved. // import Foundation import ImageIO import MobileCoreServices import piwigoKit import UIKit class ImageUtilities: NSObject { // MARK: - Piwigo Server Methods static func getInfos(forID imageId:Int, inCategoryId categoryId: Int, completion: @escaping (PiwigoImageData) -> Void, failure: @escaping (NSError) -> Void) { // Prepare parameters for retrieving image/video infos let paramsDict: [String : Any] = ["image_id" : imageId] // Launch request let JSONsession = PwgSession.shared JSONsession.postRequest(withMethod: kPiwigoImagesGetInfo, paramDict: paramsDict, jsonObjectClientExpectsToReceive: ImagesGetInfoJSON.self, countOfBytesClientExpectsToReceive: 50000) { jsonData in // Decode the JSON object and store image data in cache. do { // Decode the JSON into codable type ImagesGetInfoJSON. let decoder = JSONDecoder() let imageJSON = try decoder.decode(ImagesGetInfoJSON.self, from: jsonData) // Piwigo error? if imageJSON.errorCode != 0 { let error = PwgSession.shared.localizedError(for: imageJSON.errorCode, errorMessage: imageJSON.errorMessage) failure(error as NSError) return } // Collect data returned by server guard let data = imageJSON.data, let derivatives = imageJSON.derivatives else { // Data cannot be digested failure(JsonError.unexpectedError as NSError) return } // Retrieve image data currently in cache let imageData = CategoriesData.sharedInstance() .getImageForCategory(categoryId, andId: imageId) ?? PiwigoImageData() imageData.imageId = data.imageId ?? imageId // Upper categoies if let catIds = data.categoryIds, !catIds.isEmpty { imageData.categoryIds = [NSNumber]() for catId in catIds { if let id = catId.id { imageData.categoryIds.append(NSNumber(value: id)) } } } if imageData.categoryIds.isEmpty { imageData.categoryIds.append(NSNumber(value: categoryId)) } // Image title and description if let title = data.imageTitle { imageData.imageTitle = NetworkUtilities.utf8mb4String(from: title) } if let description = data.comment { imageData.comment = NetworkUtilities.utf8mb4String(from: description) } // Image visits and rate if let visits = data.visits { imageData.visits = visits } if let score = data.ratingScore, let rate = Float(score) { imageData.ratingScore = rate } // Image file size, name and MD5 checksum imageData.fileSize = data.fileSize ?? NSNotFound imageData.md5checksum = data.md5checksum ?? imageData.md5checksum ?? "" imageData.fileName = NetworkUtilities.utf8mb4String(from: data.fileName ?? imageData.fileName ?? "NoName.jpg") let fileExt = URL(fileURLWithPath: imageData.fileName).pathExtension as NSString if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExt, nil)?.takeRetainedValue() { imageData.isVideo = UTTypeConformsTo(uti, kUTTypeMovie) } // Image dates let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" imageData.datePosted = dateFormatter.date(from: data.datePosted ?? "") ?? imageData.datePosted ?? Date() imageData.dateCreated = dateFormatter.date(from: data.dateCreated ?? "") ?? imageData.dateCreated ?? imageData.datePosted // Author imageData.author = NetworkUtilities.utf8mb4String(from: data.author ?? imageData.author ?? "NSNotFound") // Privacy level if let privacyLevel = Int32(data.privacyLevel ?? String(kPiwigoPrivacyObjcUnknown.rawValue)) { imageData.privacyLevel = kPiwigoPrivacyObjc(rawValue: privacyLevel) } else { imageData.privacyLevel = kPiwigoPrivacyObjcUnknown } // Switch to old cache data format var tagList = [PiwigoTagData]() for tag in data.tags ?? [] { guard let tagId = tag.id else { continue } let newTag = PiwigoTagData() newTag.tagId = Int(tagId) newTag.tagName = NetworkUtilities.utf8mb4String(from: tag.name ?? "") newTag.lastModified = dateFormatter.date(from: tag.lastmodified ?? "") ?? Date() newTag.numberOfImagesUnderTag = tag.counter ?? Int64(NSNotFound) tagList.append(newTag) } imageData.tags = tagList imageData.fullResWidth = data.fullResWidth ?? 1 imageData.fullResHeight = data.fullResHeight ?? 1 imageData.fullResPath = NetworkUtilities.encodedImageURL(data.fullResPath ?? imageData.fullResPath ?? "") imageData.squarePath = NetworkUtilities.encodedImageURL(derivatives.squareImage?.url ?? imageData.squarePath ?? "") imageData.squareWidth = derivatives.squareImage?.width ?? 1 imageData.squareHeight = derivatives.squareImage?.height ?? 1 imageData.thumbPath = NetworkUtilities.encodedImageURL(derivatives.thumbImage?.url ?? imageData.thumbPath ?? "") imageData.thumbWidth = derivatives.thumbImage?.width ?? 1 imageData.thumbHeight = derivatives.thumbImage?.height ?? 1 imageData.mediumPath = NetworkUtilities.encodedImageURL(derivatives.mediumImage?.url ?? imageData.mediumPath ?? "") imageData.mediumWidth = derivatives.mediumImage?.width ?? 1 imageData.mediumHeight = derivatives.mediumImage?.height ?? 1 imageData.xxSmallPath = NetworkUtilities.encodedImageURL(derivatives.xxSmallImage?.url ?? imageData.xxSmallPath ?? "") imageData.xxSmallWidth = derivatives.xxSmallImage?.width ?? 1 imageData.xxSmallHeight = derivatives.xxSmallImage?.height ?? 1 imageData.xSmallPath = NetworkUtilities.encodedImageURL(derivatives.xSmallImage?.url ?? imageData.xSmallPath ?? "") imageData.xSmallWidth = derivatives.xSmallImage?.width ?? 1 imageData.xSmallHeight = derivatives.xSmallImage?.height ?? 1 imageData.smallPath = NetworkUtilities.encodedImageURL(derivatives.smallImage?.url ?? imageData.smallPath ?? "") imageData.smallWidth = derivatives.smallImage?.width ?? 1 imageData.smallHeight = derivatives.smallImage?.height ?? 1 imageData.largePath = NetworkUtilities.encodedImageURL(derivatives.largeImage?.url ?? imageData.largePath ?? "") imageData.largeWidth = derivatives.largeImage?.width ?? 1 imageData.largeHeight = derivatives.largeImage?.height ?? 1 imageData.xLargePath = NetworkUtilities.encodedImageURL(derivatives.xLargeImage?.url ?? imageData.xLargePath ?? "") imageData.xLargeWidth = derivatives.xLargeImage?.width ?? 1 imageData.xLargeHeight = derivatives.xLargeImage?.height ?? 1 imageData.xxLargePath = NetworkUtilities.encodedImageURL(derivatives.xxLargeImage?.url ?? imageData.xxLargePath ?? "") imageData.xxLargeWidth = derivatives.xxLargeImage?.width ?? 1 imageData.xxLargeHeight = derivatives.xxLargeImage?.height ?? 1 // Update cache for catId in imageData.categoryIds { if let _ = CategoriesData.sharedInstance().getCategoryById(catId.intValue) { CategoriesData.sharedInstance().getCategoryById(catId.intValue) .updateImages([imageData]) } } completion(imageData) } catch { // Data cannot be digested let error = error as NSError failure(error) } } failure: { error in /// - Network communication errors /// - Returned JSON data is empty /// - Cannot decode data returned by Piwigo server failure(error) } } static func setInfos(with paramsDict: [String: Any], completion: @escaping () -> Void, failure: @escaping (NSError) -> Void) { let JSONsession = PwgSession.shared JSONsession.postRequest(withMethod: kPiwigoImagesSetInfo, paramDict: paramsDict, jsonObjectClientExpectsToReceive: ImagesSetInfoJSON.self, countOfBytesClientExpectsToReceive: 1000) { jsonData in // Decode the JSON object and check if image data were updated on server. do { // Decode the JSON into codable type ImagesSetInfoJSON. let decoder = JSONDecoder() let uploadJSON = try decoder.decode(ImagesSetInfoJSON.self, from: jsonData) // Piwigo error? if uploadJSON.errorCode != 0 { let error = PwgSession.shared.localizedError(for: uploadJSON.errorCode, errorMessage: uploadJSON.errorMessage) failure(error as NSError) return } // Successful? if uploadJSON.success { // Image properties successfully updated completion() } else { // Could not set image parameters failure(JsonError.unexpectedError as NSError) } } catch { // Data cannot be digested let error = error as NSError failure(error) } } failure: { error in /// - Network communication errors /// - Returned JSON data is empty /// - Cannot decode data returned by Piwigo server failure(error) } } static func delete(_ images:[PiwigoImageData], completion: @escaping () -> Void, failure: @escaping (NSError) -> Void) { // Create string containing pipe separated list of image ids let listOfImageIds = images.map({ "\($0.imageId)" }).joined(separator: "|") // Prepare parameters for retrieving image/video infos let paramsDict: [String : Any] = ["image_id" : listOfImageIds, "pwg_token" : NetworkVars.pwgToken] let JSONsession = PwgSession.shared JSONsession.postRequest(withMethod: kPiwigoImagesDelete, paramDict: paramsDict, jsonObjectClientExpectsToReceive: ImagesDeleteJSON.self, countOfBytesClientExpectsToReceive: 1000) { jsonData in // Decode the JSON and delete image from cache if successful. do { // Decode the JSON into codable type ImagesDeleteJSON. let decoder = JSONDecoder() let uploadJSON = try decoder.decode(ImagesDeleteJSON.self, from: jsonData) // Piwigo error? if uploadJSON.errorCode != 0 { let error = PwgSession.shared.localizedError(for: uploadJSON.errorCode, errorMessage: uploadJSON.errorMessage) failure(error as NSError) return } // Successful? if uploadJSON.success { // Images deleted successfully /// We may check here that the number returned matches the number of images to delete /// and return an error to the user. DispatchQueue.global(qos: .userInteractive).async { // Remove image from cache, update UI and Upload database for image in images { // Remove image from cache, update UI and Upload database CategoriesData.sharedInstance().deleteImage(image) } } completion() } else { // Could not delete images failure(JsonError.unexpectedError as NSError) } } catch { // Data cannot be digested let error = error as NSError failure(error) } } failure: { error in /// - Network communication errors /// - Returned JSON data is empty /// - Cannot decode data returned by Piwigo server failure(error) } } static func addToFavorites(_ imageData: PiwigoImageData, completion: @escaping () -> Void, failure: @escaping (NSError) -> Void) { // Prepare parameters for retrieving image/video infos let paramsDict: [String : Any] = ["image_id" : imageData.imageId] let JSONsession = PwgSession.shared JSONsession.postRequest(withMethod: kPiwigoUsersFavoritesAdd, paramDict: paramsDict, jsonObjectClientExpectsToReceive: FavoritesAddRemoveJSON.self, countOfBytesClientExpectsToReceive: 1000) { jsonData in // Decode the JSON object and add image to favorites. do { // Decode the JSON into codable type FavoritesAddRemoveJSON. let decoder = JSONDecoder() let uploadJSON = try decoder.decode(FavoritesAddRemoveJSON.self, from: jsonData) // Piwigo error? if uploadJSON.errorCode != 0 { let error = PwgSession.shared.localizedError(for: uploadJSON.errorCode, errorMessage: uploadJSON.errorMessage) failure(error as NSError) return } // Successful? if uploadJSON.success { // Images successfully added to user's favorites DispatchQueue.global(qos: .userInteractive).async { // Add image to cache CategoriesData.sharedInstance() .addImage(imageData, toCategory: "\(kPiwigoFavoritesCategoryId)") } completion() } else { // Could not delete images failure(JsonError.unexpectedError as NSError) } } catch { // Data cannot be digested let error = error as NSError failure(error) } } failure: { error in /// - Network communication errors /// - Returned JSON data is empty /// - Cannot decode data returned by Piwigo server failure(error) } } static func removeFromFavorites(_ imageData: PiwigoImageData, completion: @escaping () -> Void, failure: @escaping (NSError) -> Void) { // Prepare parameters for retrieving image/video infos let paramsDict: [String : Any] = ["image_id" : imageData.imageId] let JSONsession = PwgSession.shared JSONsession.postRequest(withMethod: kPiwigoUsersFavoritesRemove, paramDict: paramsDict, jsonObjectClientExpectsToReceive: FavoritesAddRemoveJSON.self, countOfBytesClientExpectsToReceive: 1000) { jsonData in // Decode the JSON object and remove image from faborites. do { // Decode the JSON into codable type FavoritesAddRemoveJSON. let decoder = JSONDecoder() let uploadJSON = try decoder.decode(FavoritesAddRemoveJSON.self, from: jsonData) // Piwigo error? if uploadJSON.errorCode != 0 { let error = PwgSession.shared.localizedError(for: uploadJSON.errorCode, errorMessage: uploadJSON.errorMessage) failure(error as NSError) return } // Successful? if uploadJSON.success { // Images successfully added to user's favorites DispatchQueue.global(qos: .userInteractive).async { // Remove image from cache CategoriesData.sharedInstance() .removeImage(imageData, fromCategory: String(kPiwigoFavoritesCategoryId)) } completion() } else { // Could not delete images failure(JsonError.unexpectedError as NSError) } } catch { // Data cannot be digested let error = error as NSError failure(error) } } failure: { error in /// - Network communication errors /// - Returned JSON data is empty /// - Cannot decode data returned by Piwigo server failure(error) } } // MARK: - Image Downsampling // Downsampling large images for display at smaller size (WWDC 2018 - Session 219) static func downsample(imageAt imageURL: URL, to pointSize: CGSize, scale: CGFloat) -> UIImage { let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary guard pointSize.equalTo(CGSize.zero) == false, let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions) else { if let data = try? Data( contentsOf:imageURL) { return UIImage(data: data) ?? UIImage(named: "placeholder")! } else { return UIImage(named: "placeholder")! } } return downsampledImage(from: imageSource, to: pointSize, scale: scale) } static func downsample(image: UIImage, to pointSize: CGSize, scale: CGFloat) -> UIImage { let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary guard pointSize.equalTo(CGSize.zero) == false, let imageData = image.jpegData(compressionQuality: 1.0), let imageSource = CGImageSourceCreateWithData(imageData as CFData, imageSourceOptions) else { return image } return downsampledImage(from: imageSource, to: pointSize, scale: scale) } static func downsampledImage(from imageSource:CGImageSource, to pointSize: CGSize, scale: CGFloat) -> UIImage { // The default display scale for a trait collection is 0.0 (indicating unspecified). // We therefore adopt a scale of 1.0 when the display scale is unspecified. let maxDimensionInPixels = max(pointSize.width, pointSize.height) * max(scale, 1.0) let downsampleOptions = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceShouldCacheImmediately: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels] as CFDictionary let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions)! return UIImage(cgImage: downsampledImage) } }
mit
4f88d147fdb0d5bfab181c98e0819ea1
49.420048
137
0.55098
5.756403
false
false
false
false
MrAdamBoyd/SwiftBus
Pod/Classes/TransitStation.swift
2
4014
// // TransitStation.swift // Pods // // Created by Adam on 2015-09-21. // // import Foundation private let routesAtStationEncoderString = "routesAtStationEncoder" private let stopTitleEncoderString = "stopTitleEncoder" private let stopTagEncoderString = "stopTagEncoder" private let agencyTagEncoderString = "agencyTagEncoder" private let latEncoderString = "latEncoder" private let lonEncoderString = "lonEncoder" private let predictionsEncoderString = "predictionsEncoder" private let messagesEncoderString = "messagesEncoder" //A tranit station is a transit stop tied to multiple routes open class TransitStation: NSObject, NSCoding { open var routesAtStation: [TransitRoute] = [] open var stopTitle: String = "" open var stopTag: String = "" open var agencyTag: String = "" open var lat: Double = 0 open var lon: Double = 0 open var predictions: [String: [String: [TransitPrediction]]] = [:] //[routeTag : [direction : prediction]] open var messages: [String] = [] /** Returns a list of all the predictions from the different directions in order - returns: In order list of all predictions from all different directions */ open var allPredictions: [TransitPrediction] { var listOfPredictions: [TransitPrediction] = [] for line in predictions.values { //Going through each line for predictionDirection in line.values { //Going through each direction listOfPredictions += predictionDirection } } //Sorting the list listOfPredictions.sort { return $0.predictionInSeconds < $1.predictionInSeconds } return listOfPredictions } //Basic init public override init() { super.init() } /** Initializes the object with everything needed to get the route config - parameter stopTitle: title of the stop - parameter stopTag: 4 digit tag of the stop - parameter routesAtStation: array of routes that go to the station - returns: None */ public init(stopTitle:String, stopTag:String, routesAtStation:[TransitRoute]) { self.stopTitle = stopTitle self.stopTag = stopTag self.routesAtStation = routesAtStation } @available(*, deprecated: 1.4, obsoleted: 2.0, message: "Use variable `allPredictions` instead") open func combinedPredictions() -> [TransitPrediction] { return self.allPredictions } //MARK: NSCoding public required init?(coder aDecoder: NSCoder) { self.routesAtStation = aDecoder.decodeObject(forKey: routesAtStationEncoderString) as? [TransitRoute] ?? [] self.stopTitle = aDecoder.decodeObject(forKey: stopTitleEncoderString) as? String ?? "" self.stopTag = aDecoder.decodeObject(forKey: stopTagEncoderString) as? String ?? "" self.agencyTag = aDecoder.decodeObject(forKey: agencyTagEncoderString) as? String ?? "" self.lat = aDecoder.decodeDouble(forKey: latEncoderString) self.lon = aDecoder.decodeDouble(forKey: lonEncoderString) self.predictions = aDecoder.decodeObject(forKey: predictionsEncoderString) as? [String: [String: [TransitPrediction]]] ?? [:] self.messages = aDecoder.decodeObject(forKey: messagesEncoderString) as? [String] ?? [] } open func encode(with aCoder: NSCoder) { aCoder.encode(self.routesAtStation, forKey: routesAtStationEncoderString) aCoder.encode(self.stopTitle, forKey: stopTitleEncoderString) aCoder.encode(self.stopTag, forKey: stopTagEncoderString) aCoder.encode(self.agencyTag, forKey: agencyTagEncoderString) aCoder.encode(self.lat, forKey: latEncoderString) aCoder.encode(self.lon, forKey: lonEncoderString) aCoder.encode(self.predictions, forKey: predictionsEncoderString) aCoder.encode(self.messages, forKey: messagesEncoderString) } }
mit
171982dcd72af0d02d505a4b171f08ec
38.742574
133
0.681863
4.510112
false
false
false
false
practicalswift/swift
validation-test/Evolution/Inputs/struct_change_size.swift
50
760
public struct ChangeSize { public init(version: Int32) { self._version = T(version) } public var version: Int32 { get { return Int32(_version) } set { _version = T(newValue) } } #if BEFORE typealias T = Int32 #else typealias T = Int64 #endif private var _version: T } @_fixed_layout public struct ChangeFieldOffsetsOfFixedLayout { public init(major: Int32, minor: Int32, patch: Int32) { self.major = ChangeSize(version: major) self.minor = ChangeSize(version: minor) self.patch = ChangeSize(version: patch) } public var major: ChangeSize public var minor: ChangeSize public var patch: ChangeSize public func getVersion() -> String { return "\(major.version).\(minor.version).\(patch.version)" } }
apache-2.0
921af98111445a517bfa79b91c96f757
20.714286
63
0.678947
3.601896
false
false
false
false
iOSWizards/AwesomeMedia
AwesomeMedia/Classes/Controllers/AwesomeMediaAudioViewController.swift
1
13003
// // AwesomeMediaAudioViewController.swift // AwesomeMedia // // Created by Evandro Harrison Hoffmann on 4/23/18. // import UIKit import AwesomeDownloading import AwesomeTracking public class AwesomeMediaAudioViewController: UIViewController { @IBOutlet weak var contentStackView: UIStackView! @IBOutlet weak var coverImageView: UIImageView! @IBOutlet weak var controlView: AwesomeMediaAudioControlView! @IBOutlet weak var minimizeButton: UIButton! @IBOutlet weak var topControlsStackView: UIStackView! @IBOutlet weak var airplayButton: UIButton! @IBOutlet weak var downloadButton: UIButton! @IBOutlet weak var downloadStateStackView: UIStackView! @IBOutlet weak var downloadStateLabel: UILabel! @IBOutlet weak var downloadStateImageView: UIImageView! @IBOutlet weak var downloadProgressView: UIProgressView! // Public Variaables public var mediaParams = AwesomeMediaParams() // Private Variables fileprivate var downloadState: AwesomeMediaDownloadState = .none public override func viewDidLoad() { super.viewDidLoad() // configure controller configure() } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Add observers addObservers() } public override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Remove observers removeObservers() } public override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { // track event track(event: .changedOrientation, source: .audioFullscreen, value: UIApplication.shared.statusBarOrientation) } // Configure public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateAppearance(isPortrait: UIApplication.shared.statusBarOrientation.isPortrait) } fileprivate func configure() { configureControls() refreshDownloadState() loadCoverImage() play() // Refresh controls refreshControls() // check for loading state coverImageView.stopLoadingAnimation() if AwesomeMediaManager.shared.mediaIsLoading(withParams: mediaParams) { coverImageView.startLoadingAnimation() } } public override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } fileprivate func configureControls() { controlView.configure(withParams: mediaParams, trackingSource: .audioFullscreen) // play/pause controlView.playCallback = { [weak self] (isPlaying) in if isPlaying { self?.play() } else { sharedAVPlayer.pause() } } // seek slider controlView.timeSliderChangedCallback = { (time) in sharedAVPlayer.seek(toTime: time) } controlView.timeSliderFinishedDraggingCallback = { (play) in if play { sharedAVPlayer.play() } } // Rewind controlView.rewindCallback = { sharedAVPlayer.seekBackward() } // Speed controlView.speedToggleCallback = { sharedAVPlayer.toggleSpeed() } } public func updateAppearance(isPortrait: Bool) { contentStackView.axis = isPortrait ? .vertical : .horizontal contentStackView.alignment = (isPortrait || isPhone) ? .fill : .center contentStackView.spacing = (isPortrait || isPhone) ? 0 : 60 } // MARK: - Events @IBAction func minimizeButtonPressed(_ sender: Any) { self.dismiss(animated: true, completion: nil) // track event track(event: .toggleFullscreen, source: .audioFullscreen) } @IBAction func airplayButtonPressed(_ sender: Any) { view.showAirplayMenu() // track event track(event: .tappedAirplay, source: .audioFullscreen) } @IBAction func downloadButtonPressed(_ sender: Any) { switch downloadState { case .downloaded: deleteMedia() case .downloading: break default: downloadMedia() } self.trackDownloadedAsset(params: mediaParams) // track event //track(event: .tappedDownload, source: .audioFullscreen) } fileprivate func downloadMedia() { downloadState = .downloading updateDownloadState() downloadProgressView.progress = 0 AwesomeDownloading.downloadMedia(withUrl: mediaParams.url?.url, completion: { (success) in self.refreshDownloadState() if success, sharedAVPlayer.isPlaying { // play offline media sharedAVPlayer.stop() self.play() } }, progressUpdated: {(progress) in self.downloadProgressView.progress = progress }) } fileprivate func deleteMedia() { sharedAVPlayer.stop() self.confirmMediaDeletion(withUrl: mediaParams.url?.url, fromView: downloadButton, withTitle: "availableoffline_delete_title".localized, withMessage: "availableoffline_delete_message".localized, withConfirmButtonTitle: "availableoffline_delete_button_confirm".localized, withCancelButtonTitle: "availableoffline_delete_button_cancel".localized, completion: {(success) in if success { // play online media sharedAVPlayer.stop() self.play() // update download button self.refreshDownloadState() } // track event track(event: .deletedDownload, source: .audioFullscreen) }) } fileprivate func play() { AwesomeMediaManager.shared.playMedia( withParams: self.mediaParams, inPlayerLayer: AwesomeMediaPlayerLayer.shared, viewController: self) } fileprivate func refreshControls() { // update slider timeUpdated() // update play button state controlView.playButton.isSelected = sharedAVPlayer.isPlaying(withParams: mediaParams) } } // MARK: - Media Information extension AwesomeMediaAudioViewController { public func loadCoverImage() { guard let coverImageUrl = mediaParams.coverUrl else { return } // set the cover image coverImageView.setImage(coverImageUrl) } // update download state public func refreshDownloadState() { downloadState = AwesomeDownloading.mediaDownloadState(withUrl: mediaParams.url?.url) updateDownloadState() } public func updateDownloadState() { switch downloadState { case .downloading: downloadButton.isHidden = true downloadStateStackView.isHidden = false if let size = mediaParams.size { downloadStateLabel.text = "\(size.uppercased()) - \("downloading".localized)" } else { downloadStateLabel.text = "downloading".localized } downloadStateImageView.image = UIImage(named: "btnDownload", in: Bundle(for: AwesomeMedia.self), compatibleWith: nil) case .downloaded: downloadButton.isHidden = true downloadStateStackView.isHidden = false downloadStateLabel.text = "availableoffline".localized downloadStateImageView.image = UIImage(named: "icoOfflineAudio", in: Bundle(for: AwesomeMedia.self), compatibleWith: nil) default: downloadButton.isHidden = false downloadStateStackView.isHidden = true } } } // MARK: - Observers extension AwesomeMediaAudioViewController: AwesomeMediaEventObserver { public func addObservers() { AwesomeMediaNotificationCenter.addObservers([.basic, .timeUpdated, .speedRateChanged, .timedOut, .stopped], to: self) } public func removeObservers() { AwesomeMediaNotificationCenter.removeObservers(from: self) } public func startedPlaying() { guard sharedAVPlayer.isPlaying(withParams: mediaParams) else { return } controlView.playButton.isSelected = true // update Control Center AwesomeMediaControlCenter.updateControlCenter(withParams: mediaParams) // remove media alert if present removeAlertIfPresent() } public func pausedPlaying() { controlView.playButton.isSelected = sharedAVPlayer.isPlaying(withParams: mediaParams) } public func stoppedPlaying() { pausedPlaying() stoppedBuffering() finishedPlaying() // remove media alert if present removeAlertIfPresent() } public func startedBuffering() { guard sharedAVPlayer.isCurrentItem(withParams: mediaParams) else { stoppedBuffering() return } coverImageView.startLoadingAnimation() controlView.lock(true, animated: true) } public func stoppedBuffering() { coverImageView.stopLoadingAnimation() controlView.lock(false, animated: true) // remove media alert if present removeAlertIfPresent() } public func finishedPlaying() { controlView.playButton.isSelected = false controlView.lock(false, animated: true) } public func timedOut() { showMediaTimedOutAlert() } public func speedRateChanged() { controlView.speedLabel?.text = AwesomeMediaSpeed.speedLabelForCurrentSpeed } public func timeUpdated() { guard let item = sharedAVPlayer.currentItem(withParams: mediaParams) else { return } //AwesomeMedia.log("Current time updated: \(item.currentTime().seconds) of \(CMTimeGetSeconds(item.duration))") // update time controls controlView?.update(withItem: item) } } // MARK: - ViewController Initialization extension AwesomeMediaAudioViewController { public static var newInstance: AwesomeMediaAudioViewController { let storyboard = UIStoryboard(name: "AwesomeMedia", bundle: AwesomeMedia.bundle) return storyboard.instantiateViewController(withIdentifier: "AwesomeMediaAudioViewController") as! AwesomeMediaAudioViewController } } // MARK: - Tracking extension AwesomeMediaAudioViewController { func trackDownloadedAsset(params: AwesomeMediaParams) { let properties: [String: String] = [ "quest id": params.params["quest id"] as? String ?? "", "quest name": params.params["quest name"] as? String ?? "", "quest type": params.params["quest type"] as? String ?? "", "course started at": params.params["course started at"] as? String ?? "", "release id": params.params["release id"] as? String ?? "", "release type": params.params["release type"] as? String ?? "", "page position":params.params["page position"] as? String ?? "", "page type": params.params["page type"] as? String ?? "", "group name": params.params["group name"] as? String ?? "", "asset id": params.params["asset id"] as? String ?? "", "asset type": params.params["asset type"] as? String ?? "" ] AwesomeTracking.trackV2("download asset", with: properties) } } extension UIViewController { public func presentAudioFullscreen(withMediaParams mediaParams: AwesomeMediaParams) { AwesomeMediaPlayerType.type = .audio let viewController = AwesomeMediaAudioViewController.newInstance viewController.mediaParams = mediaParams interactor = AwesomeMediaInteractor() viewController.modalPresentationStyle = .fullScreen viewController.transitioningDelegate = self viewController.interactor = interactor self.present(viewController, animated: true, completion: nil) } }
mit
c9d11669617c28aeb89532020957ed2d
32.086514
138
0.601092
5.859847
false
false
false
false