repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ngquerol/Diurna
refs/heads/master
App/Sources/Views/StoriesTableView.swift
mit
1
// // StoriesTableView.swift // Diurna // // Created by Nicolas Gaulard-Querol on 22/07/2017. // Copyright © 2017 Nicolas Gaulard-Querol. All rights reserved. // import AppKit import HackerNewsAPI class StoriesTableView: NSTableView { // MARK: Methods override func drawGrid(inClipRect clipRect: NSRect) {} override func menu(for event: NSEvent) -> NSMenu? { let point = convert(event.locationInWindow, from: nil) let rowAtPoint = row(at: point) guard rowAtPoint != -1 else { return nil } let menu = NSMenu(title: "Story Context Menu") let item = menu .addItem(withTitle: "Open in browser", action: .openStoryInBrowser, keyEquivalent: "") guard let cellView = view( atColumn: 0, row: rowAtPoint, makeIfNecessary: false ) as? StoryCellView, let story = cellView.objectValue as? Story else { return nil } item.representedObject = story return menu } @objc func openStoryInBrowser(_ sender: NSMenuItem) { guard let story = sender.representedObject as? Story else { return } let storyURL = HNWebpage.item(story.id).path do { try NSWorkspace.shared.open(storyURL, options: .withoutActivation, configuration: [:]) } catch let error as NSError { NSAlert(error: error).runModal() } } } // MARK: - Selectors extension Selector { fileprivate static let openStoryInBrowser = #selector(StoriesTableView.openStoryInBrowser(_:)) }
df9d987394d82b7004e02c039c464472
25.672131
98
0.611555
false
false
false
false
dobleuber/my-swift-exercises
refs/heads/master
Challenge2/Challenge2/DetailViewController.swift
mit
1
// // DetailViewController.swift // Challenge2 // // Created by Wbert Castro on 13/06/17. // Copyright © 2017 Wbert Castro. All rights reserved. // import UIKit import Social class DetailViewController: UIViewController { @IBOutlet weak var countryImageView: UIImageView! var selectedCountry: String? override func viewDidLoad() { super.viewDidLoad() title = selectedCountry if let flagToLoad = selectedCountry { countryImageView.image = UIImage(named: flagToLoad) } navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareFlag)) } func shareFlag() -> Void { if let vc = SLComposeViewController(forServiceType: SLServiceTypeFacebook) { vc.setInitialText("Checkout this amazing flag!") vc.add(countryImageView.image) present(vc, animated: true) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
b906c0d4dfde970b42e8008bbc8e6556
27.769231
133
0.663102
false
false
false
false
MaximKotliar/Bindy
refs/heads/master
Tests/TransformationsTests.swift
mit
1
// // TransformationsTests.swift // // // Created by Alexander Karpov on 21.01.2021. // import XCTest @testable import Bindy final class TransformationsTests: XCTestCase { func testMap() { let observable = Observable<String>("test") let mapped = observable.map { $0.count } let asyncExpectation = expectation(description: "Expect to call") mapped.bind(self) { old, new in guard old == 4 else { return } guard new == 0 else { return } asyncExpectation.fulfill() } observable.value = "" waitForExpectations(timeout: 1, handler: nil) } func testArrayMap() { let observable = Observable(["one", "two", "three"]) let mapped: Observable<[Int]> = observable.map { $0.count } let asyncExpectation = expectation(description: "Expect to call") mapped.bind(self) { old, new in guard old == [3, 3, 5] else { return } guard new == [4] else { return } asyncExpectation.fulfill() } observable.value = ["four"] waitForExpectations(timeout: 1, handler: nil) } func testCompactMap() { let observable = Observable(["test", "test", nil]) let compactMapped = observable.compactMap { $0 } let asyncExpectation = expectation(description: "Expect not call") asyncExpectation.isInverted = true compactMapped.bind(self) { value in guard value == ["test", "test", "test"] else { return } asyncExpectation.fulfill() } observable.value.append("test") waitForExpectations(timeout: 1, handler: nil) } func testReduce() { let observable = Observable(["test", "test"]) let reduced = observable.reduce(0) { $0 + $1.count } let asyncExpectation = expectation(description: "Expect to call") reduced.bind(self) { value in guard value == 12 else { return } asyncExpectation.fulfill() } observable.value.append("test") waitForExpectations(timeout: 1, handler: nil) } func testFilter() { let observable = Observable(["test", "test", "notTest"]) let filtered = observable.filter { $0 == "test" } let asyncExpectation = expectation(description: "Expect to call") filtered.bind(self) { value in guard value.count == 3 else { return } asyncExpectation.fulfill() } observable.value.append("test") waitForExpectations(timeout: 1, handler: nil) } static var allTests = [ ("testMap", testMap), ("testArrayMap", testArrayMap), ("testCompactMap", testCompactMap), ("testReduce", testReduce), ("testFilter", testFilter) ] }
762905923e19d68cd1930399bf8bb3c1
32.795181
74
0.587522
false
true
false
false
attaswift/Attabench
refs/heads/master
OptimizingCollections.attabench/Sources/BTree.swift
mit
2
// // UnoptimizedBTree.swift // Benchmark // // Created by Károly Lőrentey on 2017-02-09. // Copyright © 2017 Károly Lőrentey. // struct BTree<Element: Comparable> { fileprivate var root: Node<Element> init(order: Int) { self.root = Node(order: order) } } fileprivate final class Node<Element: Comparable> { let order: Int var mutationCount: Int = 0 var elements: [Element] = [] var children: [Node] = [] init(order: Int) { self.order = order } } import Darwin let cacheSize: Int = { var result: Int = 0 var size = MemoryLayout<Int>.size if sysctlbyname("hw.l1dcachesize", &result, &size, nil, 0) == -1 { return 32768 } return result }() extension BTree { init() { let order = cacheSize / (4 * MemoryLayout<Element>.stride) self.init(order: Swift.max(16, order)) } } extension BTree { public func forEach(_ body: (Element) throws -> Void) rethrows { try root.forEach(body) } } extension Node { func forEach(_ body: (Element) throws -> Void) rethrows { if children.count == 0 { try elements.forEach(body) } else { for i in 0 ..< elements.count { try children[i].forEach(body) try body(elements[i]) } try children[elements.count].forEach(body) } } } extension Node { internal func slot(of element: Element) -> (match: Bool, index: Int) { var start = 0 var end = elements.count while start < end { let mid = start + (end - start) / 2 if elements[mid] < element { start = mid + 1 } else { end = mid } } let match = start < elements.count && elements[start] == element return (match, start) } } extension BTree { public func contains(_ element: Element) -> Bool { return root.contains(element) } } extension Node { func contains(_ element: Element) -> Bool { let slot = self.slot(of: element) if slot.match { return true } guard !children.isEmpty else { return false } return children[slot.index].contains(element) } } extension BTree { fileprivate mutating func makeRootUnique() -> Node<Element> { if isKnownUniquelyReferenced(&root) { return root } root = root.clone() return root } } extension Node { func clone() -> Node { let clone = Node(order: order) clone.elements = self.elements clone.children = self.children return clone } } extension Node { func makeChildUnique(_ slot: Int) -> Node { guard !isKnownUniquelyReferenced(&children[slot]) else { return children[slot] } let clone = children[slot].clone() children[slot] = clone return clone } } extension Node { var isLeaf: Bool { return children.isEmpty } var isTooLarge: Bool { return elements.count >= order } } private struct Splinter<Element: Comparable> { let separator: Element let node: Node<Element> } extension Node { func split() -> Splinter<Element> { let count = elements.count let middle = count / 2 let separator = elements[middle] let node = Node(order: order) node.elements.append(contentsOf: elements[middle + 1 ..< count]) elements.removeSubrange(middle ..< count) if !isLeaf { node.children.append(contentsOf: children[middle + 1 ..< count + 1]) children.removeSubrange(middle + 1 ..< count + 1) } return Splinter(separator: separator, node: node) } } extension Node { func insert(_ element: Element) -> (old: Element?, splinter: Splinter<Element>?) { let slot = self.slot(of: element) if slot.match { // The element is already in the tree. return (self.elements[slot.index], nil) } mutationCount += 1 if self.isLeaf { elements.insert(element, at: slot.index) return (nil, self.isTooLarge ? self.split() : nil) } let (old, splinter) = makeChildUnique(slot.index).insert(element) guard let s = splinter else { return (old, nil) } elements.insert(s.separator, at: slot.index) children.insert(s.node, at: slot.index + 1) return (nil, self.isTooLarge ? self.split() : nil) } } extension BTree { @discardableResult public mutating func insert(_ element: Element) -> (inserted: Bool, memberAfterInsert: Element) { let root = makeRootUnique() let (old, splinter) = root.insert(element) if let splinter = splinter { let r = Node<Element>(order: root.order) r.elements = [splinter.separator] r.children = [root, splinter.node] self.root = r } return (old == nil, old ?? element) } } private struct PathElement<Element: Comparable> { unowned(unsafe) let node: Node<Element> var slot: Int init(_ node: Node<Element>, _ slot: Int) { self.node = node self.slot = slot } } extension PathElement { var isLeaf: Bool { return node.isLeaf } var isAtEnd: Bool { return slot == node.elements.count } var value: Element? { guard slot < node.elements.count else { return nil } return node.elements[slot] } var child: Node<Element> { return node.children[slot] } } extension PathElement: Equatable { static func ==(left: PathElement, right: PathElement) -> Bool { return left.node === right.node && left.slot == right.slot } } public struct BTreeIndex<Element: Comparable> { fileprivate weak var root: Node<Element>? fileprivate let mutationCount: Int fileprivate var path: [PathElement<Element>] fileprivate var current: PathElement<Element> init(startOf tree: BTree<Element>) { self.root = tree.root self.mutationCount = tree.root.mutationCount self.path = [] self.current = PathElement(tree.root, 0) while !current.isLeaf { push(0) } } init(endOf tree: BTree<Element>) { self.root = tree.root self.mutationCount = tree.root.mutationCount self.path = [] self.current = PathElement(tree.root, tree.root.elements.count) } } extension BTreeIndex { fileprivate func validate(for root: Node<Element>) { precondition(self.root === root) precondition(self.mutationCount == root.mutationCount) } fileprivate static func validate(_ left: BTreeIndex, _ right: BTreeIndex) { precondition(left.root === right.root) precondition(left.mutationCount == right.mutationCount) precondition(left.root != nil) precondition(left.mutationCount == left.root!.mutationCount) } } extension BTreeIndex { fileprivate mutating func push(_ slot: Int) { path.append(current) current = PathElement(current.node.children[current.slot], slot) } fileprivate mutating func pop() { current = self.path.removeLast() } } extension BTreeIndex { fileprivate mutating func formSuccessor() { precondition(!current.isAtEnd, "Cannot advance beyond endIndex") current.slot += 1 if current.isLeaf { while current.isAtEnd, current.node !== root { pop() } } else { while !current.isLeaf { push(0) } } } } extension BTreeIndex { fileprivate mutating func formPredecessor() { if current.isLeaf { while current.slot == 0, current.node !== root { pop() } precondition(current.slot > 0, "Cannot go below startIndex") current.slot -= 1 } else { while !current.isLeaf { let c = current.child push(c.isLeaf ? c.elements.count - 1 : c.elements.count) } } } } extension BTreeIndex: Comparable { public static func ==(left: BTreeIndex, right: BTreeIndex) -> Bool { BTreeIndex.validate(left, right) return left.current == right.current } public static func <(left: BTreeIndex, right: BTreeIndex) -> Bool { BTreeIndex.validate(left, right) switch (left.current.value, right.current.value) { case let (.some(a), .some(b)): return a < b case (.none, _): return false default: return true } } } extension BTree: SortedSet { public typealias Index = BTreeIndex<Element> public var startIndex: Index { return Index(startOf: self) } public var endIndex: Index { return Index(endOf: self) } public subscript(index: Index) -> Element { get { index.validate(for: root) return index.current.value! } } public func formIndex(after i: inout Index) { i.validate(for: root) i.formSuccessor() } public func formIndex(before i: inout Index) { i.validate(for: root) i.formPredecessor() } public func index(after i: Index) -> Index { i.validate(for: root) var i = i i.formSuccessor() return i } public func index(before i: Index) -> Index { i.validate(for: root) var i = i i.formPredecessor() return i } } extension BTree { public var count: Int { return root.count } } extension Node { var count: Int { return children.reduce(elements.count) { $0 + $1.count } } } public struct BTreeIterator<Element: Comparable>: IteratorProtocol { let tree: BTree<Element> var index: BTreeIndex<Element> init(_ tree: BTree<Element>) { self.tree = tree self.index = tree.startIndex } public mutating func next() -> Element? { guard let result = index.current.value else { return nil } index.formSuccessor() return result } } extension BTree { public func makeIterator() -> BTreeIterator<Element> { return BTreeIterator(self) } }
69f61099bfa4a7d780e2fb44f8b748fc
25.191327
101
0.585663
false
false
false
false
SnapFresh/SnapFresh
refs/heads/develop
iOS/SnapFresh/Constants.swift
apache-2.0
3
/* * Copyright 2015 Marco Abundo, Ysiad Ferreiras, Aaron Bannert, Jeremy Canfield and Michelle Koeth * * 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 Constants @abstract SnapFresh constants */ struct Constants { // SnapFresh API base URL static let kSnapFreshBaseURL = "http://snapfresh.org" // SnapFresh API endpoint static let kSnapFreshEndpoint = "/retailers/nearaddy.json/" // USDA farmers market API base URL static let kUSDABaseURL = "http://search.ams.usda.gov" // USDA farmers market location search API endpoint static let kUSDAFarmersMarketSearchEndpoint = "/farmersmarkets/mobile/mobile.svc/locSearch?" // USDA farmers market detail API endpoint static let kUSDAFarmersMarketDetailEndpoint = "/farmersmarkets/v1/data.svc/mktDetail?" // SnapFresh timeout interval static let kSnapFreshTimeout: NSTimeInterval = 10.0 // Animation duration static let kAnimationDuration: NSTimeInterval = 0.5 // Edge insets static let kEdgeInsetPhone: CGFloat = 40.0 static let kEdgeInsetPad: CGFloat = 100.0 // Map image name static let kMapImageName = "103-map" // List image name static let kListImageName = "259-list" // Notifications posted when responses are returned static let kSNAPRetailersDidLoadNotification = "SNAPRetailersDidLoadNotification" static let kSNAPRetailersDidNotLoadNotification = "SNAPRetailersDidNotLoadNotification" static let kFarmersMarketsDidLoadNotification = "FarmersMarketsDidLoadNotification" static let kFarmersMarketsDidNotLoadNotification = "FarmersMarketsDidNotLoadNotification" }
467b5b60a759bcd1176b70728b23d7cb
34.57377
98
0.753456
false
false
false
false
paulicelli/RadioButton
refs/heads/master
RadioButton/RoundButton.swift
mit
1
/* ------------------------------------------------------------------------------ MIT License Copyright (c) 2017 Sabino Paulicelli 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. ------------------------------------------------------------------------------ RoundButton.swift ------------------------------------------------------------------------------ */ import UIKit final class RoundButton: UIButton { var borderWidth: CGFloat = 2.0 var primaryColor: UIColor = UIColor.blue var primaryColorWithAlpha: UIColor { return primaryColor.withAlphaComponent(0.25) } override public var buttonType: UIButtonType { return .custom } override public func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = bounds.size.width * 0.5 self.clipsToBounds = true setupColors() } func setupColors() { switch self.state { case UIControlState.normal: super.backgroundColor = .white self.setTitleColor(primaryColor, for: state) self.layer.borderColor = primaryColor.cgColor self.layer.borderWidth = borderWidth default: super.backgroundColor = primaryColorWithAlpha self.setTitleColor(.white, for: state) } } }
187105069aa6e173cb4b17b180eb0af1
32.044118
80
0.660436
false
false
false
false
wang-chuanhui/CHSDK
refs/heads/master
Source/Transformation/StringTransform.swift
mit
1
// // StringTransform.swift // CHSDK // // Created by 王传辉 on 2017/8/4. // Copyright © 2017年 王传辉. All rights reserved. // import Foundation extension StringTransform where Self: CustomStringConvertible { public func _toString() -> String { return self.description } } extension NSString: StringTransform {} extension String: StringTransform {} extension Int: StringTransform {} extension Int8: StringTransform {} extension Int16: StringTransform {} extension Int32: StringTransform {} extension Int64: StringTransform {} extension UInt: StringTransform {} extension UInt8: StringTransform {} extension UInt16: StringTransform {} extension UInt32: StringTransform {} extension UInt64: StringTransform {} extension Float: StringTransform {} extension Double: StringTransform {} extension Bool: StringTransform {} extension RawRepresentable where RawValue: StringTransform { func _toString() -> String { return self.rawValue._toString() } } extension NSNumber: StringTransform { public func _toString() -> String { if NSStringFromClass(type(of: self)) == "__NSCFBoolean" { if boolValue { return "true" }else { return "false" } } return stringValue } } extension StringTransform { func _jsonString() -> String? { if let json = (self as? Transformational)?.___toJSONValue() { if JSONSerialization.isValidJSONObject(json) { do { let data = try JSONSerialization.data(withJSONObject: json) if let string = String(data: data, encoding: String.Encoding.utf8) { return string } } catch { handle(error) } } } return nil } } extension NSArray: StringTransform { public func _toString() -> String { if let jsonString = _jsonString() { return jsonString } do { let data = try JSONSerialization.data(withJSONObject: self, options: []) let string = String(data: data, encoding: .utf8) return string ?? description } catch { } return description } } extension Array: StringTransform { public func _toString() -> String { if let jsonString = _jsonString() { return jsonString } do { let data = try JSONSerialization.data(withJSONObject: self, options: []) let string = String(data: data, encoding: .utf8) return string ?? description } catch { } return description } } extension NSDictionary: StringTransform { public func _toString() -> String { if let jsonString = _jsonString() { return jsonString } do { let data = try JSONSerialization.data(withJSONObject: self, options: []) let string = String(data: data, encoding: .utf8) return string ?? description } catch { } return description } } extension Dictionary: StringTransform { public func _toString() -> String { if let jsonString = _jsonString() { return jsonString } do { let data = try JSONSerialization.data(withJSONObject: self, options: []) let string = String(data: data, encoding: .utf8) return string ?? description } catch { } return description } }
80835f7eae447c9bc2c1ac02e88a14e7
25.705882
88
0.574615
false
false
false
false
ilyapuchka/VIPER-SWIFT
refs/heads/master
VIPER-SWIFT/Classes/Modules/List/User Interface/Presenter/UpcomingDisplaySection.swift
mit
1
// // UpcomingDisplaySection.swift // VIPER-SWIFT // // Created by Conrad Stoll on 6/5/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import Foundation struct UpcomingDisplaySection : Equatable { let name : String let imageName : String var items : [UpcomingDisplayItem] = [] } func == (leftSide: UpcomingDisplaySection, rightSide: UpcomingDisplaySection) -> Bool { var hasEqualSections = false hasEqualSections = rightSide.items == leftSide.items return hasEqualSections }
cdd45c7cbb577adcf9975be8d51dd82c
22.818182
87
0.717017
false
false
false
false
kevll/LLImagePicker
refs/heads/master
LLImagePicker/LLImagePickerController.swift
mit
1
// // LLImagePickerController.swift // BuyInterflow // // Created by kevin on 2017/3/27. // Copyright © 2017年 Ecommerce. All rights reserved. // import UIKit import Photos @available(iOS 8.0, *) public final class LLImagePickerController: UIViewController { private var navController: UINavigationController! public var checkImg: UIImage? public var minimumNumberOfSelection: UInt! = 1 // default is 1 public var maximumNumberOfSelection: UInt? public var albumNavTitle: String? = "相册" public var cancelTitle: String? = "取消" public var confirmTitle: String? = "确定" public var openPhotoAuthorPrompt: String? = "请先前往设置打开App访问相册权限" public var downloadIcloudImagePrompt: String? = "请在系统相册下载iCloud图片后重试。" public var alreadySelectionNumPrompt: String? = "已选择%d张图片" public var didFinishPickingAssets: ((_ imagePickerController: LLImagePickerController ,_ assets: Array<PHAsset>)->Void)? public override func viewDidLoad() { super.viewDidLoad() setAlbumsViewController() } internal func setAlbumsViewController(){ weak var selfWeak:LLImagePickerController! = self let imagePickerController = LLAlbumsViewController() imagePickerController.checkImg = checkImg imagePickerController.minimumNumberOfSelection = minimumNumberOfSelection imagePickerController.maximumNumberOfSelection = maximumNumberOfSelection imagePickerController.albumNavTitle = albumNavTitle imagePickerController.cancelTitle = cancelTitle imagePickerController.confirmTitle = confirmTitle imagePickerController.openPhotoAuthorPrompt = openPhotoAuthorPrompt imagePickerController.downloadIcloudImagePrompt = downloadIcloudImagePrompt imagePickerController.alreadySelectionNumPrompt = alreadySelectionNumPrompt imagePickerController.didFinishPickingAssets = { (assets: Array<PHAsset>) in selfWeak.didFinishPickingAssets?(selfWeak,assets) } navController = UINavigationController.init(rootViewController: imagePickerController) navController.view.frame = self.view.bounds imagePickerController.backBtnClick = { selfWeak.dismiss(animated: true, completion: nil) } self.view.addSubview(navController.view) } }
64a94ccd02c3bca1acb6964ba5031939
39
124
0.73178
false
false
false
false
abonz/Swift
refs/heads/master
CoreAnimationSample3/CoreAnimationSample3/ViewController.swift
gpl-3.0
6
// // ViewController.swift // CoreAnimationSample3 // // Created by Carlos Butron on 02/12/14. // Copyright (c) 2015 Carlos Butron. All rights reserved. // // This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later // version. // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License along with this program. If not, see // http:/www.gnu.org/licenses/. // import UIKit class ViewController: UIViewController { var position = true @IBOutlet weak var image: UIImageView! @IBAction func animate(sender: UIButton) { if (position){ //SAMPLE2 let animation:CABasicAnimation! = CABasicAnimation(keyPath:"position") animation.toValue = NSValue(CGPoint:CGPointMake(160, 200)) //SAMPLE2 animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false let resizeAnimation:CABasicAnimation = CABasicAnimation(keyPath:"bounds.size") resizeAnimation.toValue = NSValue(CGSize:CGSizeMake(240, 60)) //SAMPLE2 resizeAnimation.fillMode = kCAFillModeForwards resizeAnimation.removedOnCompletion = false //SAMPLE3 UIView.animateWithDuration(5.0, animations:{ //PROPERTIES CHANGES TO ANIMATE self.image.alpha = 0.0 //alpha to zero in 5 seconds }, completion: {(value: Bool) in //when finished animation do this.. self.image.alpha = 1.0 self.image.layer.addAnimation(animation, forKey: "position") self.image.layer.addAnimation(resizeAnimation, forKey: "bounds.size") }) position = false } else{ let animation:CABasicAnimation! = CABasicAnimation(keyPath:"position") animation.fromValue = NSValue(CGPoint:CGPointMake(160, 200)) //SAMPLE2 animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false let resizeAnimation:CABasicAnimation = CABasicAnimation(keyPath:"bounds.size") resizeAnimation.fromValue = NSValue(CGSize:CGSizeMake(240, 60)) //SAMPLE2 resizeAnimation.fillMode = kCAFillModeForwards resizeAnimation.removedOnCompletion = false image.layer.addAnimation(animation, forKey: "position") image.layer.addAnimation(resizeAnimation, forKey: "bounds.size") position = true } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
d97b1147ec0022e86bb62045268f39a8
32.324324
121
0.572587
false
false
false
false
stripe/stripe-ios
refs/heads/master
StripePayments/StripePayments/API Bindings/Models/PaymentMethods/STPPaymentMethodBillingDetails.swift
mit
1
// // STPPaymentMethodBillingDetails.swift // StripePayments // // Created by Yuki Tokuhiro on 3/5/19. // Copyright © 2019 Stripe, Inc. All rights reserved. // import Foundation /// Billing information associated with a `STPPaymentMethod` that may be used or required by particular types of payment methods. /// - seealso: https://stripe.com/docs/api/payment_methods/object#payment_method_object-billing_details public class STPPaymentMethodBillingDetails: NSObject, STPAPIResponseDecodable, STPFormEncodable { @objc public var additionalAPIParameters: [AnyHashable: Any] = [:] /// Billing address. @objc public var address: STPPaymentMethodAddress? /// Email address. @objc public var email: String? /// Full name. @objc public var name: String? /// Billing phone number (including extension). @objc public var phone: String? @objc public private(set) var allResponseFields: [AnyHashable: Any] = [:] /// :nodoc: @objc public override var description: String { let props = [ // Object String(format: "%@: %p", NSStringFromClass(STPPaymentMethodBillingDetails.self), self), // Properties "name = \(name ?? "")", "phone = \(phone ?? "")", "email = \(email ?? "")", "address = \(String(describing: address))", ] return "<\(props.joined(separator: "; "))>" } /// :nodoc: @objc public override required init() { super.init() } // MARK: - STPFormEncodable @objc public class func propertyNamesToFormFieldNamesMapping() -> [String: String] { return [ NSStringFromSelector(#selector(getter:address)): "address", NSStringFromSelector(#selector(getter:email)): "email", NSStringFromSelector(#selector(getter:name)): "name", NSStringFromSelector(#selector(getter:phone)): "phone", ] } @objc public class func rootObjectName() -> String? { return nil } // MARK: - NSCopying @objc(copyWithZone:) func copy(with zone: NSZone? = nil) -> Any { let copyBillingDetails = type(of: self).init() copyBillingDetails.allResponseFields = allResponseFields copyBillingDetails.address = address?.copy() as? STPPaymentMethodAddress copyBillingDetails.email = email copyBillingDetails.name = name copyBillingDetails.phone = phone return copyBillingDetails } // MARK: - Equality /// :nodoc: @objc public override func isEqual(_ other: Any?) -> Bool { return isEqual(to: other as? STPPaymentMethodBillingDetails) } func isEqual(to other: STPPaymentMethodBillingDetails?) -> Bool { if self === other { return true } guard let other = other else { return false } if !((additionalAPIParameters as NSDictionary).isEqual(to: other.additionalAPIParameters)) { return false } return address == other.address && email == other.email && name == other.name && phone == other.phone } // MARK: - STPAPIResponseDecodable @objc public class func decodedObject(fromAPIResponse response: [AnyHashable: Any]?) -> Self? { guard let response = response else { return nil } let dict = response.stp_dictionaryByRemovingNulls() let billingDetails = self.init() billingDetails.allResponseFields = response billingDetails.address = STPPaymentMethodAddress.decodedObject( fromAPIResponse: dict.stp_dictionary(forKey: "address") ) billingDetails.email = dict.stp_string(forKey: "email") billingDetails.name = dict.stp_string(forKey: "name") billingDetails.phone = dict.stp_string(forKey: "phone") return billingDetails } } /// :nodoc: extension STPPaymentMethodBillingDetails { /// Convenience initializer for creating an `STPPaymentMethodBillingDetails` instance with a postal and country code @objc convenience init( postalCode: String, countryCode: String? = Locale.autoupdatingCurrent.regionCode ) { self.init() let address = STPPaymentMethodAddress() address.postalCode = postalCode address.country = countryCode self.address = address } }
97e5a061a5b6094f1b9a1176e610c39f
32.416667
129
0.63251
false
false
false
false
crazypoo/PTools
refs/heads/master
Pods/SwifterSwift/Sources/SwifterSwift/SwiftStdlib/ArrayExtensions.swift
mit
1
// // ArrayExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/5/16. // Copyright © 2016 SwifterSwift // // MARK: - Methods public extension Array { /// SwifterSwift: Insert an element at the beginning of array. /// /// [2, 3, 4, 5].prepend(1) -> [1, 2, 3, 4, 5] /// ["e", "l", "l", "o"].prepend("h") -> ["h", "e", "l", "l", "o"] /// /// - Parameter newElement: element to insert. mutating func prepend(_ newElement: Element) { insert(newElement, at: 0) } /// SwifterSwift: Safely swap values at given index positions. /// /// [1, 2, 3, 4, 5].safeSwap(from: 3, to: 0) -> [4, 2, 3, 1, 5] /// ["h", "e", "l", "l", "o"].safeSwap(from: 1, to: 0) -> ["e", "h", "l", "l", "o"] /// /// - Parameters: /// - index: index of first element. /// - otherIndex: index of other element. mutating func safeSwap(from index: Index, to otherIndex: Index) { guard index != otherIndex else { return } guard startIndex..<endIndex ~= index else { return } guard startIndex..<endIndex ~= otherIndex else { return } swapAt(index, otherIndex) } /// SwifterSwift: Sort an array like another array based on a key path. If the other array doesn't contain a certain value, it will be sorted last. /// /// [MyStruct(x: 3), MyStruct(x: 1), MyStruct(x: 2)].sorted(like: [1, 2, 3], keyPath: \.x) /// -> [MyStruct(x: 1), MyStruct(x: 2), MyStruct(x: 3)] /// /// - Parameters: /// - otherArray: array containing elements in the desired order. /// - keyPath: keyPath indiciating the property that the array should be sorted by /// - Returns: sorted array. func sorted<T: Hashable>(like otherArray: [T], keyPath: KeyPath<Element, T>) -> [Element] { let dict = otherArray.enumerated().reduce(into: [:]) { $0[$1.element] = $1.offset } return sorted { guard let thisIndex = dict[$0[keyPath: keyPath]] else { return false } guard let otherIndex = dict[$1[keyPath: keyPath]] else { return true } return thisIndex < otherIndex } } } // MARK: - Methods (Equatable) public extension Array where Element: Equatable { /// SwifterSwift: Remove all instances of an item from array. /// /// [1, 2, 2, 3, 4, 5].removeAll(2) -> [1, 3, 4, 5] /// ["h", "e", "l", "l", "o"].removeAll("l") -> ["h", "e", "o"] /// /// - Parameter item: item to remove. /// - Returns: self after removing all instances of item. @discardableResult mutating func removeAll(_ item: Element) -> [Element] { removeAll(where: { $0 == item }) return self } /// SwifterSwift: Remove all instances contained in items parameter from array. /// /// [1, 2, 2, 3, 4, 5].removeAll([2,5]) -> [1, 3, 4] /// ["h", "e", "l", "l", "o"].removeAll(["l", "h"]) -> ["e", "o"] /// /// - Parameter items: items to remove. /// - Returns: self after removing all instances of all items in given array. @discardableResult mutating func removeAll(_ items: [Element]) -> [Element] { guard !items.isEmpty else { return self } removeAll(where: { items.contains($0) }) return self } /// SwifterSwift: Remove all duplicate elements from Array. /// /// [1, 2, 2, 3, 4, 5].removeDuplicates() -> [1, 2, 3, 4, 5] /// ["h", "e", "l", "l", "o"]. removeDuplicates() -> ["h", "e", "l", "o"] /// /// - Returns: Return array with all duplicate elements removed. @discardableResult mutating func removeDuplicates() -> [Element] { // Thanks to https://github.com/sairamkotha for improving the method self = reduce(into: [Element]()) { if !$0.contains($1) { $0.append($1) } } return self } /// SwifterSwift: Return array with all duplicate elements removed. /// /// [1, 1, 2, 2, 3, 3, 3, 4, 5].withoutDuplicates() -> [1, 2, 3, 4, 5]) /// ["h", "e", "l", "l", "o"].withoutDuplicates() -> ["h", "e", "l", "o"]) /// /// - Returns: an array of unique elements. /// func withoutDuplicates() -> [Element] { // Thanks to https://github.com/sairamkotha for improving the method return reduce(into: [Element]()) { if !$0.contains($1) { $0.append($1) } } } /// SwifterSwift: Returns an array with all duplicate elements removed using KeyPath to compare. /// /// - Parameter path: Key path to compare, the value must be Equatable. /// - Returns: an array of unique elements. func withoutDuplicates<E: Equatable>(keyPath path: KeyPath<Element, E>) -> [Element] { return reduce(into: [Element]()) { (result, element) in if !result.contains(where: { $0[keyPath: path] == element[keyPath: path] }) { result.append(element) } } } /// SwifterSwift: Returns an array with all duplicate elements removed using KeyPath to compare. /// /// - Parameter path: Key path to compare, the value must be Hashable. /// - Returns: an array of unique elements. func withoutDuplicates<E: Hashable>(keyPath path: KeyPath<Element, E>) -> [Element] { var set = Set<E>() return filter { set.insert($0[keyPath: path]).inserted } } }
b6fac9096da7070b2c07c5caf2a9a9a0
38.352518
151
0.550091
false
false
false
false
IngmarStein/swift
refs/heads/master
test/stdlib/Map.swift
apache-2.0
4
//===--- Map.swift - tests for lazy mapping -------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // Check that the generic parameters are called 'Base' and 'Element'. protocol TestProtocol1 {} extension LazyMapIterator where Base : TestProtocol1, Element : TestProtocol1 { var _baseIsTestProtocol1: Bool { fatalError("not implemented") } } extension LazyMapSequence where Base : TestProtocol1, Element : TestProtocol1 { var _baseIsTestProtocol1: Bool { fatalError("not implemented") } } extension LazyMapCollection where Base : TestProtocol1, Element : TestProtocol1 { var _baseIsTestProtocol1: Bool { fatalError("not implemented") } } // CHECK: testing... print("testing...") // Test mapping a collection // CHECK-NEXT: [6, 9, 12, 15, 18, 21] let a = Array((2..<8).lazy.map { $0 * 3 }) print(a) // Test mapping a sequence let s = a.makeIterator().lazy.map { $0 / 3 } // CHECK-NEXT: <2, 3, 4, 5, 6, 7> print("<", terminator: "") var prefix = "" for x in s { print("\(prefix)\(x)", terminator: "") prefix = ", " } print(">") //===--- Avoid creating gratuitously self-destructive sequences -----------===// // In a naive implementation, mapping over a non-self-destructive // Sequence having a reference-semantics IteratorProtocol produces a // self-destructive mapped view. This is technically correct because // Sequences are allowed to be self-destructive, and theoretically // every multi-pass Sequence would be a Collection, but Sequences are // much easier to build than Collections and it would be extremely // surprising for users if their mappings were not stable. // An IteratorProtocol with reference semantics class Counter : IteratorProtocol { func next() -> Int? { if n >= end { return nil } n += 1 return n-1 } init(_ n: Int, _ end: Int) { self.n = n self.end = end } var n: Int var end: Int } // A Sequence with value semantics struct IntRange : Sequence { func makeIterator() -> Counter { return Counter(start, end) } var start: Int var end: Int } // Make sure we can iterate a mapped view of IntRange without // consuming it. let m1 = IntRange(start: 1, end: 5).lazy.map { $0 * 2 } // CHECK-NEXT: [2, 4, 6, 8] print(Array(m1)) // A second iteration produces the same result. // CHECK-NEXT: [2, 4, 6, 8] print(Array(m1)) // CHECK-NEXT: all done. print("all done.")
9c5345fe2c097bf3b704e7c2654769b9
26.625
81
0.653324
false
true
false
false
BlurredSoftware/BSWFoundation
refs/heads/develop
Sources/BSWFoundation/Parse/JSONParser.swift
mit
1
// // Created by Pierluigi Cifani. // Copyright (c) 2016 TheLeftBit SL. All rights reserved. // import Foundation import Task; import Deferred public enum JSONParser { private static let queue = DispatchQueue(label: "com.bswfoundation.JSONParser") public static let jsonDecoder = JSONDecoder() public static let Options: JSONSerialization.ReadingOptions = [.allowFragments] public static func parseData<T: Decodable>(_ data: Data) -> Task<T> { let task: Task<T> = Task.async(upon: queue, onCancel: Error.canceled) { let result: Task<T>.Result = self.parseData(data) return try result.extract() } return task } public static func dataIsNull(_ data: Data) -> Bool { guard let j = try? JSONSerialization.jsonObject(with: data, options: JSONParser.Options) else { return false } guard let _ = j as? NSNull else { return false } return true } public static func parseDataAsJSONPrettyPrint(_ data: Data) -> String? { guard let json = try? JSONSerialization.jsonObject(with: data, options: JSONParser.Options) else { return nil } let options: JSONSerialization.WritingOptions = { if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { return [.fragmentsAllowed,.withoutEscapingSlashes] } else { return [.fragmentsAllowed] } }() guard let prettyPrintedData = try? JSONSerialization.data(withJSONObject: json, options: options) else { return nil } return String(data: prettyPrintedData, encoding: .utf8) } public static func errorMessageFromData(_ data: Data) -> String? { guard let j = try? JSONSerialization.jsonObject(with: data, options: JSONParser.Options) else { return nil } guard let dictionary = j as? [String: String] else { return nil } return dictionary["error"] } static public func parseData<T: Decodable>(_ data: Data) -> Task<T>.Result { guard T.self != VoidResponse.self else { let response = VoidResponse.init() as! T return .success(response) } /// Turns out that on iOS 12, parsing basic types using /// Swift's `Decodable` is failing for some unknown /// reasons. To lazy to file a radar... /// So here we're instead using the good and trusted /// `NSJSONSerialization` class if T.self == Bool.self || T.self == Int.self || T.self == String.self { if let output = try? JSONSerialization.jsonObject(with: data, options: JSONParser.Options) as? T { return .success(output) } else { return .failure(Error.malformedJSON) } } if let provider = T.self as? DateDecodingStrategyProvider.Type { jsonDecoder.dateDecodingStrategy = .formatted(provider.dateDecodingStrategy) } else { jsonDecoder.dateDecodingStrategy = .formatted(iso8601DateFormatter) } let result: Task<T>.Result do { let output: T = try jsonDecoder.decode(T.self, from: data) result = .success(output) } catch let decodingError as DecodingError { switch decodingError { case .keyNotFound(let missingKey, let context): print("*ERROR* decoding, key \"\(missingKey)\" is missing, Context: \(context)") result = .failure(Error.malformedSchema) case .typeMismatch(let type, let context): print("*ERROR* decoding, type \"\(type)\" mismatched, context: \(context)") result = .failure(Error.malformedSchema) case .valueNotFound(let type, let context): print("*ERROR* decoding, value not found \"\(type)\", context: \(context)") result = .failure(Error.malformedSchema) case .dataCorrupted(let context): print("*ERROR* Data Corrupted \"\(context)\")") if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) { print("*ERROR* incoming JSON: \(string)") } result = .failure(Error.malformedJSON) @unknown default: result = .failure(Error.unknownError) } } catch { result = .failure(Error.unknownError) } return result } //MARK: Error public enum Error: Swift.Error { case malformedJSON case malformedSchema case unknownError case canceled } } #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) public extension JSONParser { static func parseData<T: Decodable>(_ data: Data) -> CombineTask<T> { let task: Task<T> = self.parseData(data) return task.future } static func parseData<T: Decodable>(_ data: Data) -> Swift.Result<T, Swift.Error> { return parseData(data).swiftResult } } #endif public protocol DateDecodingStrategyProvider { static var dateDecodingStrategy: DateFormatter { get } } private var iso8601DateFormatter: DateFormatter { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" return formatter } extension Array: DateDecodingStrategyProvider where Element: DateDecodingStrategyProvider { public static var dateDecodingStrategy: DateFormatter { return Element.dateDecodingStrategy } }
958667835820d8ff46458a93869df7a2
35.452229
125
0.605452
false
false
false
false
DikeyKing/WeCenterMobile-iOS
refs/heads/master
WeCenterMobile/View/Answer/AnswerCellWithQuestionTitle.swift
gpl-2.0
1
// // AnswerCellWithQuestionTitle.swift // WeCenterMobile // // Created by Darren Liu on 15/4/12. // Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved. // import UIKit class AnswerCellWithQuestionTitle: UITableViewCell { @IBOutlet weak var questionTitleLabel: UILabel! @IBOutlet weak var answerUserAvatarView: MSRRoundedImageView! @IBOutlet weak var answerUserNameLabel: UILabel! @IBOutlet weak var answerBodyLabel: UILabel! @IBOutlet weak var answerAgreementCountLabel: UILabel! @IBOutlet weak var questionButton: UIButton! @IBOutlet weak var answerButton: UIButton! @IBOutlet weak var userButton: UIButton! @IBOutlet weak var containerView: UIView! @IBOutlet weak var questionContainerView: UIView! @IBOutlet weak var userContainerView: UIView! @IBOutlet weak var answerContainerView: UIView! @IBOutlet weak var separatorA: UIView! @IBOutlet weak var separatorB: UIView! override func awakeFromNib() { super.awakeFromNib() let theme = SettingsManager.defaultManager.currentTheme msr_scrollView?.delaysContentTouches = false for v in [containerView, answerAgreementCountLabel] { v.msr_borderColor = theme.borderColorA } for v in [separatorA, separatorB] { v.backgroundColor = theme.borderColorA } for v in [questionContainerView, userContainerView] { v.backgroundColor = theme.backgroundColorB } for v in [answerContainerView, answerAgreementCountLabel] { v.backgroundColor = theme.backgroundColorA } for v in [questionButton, userButton, answerButton] { v.msr_setBackgroundImageWithColor(theme.highlightColor, forState: .Highlighted) } for v in [answerBodyLabel, answerAgreementCountLabel] { v.textColor = theme.subtitleTextColor } questionTitleLabel.textColor = theme.titleTextColor } func update(#answer: Answer) { questionTitleLabel.text = answer.question!.title answerUserAvatarView.wc_updateWithUser(answer.user) let theme = SettingsManager.defaultManager.currentTheme let text = NSMutableAttributedString(string: answer.user?.name ?? "匿名用户", attributes: [ NSFontAttributeName: UIFont.systemFontOfSize(14), NSForegroundColorAttributeName: theme.titleTextColor]) if let signature = answer.user?.signature?.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet()) { text.appendAttributedString(NSAttributedString(string: "," + signature, attributes: [ NSFontAttributeName: UIFont.systemFontOfSize(14), NSForegroundColorAttributeName: theme.footnoteTextColor])) } answerUserNameLabel.attributedText = text answerBodyLabel.text = answer.body!.wc_plainString answerAgreementCountLabel.text = answer.agreementCount?.description ?? "0" questionButton.msr_userInfo = answer.question answerButton.msr_userInfo = answer userButton.msr_userInfo = answer.user setNeedsLayout() layoutIfNeeded() } }
33b24c67af14863d5f73b6c1a76e445d
42.053333
122
0.699597
false
false
false
false
StevenUpForever/FBSimulatorControl
refs/heads/master
fbsimctl/FBSimulatorControlKit/Sources/SimulatorRunners.swift
bsd-3-clause
2
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import Foundation import FBSimulatorControl extension FileOutput { func makeWriter() throws -> FBFileWriter { switch self { case .path(let path): return try FBFileWriter(forFilePath: path, blocking: true) case .standardOut: return FBFileWriter(fileHandle: FileHandle.standardOutput, blocking: true) } } } struct SimulatorCreationRunner : Runner { let context: iOSRunnerContext<CreationSpecification> func run() -> CommandResult { do { for configuration in self.configurations { self.context.reporter.reportSimpleBridge(.create, .started, configuration) let simulator = try self.context.simulatorControl.set.createSimulator(with: configuration) self.context.defaults.updateLastQuery(FBiOSTargetQuery.udids([simulator.udid])) self.context.reporter.reportSimpleBridge(.create, .ended, simulator) } return .success(nil) } catch let error as NSError { return .failure("Failed to Create Simulator \(error.description)") } } fileprivate var configurations: [FBSimulatorConfiguration] { get { switch self.context.value { case .allMissingDefaults: return self.context.simulatorControl.set.configurationsForAbsentDefaultSimulators() case .individual(let configuration): return [configuration.simulatorConfiguration] } }} } struct SimulatorActionRunner : Runner { let context: iOSRunnerContext<(Action, FBSimulator)> func run() -> CommandResult { let (action, simulator) = self.context.value let reporter = SimulatorReporter(simulator: simulator, format: self.context.format, reporter: self.context.reporter) defer { simulator.userEventSink = nil } let context = self.context.replace((action, simulator, reporter)) return SimulatorActionRunner.makeRunner(context).run() } static func makeRunner(_ context: iOSRunnerContext<(Action, FBSimulator, SimulatorReporter)>) -> Runner { let (action, simulator, reporter) = context.value let covariantTuple: (Action, FBiOSTarget, iOSReporter) = (action, simulator, reporter) if let runner = iOSActionProvider(context: context.replace(covariantTuple)).makeRunner() { return runner } switch action { case .approve(let bundleIDs): return iOSTargetRunner.simple(reporter, .approve, StringsSubject(bundleIDs)) { try simulator.authorizeLocationSettings(bundleIDs) } case .clearKeychain(let maybeBundleID): return iOSTargetRunner.simple(reporter, .clearKeychain, ControlCoreSubject(simulator)) { if let bundleID = maybeBundleID { try simulator.killApplication(withBundleID: bundleID) } try simulator.clearKeychain() } case .delete: return iOSTargetRunner.simple(reporter, .delete, ControlCoreSubject(simulator)) { try simulator.set!.delete(simulator) } case .erase: return iOSTargetRunner.simple(reporter, .erase, ControlCoreSubject(simulator)) { try simulator.erase() } case .focus: return iOSTargetRunner.simple(reporter, .focus, ControlCoreSubject(simulator)) { try simulator.focus() } case .keyboardOverride: return iOSTargetRunner.simple(reporter, .keyboardOverride, ControlCoreSubject(simulator)) { try simulator.setupKeyboard() } case .open(let url): return iOSTargetRunner.simple(reporter, .open, url.bridgedAbsoluteString) { try simulator.open(url) } case .relaunch(let appLaunch): return iOSTargetRunner.simple(reporter, .relaunch, ControlCoreSubject(appLaunch)) { try simulator.launchOrRelaunchApplication(appLaunch) } case .search(let search): return SearchRunner(reporter, search) case .serviceInfo(let identifier): return ServiceInfoRunner(reporter: reporter, identifier: identifier) case .shutdown: return iOSTargetRunner.simple(reporter, .shutdown, ControlCoreSubject(simulator)) { try simulator.set!.kill(simulator) } case .tap(let x, let y): return iOSTargetRunner.simple(reporter, .tap, ControlCoreSubject(simulator)) { let event = FBSimulatorHIDEvent.tapAt(x: x, y: y) try event.perform(on: simulator.connect().connectToHID()) } case .setLocation(let latitude, let longitude): return iOSTargetRunner.simple(reporter, .setLocation, ControlCoreSubject(simulator)) { try simulator.setLocation(latitude, longitude: longitude) } case .upload(let diagnostics): return UploadRunner(reporter, diagnostics) case .watchdogOverride(let bundleIDs, let timeout): return iOSTargetRunner.simple(reporter, .watchdogOverride, StringsSubject(bundleIDs)) { try simulator.overrideWatchDogTimer(forApplications: bundleIDs, withTimeout: timeout) } default: return CommandResultRunner.unimplementedActionRunner(action, target: simulator, format: context.format) } } } private struct SearchRunner : Runner { let reporter: SimulatorReporter let search: FBBatchLogSearch init(_ reporter: SimulatorReporter, _ search: FBBatchLogSearch) { self.reporter = reporter self.search = search } func run() -> CommandResult { let simulator = self.reporter.simulator let diagnostics = simulator.diagnostics.allDiagnostics() let results = search.search(diagnostics) self.reporter.report(.search, .discrete, ControlCoreSubject(results)) return .success(nil) } } private struct ServiceInfoRunner : Runner { let reporter: SimulatorReporter let identifier: String func run() -> CommandResult { var pid: pid_t = 0 guard let _ = try? self.reporter.simulator.launchctl.serviceName(forBundleID: self.identifier, processIdentifierOut: &pid) else { return .failure("Could not get service for name \(identifier)") } guard let processInfo = self.reporter.simulator.processFetcher.processFetcher.processInfo(for: pid) else { return .failure("Could not get process info for pid \(pid)") } return .success(SimpleSubject(.serviceInfo, .discrete, ControlCoreSubject(processInfo))) } } private struct UploadRunner : Runner { let reporter: SimulatorReporter let diagnostics: [FBDiagnostic] init(_ reporter: SimulatorReporter, _ diagnostics: [FBDiagnostic]) { self.reporter = reporter self.diagnostics = diagnostics } func run() -> CommandResult { var diagnosticLocations: [(FBDiagnostic, String)] = [] for diagnostic in diagnostics { guard let localPath = diagnostic.asPath else { return .failure("Could not get a local path for diagnostic \(diagnostic)") } diagnosticLocations.append((diagnostic, localPath)) } let mediaPredicate = NSPredicate.forMediaPaths() let media = diagnosticLocations.filter { (_, location) in mediaPredicate.evaluate(with: location) } if media.count > 0 { let paths = media.map { $0.1 } let runner = iOSTargetRunner.simple(reporter, .upload, StringsSubject(paths)) { try FBUploadMediaStrategy(simulator: self.reporter.simulator).uploadMedia(paths) } let result = runner.run() switch result.outcome { case .failure: return result default: break } } let basePath = self.reporter.simulator.auxillaryDirectory let arbitraryPredicate = NSCompoundPredicate(notPredicateWithSubpredicate: mediaPredicate) let arbitrary = diagnosticLocations.filter{ arbitraryPredicate.evaluate(with: $0.1) } for (sourceDiagnostic, sourcePath) in arbitrary { guard let destinationPath = try? sourceDiagnostic.writeOut(toDirectory: basePath as String) else { return CommandResult.failure("Could not write out diagnostic \(sourcePath) to path") } let destinationDiagnostic = FBDiagnosticBuilder().updatePath(destinationPath).build() self.reporter.report(.upload, .discrete, ControlCoreSubject(destinationDiagnostic)) } return .success(nil) } }
ba63895e5ad26f02ce23508f607714e5
37.105505
133
0.713254
false
false
false
false
pjocprac/PTPopupWebView
refs/heads/master
Pod/Classes/PTPopupWebViewController.swift
mit
1
// // PopupWebViewController.swift // PTPopupWebView // // Created by Takeshi Watanabe on 2016/03/19. // Copyright © 2016 Takeshi Watanabe. All rights reserved. // import Foundation import UIKit import WebKit open class PTPopupWebViewController : UIViewController { public enum PTPopupWebViewControllerBackgroundStyle { // blur effect background case blurEffect (UIBlurEffectStyle) // opacity background case opacity (UIColor?) // transparent background case transparent } public enum PTPopupWebViewControllerTransitionStyle { /// Transition without style. case none /// Transition with fade in/out effect. case fade (TimeInterval) /// Transition with slide in/out effect. case slide (PTPopupWebViewEffectDirection, TimeInterval, Bool) /// Transition with spread out/in style case spread (TimeInterval) /// Transition with pop out/in style case pop (TimeInterval, Bool) } public enum PTPopupWebViewEffectDirection { case top, bottom, left, right } @IBOutlet weak fileprivate var contentView : UIView! @IBOutlet weak fileprivate var blurView: UIVisualEffectView! /// PTPopupWebView open fileprivate(set) var popupView = PTPopupWebView().style(PTPopupWebViewControllerStyle()) /// Background Style open fileprivate(set) var backgroundStyle : PTPopupWebViewControllerBackgroundStyle = .blurEffect(.dark) /// Transition Style open fileprivate(set) var transitionStyle : UIModalTransitionStyle = .crossDissolve /// Popup Appear Style open fileprivate(set) var popupAppearStyle : PTPopupWebViewControllerTransitionStyle = .pop(0.3, true) /// Popup Disappear Style open fileprivate(set) var popupDisappearStyle : PTPopupWebViewControllerTransitionStyle = .pop(0.3, true) fileprivate let attributes = [ NSLayoutAttribute.top, NSLayoutAttribute.left, NSLayoutAttribute.bottom, NSLayoutAttribute.right ] fileprivate var constraints : [NSLayoutAttribute : NSLayoutConstraint] = [:] override open func loadView() { let bundle = Bundle(for: type(of: self)) switch backgroundStyle { case .blurEffect(let blurStyle): let nib = UINib(nibName: "PTPopupWebViewControllerBlur", bundle: bundle) view = nib.instantiate(withOwner: self, options: nil).first as! UIView blurView.effect = UIBlurEffect(style: blurStyle) case .opacity(let color): let view = UIView(frame: UIScreen.main.bounds) self.view = view self.contentView = view self.contentView.backgroundColor = color case .transparent: let view = UIView(frame: UIScreen.main.bounds) self.view = view self.contentView = view self.contentView.backgroundColor = .clear } } override open func viewDidLoad() { super.viewDidLoad() popupView.delegate = self self.contentView.addSubview(popupView) popupView.translatesAutoresizingMaskIntoConstraints = false for attribute in attributes { let constraint = NSLayoutConstraint( item : contentView, attribute: attribute, relatedBy: NSLayoutRelation.equal, toItem: popupView, attribute: attribute, multiplier: 1.0, constant: 0.0) contentView.addConstraint(constraint) constraints[attribute] = constraint } } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) switch popupAppearStyle { case .none: popupView.alpha = 1 default : popupView.alpha = 0 } } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) switch popupAppearStyle { case .none: break case .fade (let duration): UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: {self.popupView.alpha = 1}, completion: nil) case .slide(let direction, let duration, let damping): self.popupView.alpha = 1 switch direction { case .top : self.popupView.transform = CGAffineTransform(translationX: 0, y: -self.view.bounds.height) case .bottom: self.popupView.transform = CGAffineTransform(translationX: 0, y: self.view.bounds.height) case .left : self.popupView.transform = CGAffineTransform(translationX: -self.view.bounds.width, y: 0) case .right : self.popupView.transform = CGAffineTransform( translationX: self.view.bounds.width, y: 0) } let animations = { self.popupView.transform = CGAffineTransform(translationX: 0, y: 0) } if damping { UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil) } else { UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil) } case .spread (let duration): popupView.alpha = 1 CATransaction.begin() CATransaction.setCompletionBlock({ self.popupView.layer.mask = nil }) CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)) let maskLayer = CALayer() maskLayer.backgroundColor = UIColor.white.cgColor maskLayer.cornerRadius = popupView.style?.cornerRadius ?? 0 let oldBounds = CGRect.zero let newBounds = popupView.contentView.bounds let revealAnimation = CABasicAnimation(keyPath: "bounds") revealAnimation.fromValue = NSValue(cgRect: oldBounds) revealAnimation.toValue = NSValue(cgRect: newBounds) revealAnimation.duration = duration maskLayer.frame = popupView.contentView.frame popupView.layer.mask = maskLayer maskLayer.add(revealAnimation, forKey: "revealAnimation") CATransaction.commit() case .pop (let duration, let damping): popupView.alpha = 1 popupView.transform = CGAffineTransform(scaleX: 0, y: 0) let animations = { self.popupView.transform = CGAffineTransform(scaleX: 1, y: 1) } if damping { UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil) } else { UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil) } } } /** Set the background style (Default: .BlurEffect(.Dark)) - parameters: - style: PTPopupWebViewControllerBackgroundStyle */ open func backgroundStyle(_ style: PTPopupWebViewControllerBackgroundStyle) -> Self { self.backgroundStyle = style return self } /** Set the tansition style (Default: .CrossDissolve) - parameters: - style: UIModalTransitionStyle */ open func transitionStyle(_ style: UIModalTransitionStyle) -> Self { self.transitionStyle = style return self } /** Set the popup appear style (Default: .None) - parameters: - style: PTPopupWebViewControllerTransitionStyle */ open func popupAppearStyle(_ style: PTPopupWebViewControllerTransitionStyle) -> Self { self.popupAppearStyle = style return self } /** Set the popup disappear style (Default: .None) - parameters: - style: PTPopupWebViewControllerTransitionStyle */ open func popupDisappearStyle(_ style: PTPopupWebViewControllerTransitionStyle) -> Self { self.popupDisappearStyle = style return self } /** Show the popup view. Transition from the ViewController, which is - foreground view controller (without argument) - specified view controller (with argument) - parameters: - presentViewController: transition source ViewController */ open func show(_ presentViewController: UIViewController? = nil) { modalPresentationStyle = UIModalPresentationStyle.overCurrentContext modalTransitionStyle = self.transitionStyle if let presentViewController = presentViewController { presentViewController.present(self, animated: true, completion: nil) } else { var rootViewController = UIApplication.shared.keyWindow?.rootViewController; if rootViewController != nil { while ((rootViewController!.presentedViewController) != nil) { rootViewController = rootViewController!.presentedViewController; } rootViewController!.present(self, animated: true, completion: nil) } } } override open var prefersStatusBarHidden : Bool { return true } } extension PTPopupWebViewController : PTPopupWebViewDelegate { public func close() { let completion:(Bool) -> Void = { completed in self.dismiss(animated: true, completion: nil) } switch popupDisappearStyle { case .none: completion(true) case .fade (let duration): UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: {self.popupView.alpha = 0}, completion: completion) case .slide(let direction, let duration, let damping): let animations = { switch direction { case .top : self.popupView.transform = CGAffineTransform(translationX: 0, y: -self.view.bounds.height) case .bottom: self.popupView.transform = CGAffineTransform(translationX: 0, y: self.view.bounds.height) case .left : self.popupView.transform = CGAffineTransform(translationX: -self.view.bounds.width, y: 0) case .right : self.popupView.transform = CGAffineTransform( translationX: self.view.bounds.width, y: 0) } } if damping { let springAnimations = { switch direction { case .top : self.popupView.transform = CGAffineTransform(translationX: 0, y: self.popupView.bounds.height * 0.05) case .bottom: self.popupView.transform = CGAffineTransform(translationX: 0, y: -self.popupView.bounds.height * 0.05) case .left : self.popupView.transform = CGAffineTransform( translationX: self.popupView.bounds.width * 0.05, y: 0) case .right : self.popupView.transform = CGAffineTransform(translationX: -self.popupView.bounds.width * 0.05, y: 0) } } UIView.animate( withDuration: duration/3, delay: 0, options: UIViewAnimationOptions(), animations: springAnimations, completion: { completed in UIView.animate( withDuration: duration * 2/3, delay: 0, options: UIViewAnimationOptions(), animations: animations, completion: completion) }) } else { UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil) } case .spread (let duration): CATransaction.begin() CATransaction.setCompletionBlock({ completion(true) }) CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)) let maskLayer = CALayer() maskLayer.backgroundColor = UIColor.white.cgColor maskLayer.cornerRadius = popupView.style?.cornerRadius ?? 0 let oldBounds = popupView.contentView.bounds let newBounds = CGRect.zero let revealAnimation = CABasicAnimation(keyPath: "bounds") revealAnimation.fromValue = NSValue(cgRect: oldBounds) revealAnimation.toValue = NSValue(cgRect: newBounds) revealAnimation.duration = duration revealAnimation.repeatCount = 0 maskLayer.frame = popupView.contentView.frame maskLayer.bounds = CGRect.zero popupView.layer.mask = maskLayer maskLayer.add(revealAnimation, forKey: "revealAnimation") CATransaction.commit() case .pop (let duration, let damping): if damping { UIView.animate( withDuration: duration/3, delay: 0, options: UIViewAnimationOptions(), animations: { self.popupView.transform = CGAffineTransform(scaleX: 1.05, y: 1.05) }, completion: { completed in UIView.animate( withDuration: duration * 2/3, delay: 0, options: UIViewAnimationOptions(), animations: { self.popupView.transform = CGAffineTransform(scaleX: 0.0000001, y: 0.0000001) // if 0, no animation }, completion: completion) }) } else { UIView.animate( withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: { self.popupView.transform = CGAffineTransform(scaleX: 0.0000001, y: 0.0000001) }, completion: completion) } } } }
a4e779b600cdf2adf64b06fa6be3f4f9
39.308333
196
0.604507
false
false
false
false
iosexample/LearnSwift
refs/heads/master
Initialization.playground/Contents.swift
apache-2.0
1
//: Playground - noun: a place where people can play import Cocoa // The process of preparing an instance of a class. struct Fahrenheit { var temp: Double init() { temp = 32.0 } } var f = Fahrenheit() struct Celsius { var tempInCelsius: Double init(fromFahrenheit fahrenheit: Double) { tempInCelsius = (fahrenheit - 32.0) / 1.8 } init(fromKelvin kelvin: Double) { tempInCelsius = kelvin - 273.15 } } let boilingPoint = Celsius(fromFahrenheit: 212.0) boilingPoint.tempInCelsius let freezingPoint = Celsius(fromKelvin: 273.15) // Struct initializer struct Size { var width: Double, height = 0.0 } let twoByTwo = Size(width: 2.0, height: 2.0) //twoByTwo.width = 3.0 // Class initializer /* class Size { var width: Double, height: Double init(w: Double, h: Double) { width = w height = h } } let twoByTwo = Size(w: 2.0, h: 2.0) twoByTwo.width = 3.0 */ /* Require initializers */ class SomeClass { required init() { } deinit { print("deinit from SomeClass") } } class SomeSubclass: SomeClass { required init() { } deinit { print("deinit from SomeSubclass") } } /* Deinitialization */ for i in 0...1 { let someClass = SomeSubclass() }
14c10dc793c199d5ae8957e2fd877d47
16.025974
52
0.608696
false
false
false
false
OpsLabJPL/MarsImagesIOS
refs/heads/main
MarsImagesIOS/MER.swift
apache-2.0
1
// // MER.swift // MarsImagesIOS // // Created by Mark Powell on 7/28/17. // Copyright © 2017 Mark Powell. All rights reserved. // import Foundation class MER: Mission { let SOL = "Sol" let LTST = "LTST" let RMC = "RMC" let COURSE = "Course" enum TitleState { case START, SOL_NUMBER, IMAGESET_ID, INSTRUMENT_NAME, MARS_LOCAL_TIME, DISTANCE, YAW, PITCH, ROLL, TILT, ROVER_MOTION_COUNTER } override init() { super.init() self.eyeIndex = 23 self.instrumentIndex = 1 self.sampleTypeIndex = 12 self.cameraFOVs["N"] = 0.78539816 self.cameraFOVs["P"] = 0.27925268 } override func getSortableImageFilename(url: String) -> String { let tokens = url.components(separatedBy: "/") if tokens.count > 0 { let filename = tokens[tokens.count-1] if filename.hasPrefix("Sol") { return "0" //sort Cornell Pancam images first } else if (filename.hasPrefix("1") || filename.hasPrefix("2")) && filename.count == 31 { let index = filename.index(filename.startIndex, offsetBy: 23) return filename.substring(from: index) } return filename } return url } override func rowTitle(_ title: String) -> String { let merTitle = tokenize(title) as! MERTitle if merTitle.instrumentName == "Course Plot" { let distanceFormatted = String.localizedStringWithFormat("%.2f", merTitle.distance) return "Drive for \(distanceFormatted) meters" } return merTitle.instrumentName } override func caption(_ title: String) -> String { if let t = tokenize(title) as? MERTitle { if (t.instrumentName == "Course Plot") { return String(format:"Drive for %.2f meters on Sol %d", t.distance, t.sol) } else { return "\(t.instrumentName) image taken on Sol \(t.sol)." } } else { return super.caption(title) } } override func tokenize(_ title: String) -> Title { var mer = MERTitle() let tokens = title.components(separatedBy: " ") var state = TitleState.START for word in tokens { if word == SOL { state = TitleState.SOL_NUMBER continue } else if word == LTST { state = TitleState.MARS_LOCAL_TIME continue } else if word == RMC { state = TitleState.ROVER_MOTION_COUNTER continue } var indices:[Int] = [] switch (state) { case .START: break case .SOL_NUMBER: mer.sol = Int(word)! state = TitleState.IMAGESET_ID break case .IMAGESET_ID: if word == COURSE { mer = parseCoursePlotTitle(title: title, mer: mer) return mer } else { mer.imageSetID = word } state = TitleState.INSTRUMENT_NAME break case .INSTRUMENT_NAME: if mer.instrumentName.isEmpty { mer.instrumentName = String(word) } else { mer.instrumentName.append(" \(word)") } break case .MARS_LOCAL_TIME: mer.marsLocalTime = word break case .ROVER_MOTION_COUNTER: indices = word.components(separatedBy: "-").map { Int($0)! } mer.siteIndex = indices[0] mer.driveIndex = indices[1] break default: print("Unexpected state in parsing image title: \(state)") break } } return mer } func parseCoursePlotTitle(title:String, mer: MERTitle) -> MERTitle { let tokens = title.components(separatedBy: " ") var state = TitleState.START for word in tokens { if word == COURSE { mer.instrumentName = "Course Plot" } else if word == "Distance" { state = TitleState.DISTANCE continue } else if word == "yaw" { state = TitleState.YAW continue } else if word == "pitch" { state = TitleState.PITCH continue } else if word == "roll" { state = TitleState.ROLL continue } else if word == "tilt" { state = TitleState.TILT continue } else if word == "RMC" { state = TitleState.ROVER_MOTION_COUNTER continue } var indices:[Int] = [] switch (state) { case .START: break case .DISTANCE: mer.distance = Double(word)! break case .YAW: mer.yaw = Double(word)! break case .PITCH: mer.pitch = Double(word)! break case .ROLL: mer.roll = Double(word)! break case .TILT: mer.tilt = Double(word)! break case .ROVER_MOTION_COUNTER: indices = word.components(separatedBy: "-").map { Int($0)! } mer.siteIndex = indices[0] mer.driveIndex = indices[1] break default: print("Unexpected state in parsing course plot title: \(state)") } } return mer } override func imageName(imageId: String) -> String { if imageId.range(of:"False") != nil { return "Color" } let irange = imageId.index(imageId.startIndex, offsetBy: instrumentIndex)..<imageId.index(imageId.startIndex, offsetBy: instrumentIndex+1) let instrument = imageId[irange] if instrument == "N" || instrument == "F" || instrument == "R" { let erange = imageId.index(imageId.startIndex, offsetBy: eyeIndex)..<imageId.index(imageId.startIndex, offsetBy:eyeIndex+1) let eye = imageId[erange] if eye == "L" { return "Left" } else { return "Right" } } else if instrument == "P" { let prange = imageId.index(imageId.startIndex, offsetBy: eyeIndex)..<imageId.index(imageId.startIndex, offsetBy:eyeIndex+2) return String(imageId[prange]) } return "" } override func stereoImageIndices(imageIDs: [String]) -> (Int,Int)? { let imageid = imageIDs[0] let instrument = getInstrument(imageId: imageid) if !isStereo(instrument: instrument) { return nil } var leftImageIndex = -1; var rightImageIndex = -1; var index = 0; for imageId in imageIDs { let eye = getEye(imageId: imageId) if leftImageIndex == -1 && eye=="L" && !imageId.hasPrefix("Sol") { leftImageIndex = index; } if rightImageIndex == -1 && eye=="R" { rightImageIndex = index; } index += 1; } if (leftImageIndex >= 0 && rightImageIndex >= 0) { return (Int(leftImageIndex), Int(rightImageIndex)) } return nil } func isStereo(instrument:String) -> Bool { return instrument == "F" || instrument == "R" || instrument == "N" || instrument == "P" } override func getCameraId(imageId: String) -> String { if imageId.range(of:"Sol") != nil { return "P"; } else { return imageId[1] } } override func mastPosition() -> [Double] { return [0.456,0.026,-1.0969] } } class MERTitle: Title { var distance = 0.0 var yaw = 0.0 var pitch = 0.0 var roll = 0.0 var tilt = 0.0 }
fadd0133b623fef79a576697777c7965
30.591078
146
0.479525
false
false
false
false
genedelisa/AVFoundationRecorder
refs/heads/master
AVFoundation Recorder/RecorderViewController.swift
mit
1
// // RecorderViewController.swift // SwiftAVFound // // Created by Gene De Lisa on 8/11/14. // Copyright (c) 2014 Gene De Lisa. All rights reserved. // import UIKit import AVFoundation // swiftlint:disable file_length // swiftlint:disable type_body_length /** Uses AVAudioRecorder to record a sound file and an AVAudioPlayer to play it back. - Author: Gene De Lisa */ class RecorderViewController: UIViewController { var recorder: AVAudioRecorder! var player: AVAudioPlayer! @IBOutlet var recordButton: UIButton! @IBOutlet var stopButton: UIButton! @IBOutlet var playButton: UIButton! @IBOutlet var statusLabel: UILabel! var meterTimer: Timer! var soundFileURL: URL! override func viewDidLoad() { super.viewDidLoad() stopButton.isEnabled = false playButton.isEnabled = false setSessionPlayback() askForNotifications() checkHeadphones() } @objc func updateAudioMeter(_ timer: Timer) { if let recorder = self.recorder { if recorder.isRecording { let min = Int(recorder.currentTime / 60) let sec = Int(recorder.currentTime.truncatingRemainder(dividingBy: 60)) let s = String(format: "%02d:%02d", min, sec) statusLabel.text = s recorder.updateMeters() // if you want to draw some graphics... //var apc0 = recorder.averagePowerForChannel(0) //var peak0 = recorder.peakPowerForChannel(0) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() recorder = nil player = nil } @IBAction func removeAll(_ sender: AnyObject) { deleteAllRecordings() } @IBAction func record(_ sender: UIButton) { print("\(#function)") if player != nil && player.isPlaying { print("stopping") player.stop() } if recorder == nil { print("recording. recorder nil") recordButton.setTitle("Pause", for: .normal) playButton.isEnabled = false stopButton.isEnabled = true recordWithPermission(true) return } if recorder != nil && recorder.isRecording { print("pausing") recorder.pause() recordButton.setTitle("Continue", for: .normal) } else { print("recording") recordButton.setTitle("Pause", for: .normal) playButton.isEnabled = false stopButton.isEnabled = true // recorder.record() recordWithPermission(false) } } @IBAction func stop(_ sender: UIButton) { print("\(#function)") recorder?.stop() player?.stop() meterTimer.invalidate() recordButton.setTitle("Record", for: .normal) let session = AVAudioSession.sharedInstance() do { try session.setActive(false) playButton.isEnabled = true stopButton.isEnabled = false recordButton.isEnabled = true } catch { print("could not make session inactive") print(error.localizedDescription) } //recorder = nil } @IBAction func play(_ sender: UIButton) { print("\(#function)") play() } func play() { print("\(#function)") var url: URL? if self.recorder != nil { url = self.recorder.url } else { url = self.soundFileURL! } print("playing \(String(describing: url))") do { self.player = try AVAudioPlayer(contentsOf: url!) stopButton.isEnabled = true player.delegate = self player.prepareToPlay() player.volume = 1.0 player.play() } catch { self.player = nil print(error.localizedDescription) } } func setupRecorder() { print("\(#function)") let format = DateFormatter() format.dateFormat="yyyy-MM-dd-HH-mm-ss" let currentFileName = "recording-\(format.string(from: Date())).m4a" print(currentFileName) let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] self.soundFileURL = documentsDirectory.appendingPathComponent(currentFileName) print("writing to soundfile url: '\(soundFileURL!)'") if FileManager.default.fileExists(atPath: soundFileURL.absoluteString) { // probably won't happen. want to do something about it? print("soundfile \(soundFileURL.absoluteString) exists") } let recordSettings: [String: Any] = [ AVFormatIDKey: kAudioFormatAppleLossless, AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue, AVEncoderBitRateKey: 32000, AVNumberOfChannelsKey: 2, AVSampleRateKey: 44100.0 ] do { recorder = try AVAudioRecorder(url: soundFileURL, settings: recordSettings) recorder.delegate = self recorder.isMeteringEnabled = true recorder.prepareToRecord() // creates/overwrites the file at soundFileURL } catch { recorder = nil print(error.localizedDescription) } } func recordWithPermission(_ setup: Bool) { print("\(#function)") AVAudioSession.sharedInstance().requestRecordPermission { [unowned self] granted in if granted { DispatchQueue.main.async { print("Permission to record granted") self.setSessionPlayAndRecord() if setup { self.setupRecorder() } self.recorder.record() self.meterTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.updateAudioMeter(_:)), userInfo: nil, repeats: true) } } else { print("Permission to record not granted") } } if AVAudioSession.sharedInstance().recordPermission() == .denied { print("permission denied") } } func setSessionPlayback() { print("\(#function)") let session = AVAudioSession.sharedInstance() do { try session.setCategory(AVAudioSessionCategoryPlayback, with: .defaultToSpeaker) } catch { print("could not set session category") print(error.localizedDescription) } do { try session.setActive(true) } catch { print("could not make session active") print(error.localizedDescription) } } func setSessionPlayAndRecord() { print("\(#function)") let session = AVAudioSession.sharedInstance() do { try session.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker) } catch { print("could not set session category") print(error.localizedDescription) } do { try session.setActive(true) } catch { print("could not make session active") print(error.localizedDescription) } } func deleteAllRecordings() { print("\(#function)") let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let fileManager = FileManager.default do { let files = try fileManager.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) // let files = try fileManager.contentsOfDirectory(at: documentsDirectory) var recordings = files.filter({ (name: URL) -> Bool in return name.pathExtension == "m4a" // return name.hasSuffix("m4a") }) for i in 0 ..< recordings.count { // let path = documentsDirectory.appendPathComponent(recordings[i], inDirectory: true) // let path = docsDir + "/" + recordings[i] // print("removing \(path)") print("removing \(recordings[i])") do { try fileManager.removeItem(at: recordings[i]) } catch { print("could not remove \(recordings[i])") print(error.localizedDescription) } } } catch { print("could not get contents of directory at \(documentsDirectory)") print(error.localizedDescription) } } func askForNotifications() { print("\(#function)") NotificationCenter.default.addObserver(self, selector: #selector(RecorderViewController.background(_:)), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(RecorderViewController.foreground(_:)), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(RecorderViewController.routeChange(_:)), name: NSNotification.Name.AVAudioSessionRouteChange, object: nil) } @objc func background(_ notification: Notification) { print("\(#function)") } @objc func foreground(_ notification: Notification) { print("\(#function)") } @objc func routeChange(_ notification: Notification) { print("\(#function)") if let userInfo = (notification as NSNotification).userInfo { print("routeChange \(userInfo)") //print("userInfo \(userInfo)") if let reason = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt { //print("reason \(reason)") switch AVAudioSessionRouteChangeReason(rawValue: reason)! { case AVAudioSessionRouteChangeReason.newDeviceAvailable: print("NewDeviceAvailable") print("did you plug in headphones?") checkHeadphones() case AVAudioSessionRouteChangeReason.oldDeviceUnavailable: print("OldDeviceUnavailable") print("did you unplug headphones?") checkHeadphones() case AVAudioSessionRouteChangeReason.categoryChange: print("CategoryChange") case AVAudioSessionRouteChangeReason.override: print("Override") case AVAudioSessionRouteChangeReason.wakeFromSleep: print("WakeFromSleep") case AVAudioSessionRouteChangeReason.unknown: print("Unknown") case AVAudioSessionRouteChangeReason.noSuitableRouteForCategory: print("NoSuitableRouteForCategory") case AVAudioSessionRouteChangeReason.routeConfigurationChange: print("RouteConfigurationChange") } } } // this cast fails. that's why I do that goofy thing above. // if let reason = userInfo[AVAudioSessionRouteChangeReasonKey] as? AVAudioSessionRouteChangeReason { // } /* AVAudioSessionRouteChangeReasonUnknown = 0, AVAudioSessionRouteChangeReasonNewDeviceAvailable = 1, AVAudioSessionRouteChangeReasonOldDeviceUnavailable = 2, AVAudioSessionRouteChangeReasonCategoryChange = 3, AVAudioSessionRouteChangeReasonOverride = 4, AVAudioSessionRouteChangeReasonWakeFromSleep = 6, AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory = 7, AVAudioSessionRouteChangeReasonRouteConfigurationChange NS_ENUM_AVAILABLE_IOS(7_0) = 8 routeChange Optional([AVAudioSessionRouteChangeReasonKey: 1, AVAudioSessionRouteChangePreviousRouteKey: <AVAudioSessionRouteDescription: 0x17557350, inputs = ( "<AVAudioSessionPortDescription: 0x17557760, type = MicrophoneBuiltIn; name = iPhone Microphone; UID = Built-In Microphone; selectedDataSource = Bottom>" ); outputs = ( "<AVAudioSessionPortDescription: 0x17557f20, type = Speaker; name = Speaker; UID = Built-In Speaker; selectedDataSource = (null)>" )>]) routeChange Optional([AVAudioSessionRouteChangeReasonKey: 2, AVAudioSessionRouteChangePreviousRouteKey: <AVAudioSessionRouteDescription: 0x175562f0, inputs = ( "<AVAudioSessionPortDescription: 0x1750c560, type = MicrophoneBuiltIn; name = iPhone Microphone; UID = Built-In Microphone; selectedDataSource = Bottom>" ); outputs = ( "<AVAudioSessionPortDescription: 0x17557de0, type = Headphones; name = Headphones; UID = Wired Headphones; selectedDataSource = (null)>" )>]) */ } func checkHeadphones() { print("\(#function)") // check NewDeviceAvailable and OldDeviceUnavailable for them being plugged in/unplugged let currentRoute = AVAudioSession.sharedInstance().currentRoute if !currentRoute.outputs.isEmpty { for description in currentRoute.outputs { if description.portType == AVAudioSessionPortHeadphones { print("headphones are plugged in") break } else { print("headphones are unplugged") } } } else { print("checking headphones requires a connection to a device") } } @IBAction func trim() { print("\(#function)") if self.soundFileURL == nil { print("no sound file") return } print("trimming \(soundFileURL!.absoluteString)") print("trimming path \(soundFileURL!.lastPathComponent)") let asset = AVAsset(url: self.soundFileURL!) exportAsset(asset, fileName: "trimmed.m4a") } func exportAsset(_ asset: AVAsset, fileName: String) { print("\(#function)") let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let trimmedSoundFileURL = documentsDirectory.appendingPathComponent(fileName) print("saving to \(trimmedSoundFileURL.absoluteString)") if FileManager.default.fileExists(atPath: trimmedSoundFileURL.absoluteString) { print("sound exists, removing \(trimmedSoundFileURL.absoluteString)") do { if try trimmedSoundFileURL.checkResourceIsReachable() { print("is reachable") } try FileManager.default.removeItem(atPath: trimmedSoundFileURL.absoluteString) } catch { print("could not remove \(trimmedSoundFileURL)") print(error.localizedDescription) } } print("creating export session for \(asset)") if let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) { exporter.outputFileType = AVFileType.m4a exporter.outputURL = trimmedSoundFileURL let duration = CMTimeGetSeconds(asset.duration) if duration < 5.0 { print("sound is not long enough") return } // e.g. the first 5 seconds let startTime = CMTimeMake(0, 1) let stopTime = CMTimeMake(5, 1) exporter.timeRange = CMTimeRangeFromTimeToTime(startTime, stopTime) // // set up the audio mix // let tracks = asset.tracksWithMediaType(AVMediaTypeAudio) // if tracks.count == 0 { // return // } // let track = tracks[0] // let exportAudioMix = AVMutableAudioMix() // let exportAudioMixInputParameters = // AVMutableAudioMixInputParameters(track: track) // exportAudioMixInputParameters.setVolume(1.0, atTime: CMTimeMake(0, 1)) // exportAudioMix.inputParameters = [exportAudioMixInputParameters] // // exporter.audioMix = exportAudioMix // do it exporter.exportAsynchronously(completionHandler: { print("export complete \(exporter.status)") switch exporter.status { case AVAssetExportSessionStatus.failed: if let e = exporter.error { print("export failed \(e)") } case AVAssetExportSessionStatus.cancelled: print("export cancelled \(String(describing: exporter.error))") default: print("export complete") } }) } else { print("cannot create AVAssetExportSession for asset \(asset)") } } @IBAction func speed() { let asset = AVAsset(url: self.soundFileURL!) exportSpeedAsset(asset, fileName: "trimmed.m4a") } func exportSpeedAsset(_ asset: AVAsset, fileName: String) { let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let trimmedSoundFileURL = documentsDirectory.appendingPathComponent(fileName) let filemanager = FileManager.default if filemanager.fileExists(atPath: trimmedSoundFileURL.absoluteString) { print("sound exists") } print("creating export session for \(asset)") if let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) { exporter.outputFileType = AVFileType.m4a exporter.outputURL = trimmedSoundFileURL // AVAudioTimePitchAlgorithmVarispeed // AVAudioTimePitchAlgorithmSpectral // AVAudioTimePitchAlgorithmTimeDomain exporter.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithm.varispeed let duration = CMTimeGetSeconds(asset.duration) if duration < 5.0 { print("sound is not long enough") return } // e.g. the first 5 seconds // let startTime = CMTimeMake(0, 1) // let stopTime = CMTimeMake(5, 1) // let exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime) // exporter.timeRange = exportTimeRange // do it exporter.exportAsynchronously(completionHandler: { switch exporter.status { case AVAssetExportSessionStatus.failed: print("export failed \(String(describing: exporter.error))") case AVAssetExportSessionStatus.cancelled: print("export cancelled \(String(describing: exporter.error))") default: print("export complete") } }) } } } // MARK: AVAudioRecorderDelegate extension RecorderViewController: AVAudioRecorderDelegate { func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { print("\(#function)") print("finished recording \(flag)") stopButton.isEnabled = false playButton.isEnabled = true recordButton.setTitle("Record", for: UIControlState()) // iOS8 and later let alert = UIAlertController(title: "Recorder", message: "Finished Recording", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Keep", style: .default) {[unowned self] _ in print("keep was tapped") self.recorder = nil }) alert.addAction(UIAlertAction(title: "Delete", style: .default) {[unowned self] _ in print("delete was tapped") self.recorder.deleteRecording() }) self.present(alert, animated: true, completion: nil) } func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) { print("\(#function)") if let e = error { print("\(e.localizedDescription)") } } } // MARK: AVAudioPlayerDelegate extension RecorderViewController: AVAudioPlayerDelegate { func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { print("\(#function)") print("finished playing \(flag)") recordButton.isEnabled = true stopButton.isEnabled = false } func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) { print("\(#function)") if let e = error { print("\(e.localizedDescription)") } } }
36a069e3af78ded720fefe0040acfe22
35.563981
162
0.538777
false
false
false
false
jpush/jchat-swift
refs/heads/master
JChat/Src/Utilites/3rdParty/RecordVoice/JCAudioPlayerHelper.swift
mit
1
// // JCAudioPlayerHelper.swift // JChatSwift // // Created by oshumini on 16/2/26. // Copyright © 2016年 HXHG. All rights reserved. // import UIKit import AVFoundation protocol JCAudioPlayerHelperDelegate: NSObjectProtocol { func didAudioPlayerBeginPlay(_ AudioPlayer: AVAudioPlayer) func didAudioPlayerStopPlay(_ AudioPlayer: AVAudioPlayer) func didAudioPlayerPausePlay(_ AudioPlayer: AVAudioPlayer) } final class JCAudioPlayerHelper: NSObject { var player: AVAudioPlayer! weak var delegate: JCAudioPlayerHelperDelegate? static let sharedInstance = JCAudioPlayerHelper() private override init() { super.init() } func managerAudioWithData(_ data:Data, toplay:Bool) { if toplay { playAudioWithData(data) } else { pausePlayingAudio() } } func playAudioWithData(_ voiceData:Data) { do { //AVAudioSessionCategoryPlayback if #available(iOS 10.0, *) { try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: AVAudioSession.CategoryOptions.defaultToSpeaker) } else { // Fallback on earlier versions } } catch let error as NSError { print("set category fail \(error)") } if player != nil { player.stop() player = nil } do { let pl: AVAudioPlayer = try AVAudioPlayer(data: voiceData) pl.delegate = self pl.play() player = pl } catch let error as NSError { print("alloc AVAudioPlayer with voice data fail with error \(error)") } UIDevice.current.isProximityMonitoringEnabled = true } func pausePlayingAudio() { player?.pause() } func stopAudio() { if player != nil && player.isPlaying { player.stop() } UIDevice.current.isProximityMonitoringEnabled = false delegate?.didAudioPlayerStopPlay(player) } } extension JCAudioPlayerHelper: AVAudioPlayerDelegate { func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { stopAudio() } }
2eb9712db6afe44952c74088686e8acd
26.951807
190
0.613362
false
false
false
false
startupthekid/CoordinatorKit
refs/heads/develop
CoordinatorKit/Core/NavigationCoordinator.swift
mit
1
// // NavigationCoordinator.swift // CoordinatorKit // // Created by Brendan Conron on 8/9/17. // Copyright © 2017 Brendan Conron. All rights reserved. // import UIKit import Foundation public final class NavigationCoordinator: SceneCoordinator<UINavigationController>, UIGestureRecognizerDelegate, UINavigationControllerDelegate { // MARK: - Coordinators private(set) public var rootCoordinator: Coordinator? // MARK: - Navigation State private var coordinatorStack: Stack<Coordinator> = Stack() private var controllerStack: Stack<UIViewController> = Stack() // MARK: - Initialization required public init<C>(rootCoordinator: SceneCoordinator<C>) { self.rootCoordinator = rootCoordinator super.init() rootViewController = UINavigationController(rootViewController: rootCoordinator.rootViewController) coordinatorStack.push(rootCoordinator) controllerStack.push(rootCoordinator.rootViewController) configure() } required public init() { rootCoordinator = nil super.init() rootViewController = UINavigationController() configure() } // MARK: - Configuration private func configure() { rootViewController.delegate = self rootViewController.interactivePopGestureRecognizer?.delegate = self rootViewController.view.backgroundColor = .clear rootViewController.automaticallyAdjustsScrollViewInsets = false } /// Set the root coordinator on the navigation coordinator. This can only be used if the /// the root coordinator wasn't set via the initializer already. /// /// - Parameter coordinator: Root coordinator object. public final func setRootCoordinator<C>(_ coordinator: SceneCoordinator<C>) { guard coordinatorStack.isEmpty, controllerStack.isEmpty, rootCoordinator == nil else { return } rootCoordinator = coordinator rootViewController.pushViewController(coordinator.rootViewController, animated: false) coordinatorStack.push(coordinator) controllerStack.push(coordinator.rootViewController) } /// Push a coordinator onto the navigation coordinator. /// /// - Parameters: /// - coordinator: Coordinator to push. /// - animated: Should the push be animated. public func pushCoordinator<C>(coordinator: SceneCoordinator<C>, animated: Bool = true) { if let topCoordinator = coordinatorStack.peek() { pause(coordinator: topCoordinator) } start(sceneCoordinator: coordinator) coordinatorStack.push(coordinator) controllerStack.push(coordinator.rootViewController) } /// Pop a coordinator off the navigation stack. /// /// - Parameter animated: Should the pop be animated. public func popCoordinator(animated: Bool = true) { guard let coordinator = coordinatorStack.peek() as? SceneCoordinator, rootCoordinator != coordinator else { return } stop(sceneCoordinator: coordinator) coordinatorStack.pop() controllerStack.pop() guard let topCoordinator = coordinatorStack.peek(), topCoordinator.isPaused else { return } resume(coordinator: topCoordinator) } /// Hide or show the navigation bar. /// /// - Parameters: /// - hidden: Should the bar be hidden or shown. /// - animated: Should the tranisition be animated. func setNavigationBar(hidden: Bool, animated: Bool = false) { rootViewController.setNavigationBarHidden(hidden, animated: animated) } // MARK: - Coordinator override public func start() { super.start() guard let root = rootCoordinator else { return } start(coordinator: root) } override public func stop() { super.stop() coordinatorStack.removeAll() controllerStack.removeAll() rootCoordinator = nil } override public func coordinatorDidRequestDismissal<C>(_ coordinator: SceneCoordinator<C>) { // If the root coordinator is requesting dismisal, we request dismissal from our parent if coordinator === rootCoordinator { delegate => { if let delegate = $0 as? SceneCoordinatorDelegate { delegate.coordinatorDidRequestDismissal(self) } } } else { popCoordinator(animated: true) } } // MARK: - UINavigationControllerDelegate public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { // While the view controller that was just shown does not equal the one on the top of the stack // go through the stack until you find it while controllerStack.peek() != viewController { guard let coordinator = coordinatorStack.peek() else { break } stop(coordinator: coordinator) controllerStack.pop() coordinatorStack.pop() if let topCoordinator = coordinatorStack.peek(), controllerStack.peek() == viewController, topCoordinator.isPaused { resume(coordinator: topCoordinator) break } } } // MARK: - UIGestureRecognizerDelegate public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { // Necessary to get the child navigation controller’s interactive pop gesture recognizer to work. return true } }
1a364f0d4da096456f777895d7dea875
36.686275
145
0.66129
false
false
false
false
firebase/firebase-ios-sdk
refs/heads/master
ReleaseTooling/Sources/Utils/String+Utils.swift
apache-2.0
1
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 /// Utilities to simplify String operations. public extension String { /// Finds and returns the ranges of all occurrences of a given string within a given range of the String, subject to given options, /// using the specified locale, if any. /// - Returns: An an optional array of ranges where each range corresponds to an occurence of the substring in the given string. func ranges<T: StringProtocol>(of substring: T, options: CompareOptions = .literal, locale: Locale? = nil) -> [Range<Index>] { var ranges: [Range<Index>] = [] let end = endIndex var searchRange = startIndex ..< end while searchRange.lowerBound < end { guard let range = range( of: substring, options: options, range: searchRange, locale: locale ) else { break } ranges.append(range) let shiftedStart = index(range.lowerBound, offsetBy: 1) searchRange = shiftedStart ..< end } return ranges } }
b77228714968e8470989fd523a8ca88b
32.770833
133
0.677977
false
false
false
false
badoo/Chatto
refs/heads/master
ChattoAdditions/sources/Input/Photos/Photo/PhotosInputCell.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. 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 final class PhotosInputCell: UICollectionViewCell { private struct Constants { static let backgroundColor = UIColor(red: 231.0/255.0, green: 236.0/255.0, blue: 242.0/255.0, alpha: 1) static let loadingIndicatorBackgoroundColor = UIColor.black.withAlphaComponent(0.70) static let loadingIndicatorProgressColor = UIColor.white static let loadingIncicatorProgressWidth: CGFloat = 1 static let accessibilityIdentifier = "chatto.inputbar.photos.cell.photo" } override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } private var imageView: UIImageView! private func commonInit() { self.clipsToBounds = true self.imageView = UIImageView() self.imageView.contentMode = .scaleAspectFill self.contentView.addSubview(self.imageView) self.contentView.backgroundColor = Constants.backgroundColor self.accessibilityIdentifier = Constants.accessibilityIdentifier } override func layoutSubviews() { super.layoutSubviews() self.imageView.frame = self.bounds } override func prepareForReuse() { super.prepareForReuse() self.image = nil self.hideProgressView() } var image: UIImage? { get { return self.imageView.image } set { self.imageView.image = newValue } } // MARK: - Progress indicator - fileprivate var progressView: CircleProgressIndicatorView? func showProgressView() { guard self.progressView == nil else { return } let progressIndicator = CircleProgressIndicatorView.default() progressIndicator.progressLineColor = Constants.loadingIndicatorProgressColor progressIndicator.progressLineWidth = Constants.loadingIncicatorProgressWidth progressIndicator.backgroundColor = Constants.loadingIndicatorBackgoroundColor progressIndicator.translatesAutoresizingMaskIntoConstraints = false self.addSubview(progressIndicator) self.addConstraint(NSLayoutConstraint(item: progressIndicator, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: progressIndicator, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: progressIndicator, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: progressIndicator, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)) self.progressView = progressIndicator } func updateProgress(_ progress: CGFloat) { self.progressView?.setProgress(progress) } func hideProgressView() { self.progressView?.removeFromSuperview() self.progressView = nil } }
1bfe66f9354bb73f50c63e9efe1b8b5f
40.475728
176
0.722144
false
false
false
false
8bytes/drift-sdk-ios
refs/heads/master
Drift/Birdsong/Presence.swift
mit
2
// // Presence.swift // Pods // // Created by Simon Manning on 6/07/2016. // // import Foundation internal final class Presence { // MARK: - Convenience typealiases public typealias PresenceState = [String: [Meta]] public typealias Diff = [String: [String: Any]] public typealias Meta = [String: Any] // MARK: - Properties fileprivate(set) public var state: PresenceState // MARK: - Callbacks public var onJoin: ((_ id: String, _ meta: Meta) -> ())? public var onLeave: ((_ id: String, _ meta: Meta) -> ())? public var onStateChange: ((_ state: PresenceState) -> ())? // MARK: - Initialisation init(state: PresenceState = Presence.PresenceState()) { self.state = state } // MARK: - Syncing func sync(_ diff: Response) { // Initial state event if diff.event == "presence_state" { diff.payload.forEach{ id, entry in if let entry = entry as? [String: Any] { if let metas = entry["metas"] as? [Meta] { state[id] = metas } } } } else if diff.event == "presence_diff" { if let leaves = diff.payload["leaves"] as? Diff { syncLeaves(leaves) } if let joins = diff.payload["joins"] as? Diff { syncJoins(joins) } } onStateChange?(state) } func syncLeaves(_ diff: Diff) { defer { diff.forEach { id, entry in if let metas = entry["metas"] as? [Meta] { metas.forEach { onLeave?(id, $0) } } } } for (id, entry) in diff where state[id] != nil { guard var existing = state[id] else { continue } // If there's only one entry for the id, just remove it. if existing.count == 1 { state.removeValue(forKey: id) continue } // Otherwise, we need to find the phx_ref keys to delete. let metas = entry["metas"] as? [Meta] if let refsToDelete = metas?.compactMap({ $0["phx_ref"] as? String }) { existing = existing.filter { if let phxRef = $0["phx_ref"] as? String { return !refsToDelete.contains(phxRef) } return true } state[id] = existing } } } func syncJoins(_ diff: Diff) { diff.forEach { id, entry in if let metas = entry["metas"] as? [Meta] { if var existing = state[id] { existing += metas } else { state[id] = metas } metas.forEach { onJoin?(id, $0) } } } } // MARK: - Presence access convenience func metas(id: String) -> [Meta]? { return state[id] } func firstMeta(id: String) -> Meta? { return state[id]?.first } func firstMetas() -> [String: Meta] { var result = [String: Meta]() state.forEach { id, metas in result[id] = metas.first } return result } func firstMetaValue<T>(id: String, key: String) -> T? { guard let meta = state[id]?.first, let value = meta[key] as? T else { return nil } return value } func firstMetaValues<T>(key: String) -> [T] { var result = [T]() state.forEach { id, metas in if let meta = metas.first, let value = meta[key] as? T { result.append(value) } } return result } }
0d1a9027d5cbc2d86bba9dbba12da415
25.424658
83
0.466304
false
false
false
false
iOSWizards/AwesomeMedia
refs/heads/master
Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/QuestSeries.swift
mit
1
// // SoulvanaSeries.swift // Pods // // Created by Evandro Harrison Hoffmann on 7/23/18. // import Foundation public struct QuestSeries : Codable, Equatable { public let id: String? public let coverAsset: QuestAsset? public let media: [QuestMedia]? public let favouriteMedia: [QuestMedia]? public let featuredMedia: [QuestMedia]? public let latestMedia: [QuestMedia]? public let publishedAt: String? public let slug: String? public let subtitle: String? public let title: String? public let authors: [QuestAuthor]? } // MARK: - JSON Key public struct SingleQuestSeriesDataKey: Codable { public let data: SingleQuestSeriesKey } public struct SingleQuestSeriesKey: Codable { public let series: QuestSeries } // MARK: - Equatable extension QuestSeries { static public func ==(lhs: QuestSeries, rhs: QuestSeries) -> Bool { if lhs.id != rhs.id { return false } if lhs.coverAsset != rhs.coverAsset { return false } if lhs.title != rhs.title { return false } if lhs.subtitle != rhs.subtitle { return false } if lhs.publishedAt != rhs.publishedAt { return false } if lhs.slug != rhs.slug { return false } if lhs.media != rhs.media { return false } if lhs.authors != rhs.authors { return false } return true } }
9371a335f914f95e132edf0309ab00e1
20.30137
71
0.576206
false
false
false
false
nkirby/Humber
refs/heads/master
_lib/HMGithub/_src/Realm/GithubUser.swift
mit
1
// ======================================================= // HMGithub // Nathaniel Kirby // ======================================================= import Foundation import RealmSwift // ======================================================= public class GithubUser: Object { public dynamic var login = "" public dynamic var userID = "" public dynamic var url = "" public dynamic var type = "" public dynamic var siteAdmin = false public override class func primaryKey() -> String { return "userID" } }
275e7bbc562bca6ee4fcd009725383b4
24.952381
58
0.447706
false
false
false
false
blinksh/blink
refs/heads/raw
Blink/CompleteUtils.swift
gpl-3.0
1
////////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2019 Blink Mobile Shell Project // // This file is part of Blink. // // Blink is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Blink is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import Foundation struct CompleteToken { var value: String = "" var quote: String.Element? = nil var isRedirect: Bool = false var prefix: String = "" // unquaoted query var query: String = "" // if cmd is detected var cmd: String? = nil var jsStart: Int = 0 var jsPos: Int = 0 var jsLen: Int = 0 var canShowHint: Bool = false } struct CompleteUtils { static func encode(str: String, quote: String.Element? = nil) -> String { var result = str result = result.replacingOccurrences(of: "\\", with: "\\\\") result = result.replacingOccurrences(of: "|", with: "\\|") guard let quote = quote else { result = result.replacingOccurrences(of: " ", with: "\\ ") return result } let q = String(quote) result = result.replacingOccurrences(of: q, with: "\\" + q) result = "\(q)\(result)\(q)" return result } static func completeToken(_ input: String, cursor: Int) -> CompleteToken { if input.isEmpty { return CompleteToken() } let buf = Array(input) let len = buf.count let cursor = max(min(cursor, len), 0) var start = 0; var end = 0; var i = 0; var qch: String.Element? = nil let quotes = "\"'" var bs = 0 var isRedirect = false var pos = 0 while i < cursor { defer { i += 1 } let ch = buf[i] if ch == "\\" { bs += 1 continue } defer { bs = 0 } if ch.isWhitespace && bs % 2 == 0 { pos = i continue } if ch == "|" && bs % 2 == 0 { start = i pos = i isRedirect = false continue } if ch == ">" && bs % 2 == 0 { start = i pos = i isRedirect = true continue } for quote in quotes { if ch == quote && bs % 2 == 0 { qch = quote i += 1 while i < cursor { defer { i += 1 } let c = buf[i] if c == "\\" { bs += 1 continue } defer { bs = 0 } if c == quote && bs % 2 == 0 { qch = nil break } } break } } } i = cursor while i < len { let ch = buf[i] if ch == "\\" { bs += 1 i += 1 continue } defer { bs = 0 } // we are inside quotes if let quote = qch { if ch == quote && bs % 2 == 0 { i += 1 break } } else if (ch.isWhitespace || ch == "|" || ch == ">") && bs % 2 == 0 { break } i += 1 } end = i while start < end { let ch = buf[start] if ch == " " || ch == "|" || ch == ">" { start += 1 continue } break } if start > pos { pos = start } while pos < cursor { let ch = buf[pos] if ch.isWhitespace { pos += 1 } else { break } } let range = input.index(input.startIndex, offsetBy: start)..<input.index(input.startIndex, offsetBy: end) let canShowHint = range.upperBound == input.endIndex // if pos >= len { // pos = len - 1 // } // // if start >= len { // start = len - 1 // } var cmd: String? var prefix: String var query = (cursor == 0 || pos >= len) ? "" : String(buf[pos..<cursor]) query = query.replacingOccurrences(of: "\\\\", with: "\\") if let q = qch { let qq = String(q) query = query.replacingOccurrences(of: "\\" + qq, with: qq) query.removeFirst() } else { query = query.replacingOccurrences(of: "\\ ", with: " ") if query.first == "\"" && query.last == "\"" { if query == "\"" { query = "" } else { query = query.replacingOccurrences(of: "\\\"", with: "\"") query.removeFirst() query.removeLast() } qch = Character("\"") } else if query.first == "'" && query.last == "'" { if query == "'" { query = "" } else { query = query.replacingOccurrences(of: "\\\'", with: "'") query.removeFirst() query.removeLast() } qch = Character("'") } } if pos == start || pos > len { cmd = nil prefix = "" } else { prefix = String(buf[start..<pos]) if let cmdPart = prefix.split(separator: " ", maxSplits: 1, omittingEmptySubsequences: true).first { cmd = String(cmdPart) } } let jsStart = input.index(input.startIndex, offsetBy: start).utf16Offset(in: input) let jsPos = input.index(input.startIndex, offsetBy: pos).utf16Offset(in: input) let jsEnd = input.index(input.startIndex, offsetBy: end).utf16Offset(in: input) return CompleteToken( value: String(input[range]), quote: qch, isRedirect: isRedirect, prefix: prefix, query: query, cmd: cmd, jsStart: jsStart, jsPos: jsPos, jsLen: jsEnd - jsPos, canShowHint: canShowHint ) } }
ee07fb45fbef776b78d3bc27deb01309
22.789855
109
0.490405
false
false
false
false
slavapestov/swift
refs/heads/master
test/SILGen/toplevel.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s func markUsed<T>(t: T) {} @noreturn func trap() { fatalError() } // CHECK-LABEL: sil @main // CHECK: bb0({{%.*}} : $Int32, {{%.*}} : $UnsafeMutablePointer<UnsafeMutablePointer<Int8>>): // -- initialize x // CHECK: alloc_global @_Tv8toplevel1xSi // CHECK: [[X:%[0-9]+]] = global_addr @_Tv8toplevel1xSi : $*Int // CHECK: integer_literal $Builtin.Int2048, 999 // CHECK: store {{.*}} to [[X]] var x = 999 func print_x() { markUsed(x) } // -- assign x // CHECK: integer_literal $Builtin.Int2048, 0 // CHECK: assign {{.*}} to [[X]] // CHECK: [[PRINT_X:%[0-9]+]] = function_ref @_TF8toplevel7print_xFT_T_ : // CHECK: apply [[PRINT_X]] x = 0 print_x() // <rdar://problem/19770775> Deferred initialization of let bindings rejected at top level in playground // CHECK: alloc_global @_Tv8toplevel5countSi // CHECK: [[COUNTADDR:%[0-9]+]] = global_addr @_Tv8toplevel5countSi : $*Int // CHECK-NEXT: [[COUNTMUI:%[0-9]+]] = mark_uninitialized [var] [[COUNTADDR]] : $*Int let count: Int // CHECK: cond_br if x == 5 { count = 0 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE:bb[0-9]+]] } else { count = 10 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE]] } // CHECK: [[MERGE]]: // CHECK: load [[COUNTMUI]] markUsed(count) var y : Int func print_y() { markUsed(y) } // -- assign y // CHECK: alloc_global @_Tv8toplevel1ySi // CHECK: [[Y1:%[0-9]+]] = global_addr @_Tv8toplevel1ySi : $*Int // CHECK: [[Y:%[0-9]+]] = mark_uninitialized [var] [[Y1]] // CHECK: assign {{.*}} to [[Y]] // CHECK: [[PRINT_Y:%[0-9]+]] = function_ref @_TF8toplevel7print_yFT_T_ y = 1 print_y() // -- treat 'guard' vars as locals // CHECK-LABEL: function_ref toplevel.A.__allocating_init // CHECK: switch_enum {{%.+}} : $Optional<A>, case #Optional.Some!enumelt.1: [[SOME_CASE:.+]], default // CHECK: [[SOME_CASE]]([[VALUE:%.+]] : $A): // CHECK: store [[VALUE]] to [[BOX:%.+]] : $*A // CHECK-NOT: release // CHECK: [[SINK:%.+]] = function_ref @_TF8toplevel8markUsedurFxT_ // CHECK-NOT: release // CHECK: apply [[SINK]]<A>({{%.+}}) class A {} guard var a = Optional(A()) else { trap() } markUsed(a) // CHECK: alloc_global @_Tv8toplevel21NotInitializedIntegerSi // CHECK-NEXT: [[VARADDR:%[0-9]+]] = global_addr @_Tv8toplevel21NotInitializedIntegerSi // CHECK-NEXT: [[VARMUI:%[0-9]+]] = mark_uninitialized [var] [[VARADDR]] : $*Int // CHECK-NEXT: mark_function_escape [[VARMUI]] : $*Int // <rdar://problem/21753262> Bug in DI when it comes to initialization of global "let" variables let NotInitializedInteger : Int func fooUsesUninitializedValue() { _ = NotInitializedInteger } fooUsesUninitializedValue() NotInitializedInteger = 10 fooUsesUninitializedValue() // CHECK: [[RET:%[0-9]+]] = struct $Int32 // CHECK: return [[RET]] // CHECK-LABEL: sil hidden @_TF8toplevel7print_xFT_T_ // CHECK-LABEL: sil hidden @_TF8toplevel7print_yFT_T_ // CHECK: sil hidden @_TF8toplevel13testGlobalCSEFT_Si // CHECK-NOT: global_addr // CHECK: %0 = global_addr @_Tv8toplevel1xSi : $*Int // CHECK-NOT: global_addr // CHECK: return func testGlobalCSE() -> Int { // We should only emit one global_addr in this function. return x + x }
4454f4ece0e8e5f1e51e1b68ae0c131c
24.91129
104
0.633987
false
false
false
false
CLCreate/CLCDrag
refs/heads/master
DragComponent/DragComponent/DragComponent/BlockGestureRecognizer.swift
mit
1
// // BlockGestureRecognizer.swift // DragComponent // // Created by 陈龙 on 16/1/26. // Copyright © 2016年 陈 龙. All rights reserved. // import UIKit class BlockGestureRecognizer: UIGestureRecognizer { // declare typealias ActionBlock = () -> Void var grPossibleAction : ActionBlock? var grBeganAction : ActionBlock? var grChangeAction : ActionBlock? var grEndAction : ActionBlock? var grCancleAction : ActionBlock? var grFailedAction : ActionBlock? // MARK: - Lifecycle override init(target: AnyObject?, action: Selector) { super.init(target: target, action: action) } convenience init(possibleAction : ActionBlock, beganAction : ActionBlock, changeAction : ActionBlock, cancleAction : ActionBlock, endAction : ActionBlock, failedAction : ActionBlock){ self.init(possibleAction : possibleAction, beganAction : beganAction, changeAction : changeAction, cancleAction : cancleAction, endAction : endAction) grFailedAction = failedAction } convenience init (possibleAction : ActionBlock, beganAction : ActionBlock, changeAction : ActionBlock, cancleAction : ActionBlock, endAction : ActionBlock){ self.init(beganAction : beganAction, changeAction : changeAction, cancleAction : cancleAction, endAction : endAction) grPossibleAction = possibleAction } convenience init(beganAction : ActionBlock, changeAction : ActionBlock, cancleAction : ActionBlock, endAction : ActionBlock){ self.init(beganAction : beganAction, changeAction : changeAction, endAction : endAction) grCancleAction = cancleAction } convenience init(beganAction : ActionBlock, changeAction : ActionBlock, endAction : ActionBlock){ self.init() grBeganAction = beganAction grChangeAction = changeAction grEndAction = endAction } }
6d6ab244adb3a1ea8c8c2a2b20f0abf2
34.181818
187
0.695607
false
false
false
false
hovansuit/FoodAndFitness
refs/heads/master
FoodAndFitness/Model/Core/Mapper.swift
mit
1
// // Mapper.swift // FoodAndFitness // // Created by Mylo Ho on 4/5/17. // Copyright © 2017 SuHoVan. All rights reserved. // import Foundation import Alamofire import ObjectMapper import RealmSwift import RealmS import SwiftDate enum DataType: Int { case object case array } // generic type workaround @discardableResult private func ffmap<T: Object>(realm: RealmS, type: T.Type, json: JSObject) -> T? where T: Mappable { return realm.map(T.self, json: json) } // generic type workaround @discardableResult private func ffmap<T: Object>(realm: RealmS, type: T.Type, json: JSArray) -> [T] where T: Mappable { return realm.map(T.self, json: json) } extension Mapper where N: Object, N: Mappable { func map(result: Result<JSObject>, type: DataType, completion: Completion) { switch result { case .success(let json): guard let data = json["data"] else { completion(.failure(FFError.json)) return } var result: Result<JSObject> = .failure(FFError.json) switch type { case .object: if let js = data as? JSObject, js.keys.isNotEmpty { let realm: RealmS = RealmS() realm.write { ffmap(realm: realm, type: N.self, json: js) } result = .success(json) } case .array: if let js = data as? JSArray { let realm = RealmS() realm.write { ffmap(realm: realm, type: N.self, json: js) } result = .success(json) } } completion(result) case .failure(_): completion(result) } } } // MARK: Data Transform final class DataTransform { static let date = TransformOf<Date, String>(fromJSON: { (string: String?) -> Date? in return string?.toDate(format: .date).absoluteDate }, toJSON: { (date: Date?) -> String? in return date?.ffDate(format: .date).toString(format: .date) }) static let fullDate = TransformOf<Date, String>(fromJSON: { (string: String?) -> Date? in return string?.toDate(format: .full, region: Region.GMT()).absoluteDate }, toJSON: { (date: Date?) -> String? in return date?.ffDate(format: .full).toString(format: .full) }) static let dateTime = TransformOf<Date, String>(fromJSON: { (string: String?) -> Date? in return string?.toDate(format: .dateTime).absoluteDate }, toJSON: { (date: Date?) -> String? in return date?.ffDate(format: .dateTime).toString(format: .dateTime) }) }
ff824ad7ba079dc156a90d26c9648dcd
30.813953
100
0.567251
false
false
false
false
dduan/swift
refs/heads/master
test/IRGen/generic_casts.swift
apache-2.0
2
// RUN: rm -rf %t && mkdir %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | FileCheck %s // REQUIRES: CPU=x86_64 // FIXME: rdar://problem/19648117 Needs splitting objc parts out // XFAIL: linux import Foundation import gizmo // -- Protocol records for cast-to ObjC protocols // CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_ = private constant // CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section "__DATA,__objc_protolist,coalesced,no_dead_strip" // CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section "__DATA,__objc_protorefs,coalesced,no_dead_strip" // CHECK: @_PROTOCOL_NSRuncing = private constant // CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section "__DATA,__objc_protolist,coalesced,no_dead_strip" // CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section "__DATA,__objc_protorefs,coalesced,no_dead_strip" // CHECK: @_PROTOCOLS__TtC13generic_casts10ObjCClass2 = private constant { i64, [1 x i8*] } { // CHECK: i64 1, // CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto2_ // CHECK: } // CHECK: @_DATA__TtC13generic_casts10ObjCClass2 = private constant {{.*}} @_PROTOCOLS__TtC13generic_casts10ObjCClass2 // CHECK: @_PROTOCOL_PROTOCOLS__TtP13generic_casts10ObjCProto2_ = private constant { i64, [1 x i8*] } { // CHECK: i64 1, // CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_ // CHECK: } // CHECK: define hidden i64 @_TF13generic_casts8allToInt{{.*}}(%swift.opaque* noalias nocapture, %swift.type* %T) func allToInt<T>(x: T) -> Int { return x as! Int // CHECK: [[BUF:%.*]] = alloca [[BUFFER:.24 x i8.]], // CHECK: [[INT_TEMP:%.*]] = alloca %Si, // CHECK: [[TEMP:%.*]] = call %swift.opaque* {{.*}}([[BUFFER]]* [[BUF]], %swift.opaque* %0, %swift.type* %T) // CHECK: [[T0:%.*]] = bitcast %Si* [[INT_TEMP]] to %swift.opaque* // CHECK: call i1 @rt_swift_dynamicCast(%swift.opaque* [[T0]], %swift.opaque* [[TEMP]], %swift.type* %T, %swift.type* @_TMSi, i64 7) // CHECK: [[T0:%.*]] = getelementptr inbounds %Si, %Si* [[INT_TEMP]], i32 0, i32 0 // CHECK: [[INT_RESULT:%.*]] = load i64, i64* [[T0]], // CHECK: ret i64 [[INT_RESULT]] } // CHECK: define hidden void @_TF13generic_casts8intToAll{{.*}}(%swift.opaque* noalias nocapture sret, i64, %swift.type* %T) {{.*}} { func intToAll<T>(x: Int) -> T { // CHECK: [[INT_TEMP:%.*]] = alloca %Si, // CHECK: [[T0:%.*]] = getelementptr inbounds %Si, %Si* [[INT_TEMP]], i32 0, i32 0 // CHECK: store i64 %1, i64* [[T0]], // CHECK: [[T0:%.*]] = bitcast %Si* [[INT_TEMP]] to %swift.opaque* // CHECK: call i1 @rt_swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[T0]], %swift.type* @_TMSi, %swift.type* %T, i64 7) return x as! T } // CHECK: define hidden i64 @_TF13generic_casts8anyToInt{{.*}}(%"protocol<>"* noalias nocapture dereferenceable({{.*}})) func anyToInt(x: protocol<>) -> Int { return x as! Int } @objc protocol ObjCProto1 { static func forClass() static func forInstance() var prop: NSObject { get } } @objc protocol ObjCProto2 : ObjCProto1 {} @objc class ObjCClass {} // CHECK: define hidden %objc_object* @_TF13generic_casts9protoCast{{.*}}(%C13generic_casts9ObjCClass*) {{.*}} { func protoCast(x: ObjCClass) -> protocol<ObjCProto1, NSRuncing> { // CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_" // CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing" // CHECK: call %objc_object* @swift_dynamicCastObjCProtocolUnconditional(%objc_object* {{%.*}}, i64 2, i8** {{%.*}}) return x as! protocol<ObjCProto1, NSRuncing> } @objc class ObjCClass2 : NSObject, ObjCProto2 { class func forClass() {} class func forInstance() {} var prop: NSObject { return self } } // <rdar://problem/15313840> // Class existential to opaque archetype cast // CHECK: define hidden void @_TF13generic_casts33classExistentialToOpaqueArchetype{{.*}}(%swift.opaque* noalias nocapture sret, %objc_object*, %swift.type* %T) func classExistentialToOpaqueArchetype<T>(x: ObjCProto1) -> T { var x = x // CHECK: [[X:%.*]] = alloca %P13generic_casts10ObjCProto1_ // CHECK: [[LOCAL:%.*]] = alloca %P13generic_casts10ObjCProto1_ // CHECK: [[LOCAL_OPAQUE:%.*]] = bitcast %P13generic_casts10ObjCProto1_* [[LOCAL]] to %swift.opaque* // CHECK: [[PROTO_TYPE:%.*]] = call %swift.type* @_TMaP13generic_casts10ObjCProto1_() // CHECK: call i1 @rt_swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[LOCAL_OPAQUE]], %swift.type* [[PROTO_TYPE]], %swift.type* %T, i64 7) return x as! T }
e52124faab02d42819caadfcd5490705
49.20202
228
0.663581
false
false
false
false
AlliterativeAnimals/AAFoundation
refs/heads/master
AAFoundation/Extensions.swift
apache-2.0
1
// // Extensions.swift // Line Puzzle // // Created by David Godfrey on 04/01/2017. // Copyright © 2017 Alliterative Animals. All rights reserved. // import Foundation import UIKit public extension Comparable { /** * Ensures the returned value falls within the given bounds */ public func clamped(to bounds: ClosedRange<Self>) -> Self { return min(max(self, bounds.lowerBound), bounds.upperBound) } } public extension UIBezierPath { /** * Optimisation to only fill if required. * * Only fills if the path might be visible within the given CGRect */ public func fill(ifIntersectsWith rect: CGRect) { if self.bounds.intersects(rect) { self.fill() } } /** * Optimisation to only stroke if required. * * Only strokes if the path might be visible within the given CGRect */ public func stroke(ifIntersectsWith rect: CGRect) { if self.bounds.intersects(rect) { self.stroke() } } } public extension CGPoint { /** * Returns the location of this point after being moved by a vector * * - Parameter vector: to move the point by */ public func movedBy(vector: CGVector) -> CGPoint { return CGPoint(x: self.x + vector.dx, y: self.y + vector.dy) } /** * Returns true if the `otherPoint` is within `tolerance` * * Calculates the distance between points as the straight line between them. * * - Parameters: * - otherPoint: to compare against * - tolerance: to allow when comparing */ public func isCloseTo(point otherPoint: CGPoint, withTolerance tolerance: CGFloat = 0) -> Bool { return abs(CGVector(dx: otherPoint.x - self.x, dy: otherPoint.y - self.y).squareMagnitude) < pow(tolerance, 2) } /** * Hash value of the point, in the form "(x,y)".hashValue */ public var hashValue: Int { return "(\(self.x),\(self.y))".hashValue } } public extension CGVector { /** * The square of the vector's magnitude. * * Avoids a (slow, expensive) call to `sqrt`, so is to be preferred when you are only comparing vectors and do not need the exact magnitude. */ public var squareMagnitude: CGFloat { return (dx * dx) + (dy * dy) } /** * The magitude (length) of the vector. * * See also `squareMagnitude` for a faster alternative avoiding a `sqrt` call if the literal magnitude is not required. */ public var magnitude: CGFloat { return sqrt(self.squareMagnitude) } /** * The inverse of the current vector */ public var inverse: CGVector { return CGVector(dx: -self.dx, dy: -self.dy) } /** * Returns the dot product with another given vector * * - Parameter otherVector: The other vector to calculate the dot product with */ public func getDotProduct(withVector otherVector: CGVector) -> CGFloat { return (self.dx * otherVector.dx) + (self.dy * otherVector.dy) } /** * Scales the vector by the given multiplier and returns a new vector * * - Parameter byMultiplier: the multiplier to scale by */ public func scale(byMultiplier multiplier: CGFloat) -> CGVector { return CGVector(dx: self.dx * multiplier, dy: self.dy * multiplier) } /** * Scales the vector by the given multiplier and returns a new vector * * - Parameter byMultiplier: the multiplier to scale by */ public func scale(byMultiplier multiplier: Int) -> CGVector { return self.scale(byMultiplier: CGFloat(multiplier)) } /** * Convenience initialiser to calculate vector between two points. */ public init(originPoint: CGPoint, destinationPoint: CGPoint) { self.dx = destinationPoint.x - originPoint.x self.dy = destinationPoint.y - originPoint.y } } public extension Collection where Indices.Iterator.Element == Index { /** * Returns the element at the specified index iff it is within bounds, otherwise nil. * - Parameter index: index of collection to return, if available */ public subscript (safe index: Index) -> Generator.Element? { return indices.contains(index) ? self[index] : nil } } public extension CGRect { /** * Returns true if any of the given CGPoints are within the CGRect */ public func contains(anyOf points: Array<CGPoint>, includingOnBoundary: Bool = true) -> Bool { for point in points { if self.contains(point, includingOnBoundary: includingOnBoundary) { return true } } return false } /** * Returns true if all of the given CGPoints are within the CGRect */ public func contains(allOf points: Array<CGPoint>, includingOnBoundary: Bool = true) -> Bool { for point in points { if !self.contains(point, includingOnBoundary: includingOnBoundary) { return false } } return true } /** * Returns true if the CGRect contains the given CGPoint */ public func contains(_ point: CGPoint, includingOnBoundary: Bool) -> Bool { guard includingOnBoundary else { return self.contains(point) } let x = point.x let y = point.y return x <= self.maxX && x >= self.minX && y <= self.maxY && y >= self.minY } /** * Longest edge length (either width or height) of the CGRect */ public var longestEdgeLength: CGFloat { return max(self.size.width, self.size.height) } /** * Shorted edge length (either width or height) of the CGRect */ public var shortestEdgeLength: CGFloat { return min(self.size.width, self.size.height) } /** * Returns a CGRect moved by the given vector. * * Retains size, only the origin is updated. */ public func movedBy(vector: CGVector) -> CGRect { return CGRect(origin: self.origin.movedBy(vector: vector), size: self.size) } // Center public var pointCenter: CGPoint { return self.pointMidXMidY } public var pointMidXMidY: CGPoint { return CGPoint(x: self.midX, y: self.midY) } // EightCorners - NOTE: Didn't do "top left" or similar, because that depends on the coordinate system (views vs scenekit nodes, for example) public var pointMinXMinY: CGPoint { return CGPoint(x: self.minX, y: self.minY) } public var pointMidXMinY: CGPoint { return CGPoint(x: self.midX, y: self.minY) } public var pointMaxXMinY: CGPoint { return CGPoint(x: self.maxX, y: self.minY) } public var pointMaxXMidY: CGPoint { return CGPoint(x: self.maxX, y: self.midY) } public var pointMaxXMaxY: CGPoint { return CGPoint(x: self.maxX, y: self.maxY) } public var pointMidXMaxY: CGPoint { return CGPoint(x: self.midX, y: self.maxY) } public var pointMinXMaxY: CGPoint { return CGPoint(x: self.minX, y: self.maxY) } public var pointMinXMidY: CGPoint { return CGPoint(x: self.minX, y: self.midY) } } public extension UIView { /** * All ancestors of the current view (including itsself) */ public var hierarchy: Array<UIView> { var ancestors: Array<UIView> = [ self ] var currentView = self while let currentSuperview = currentView.superview { ancestors.append(currentSuperview) currentView = currentSuperview } return ancestors } } public extension UIColor { /** * Convenience initializer to start from a HSBA object */ public convenience init(hsba: HSBA) { self.init(hue: hsba.hue, saturation: hsba.saturation, brightness: hsba.brightness, alpha: hsba.alpha) } /** * Creates a new color based on the current color using the given saturation * * - Parameter saturation: the value to set to; the range depends on the color space for the color, however in sRGB the range is 0.0...1.0 */ public func with(saturation: CGFloat) -> UIColor { var hsba = self.hsba hsba.saturation = saturation return type(of: self).init(hue: hsba.hue, saturation: hsba.saturation, brightness: hsba.brightness, alpha: hsba.alpha) } /** * Returns a HSBA representation of the color. */ public var hsba: HSBA { var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) return HSBA(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha) } } /** * Represents a color in Hue/Saturation/Brightness/Alpha format. * * As this allows the reader to visualise properties of the colour more easily than RGB, this may be preferred to standard UIColors or RGB values. */ public struct HSBA { /** * The hue of the color. * * This is often between 0.0...1.0, but depends on the color space the color will be presented in. * * - Note: If saturation or brightness are zero, the hue may not make sense. For example, `UIColor.black.hsba` and UIColor.white.hsba` both have a hue of 0º, if you take only the hue and replace saturation and brightness values this will generate a red color. */ public var hue: CGFloat /** * The saturation of the color. * * This is often between 0.0...1.0, but depends on the color space the color will be presented in. */ public var saturation: CGFloat /** * The brightness of the color. * * This is often between 0.0...1.0, but depends on the color space the color will be presented in. */ public var brightness: CGFloat /** * The alpha (opacity) of the color. * * This is often between 0.0...1.0, but depends on the color space the color will be presented in. * * Lower values denote a less opaque color. */ public var alpha: CGFloat /** * Converts the HSBA back into a UIColor for display. */ public var uiColor: UIColor { return UIColor(hue: self.hue, saturation: self.saturation, brightness: self.brightness, alpha: self.alpha) } /** * Converts the HSBA back into a CGColor for display. */ public var cgColor: CGColor { return self.uiColor.cgColor } } public extension UIBezierPath { /** * Convenience initialiser to create a full-circle path without having to explicitly state angles. */ public convenience init(arcCenter: CGPoint, radius: CGFloat, clockwise: Bool = true) { self.init(arcCenter: arcCenter, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: clockwise) } /** * Generates a smoothed line through given points * * - Parameters: * - points: points to draw the line through * - closed: if true, the line is closed to form a continuous path * * From a [github comment by Jérôme Gangneux](https://github.com/jnfisher/ios-curve-interpolation/issues/6) */ public static func interpolateHermiteFor(points: Array<CGPoint>, closed: Bool = false) -> UIBezierPath { guard points.count >= 2 else { return UIBezierPath() } if points.count == 2 { let bezierPath = UIBezierPath() bezierPath.move(to: points[0]) bezierPath.addLine(to: points[1]) return bezierPath } let nCurves = closed ? points.count : points.count - 1 let path = UIBezierPath() for i in 0..<nCurves { var curPt = points[i] var prevPt: CGPoint, nextPt: CGPoint, endPt: CGPoint if i == 0 { path.move(to: curPt) } var nexti = (i+1)%points.count var previ = (i-1 < 0 ? points.count-1 : i-1) prevPt = points[previ] nextPt = points[nexti] endPt = nextPt var mx: CGFloat var my: CGFloat if closed || i > 0 { mx = (nextPt.x - curPt.x) * CGFloat(0.5) mx += (curPt.x - prevPt.x) * CGFloat(0.5) my = (nextPt.y - curPt.y) * CGFloat(0.5) my += (curPt.y - prevPt.y) * CGFloat(0.5) } else { mx = (nextPt.x - curPt.x) * CGFloat(0.5) my = (nextPt.y - curPt.y) * CGFloat(0.5) } var ctrlPt1 = CGPoint.zero ctrlPt1.x = curPt.x + mx / CGFloat(3.0) ctrlPt1.y = curPt.y + my / CGFloat(3.0) curPt = points[nexti] nexti = (nexti + 1) % points.count previ = i; prevPt = points[previ] nextPt = points[nexti] if closed || i < nCurves-1 { mx = (nextPt.x - curPt.x) * CGFloat(0.5) mx += (curPt.x - prevPt.x) * CGFloat(0.5) my = (nextPt.y - curPt.y) * CGFloat(0.5) my += (curPt.y - prevPt.y) * CGFloat(0.5) } else { mx = (curPt.x - prevPt.x) * CGFloat(0.5) my = (curPt.y - prevPt.y) * CGFloat(0.5) } var ctrlPt2 = CGPoint.zero ctrlPt2.x = curPt.x - mx / CGFloat(3.0) ctrlPt2.y = curPt.y - my / CGFloat(3.0) path.addCurve(to: endPt, controlPoint1: ctrlPt1, controlPoint2: ctrlPt2) } if closed { path.close() } return path } } @available(iOS 10.0, *) public extension UIImage { public struct RotationOptions: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let flipOnVerticalAxis = RotationOptions(rawValue: 1) public static let flipOnHorizontalAxis = RotationOptions(rawValue: 2) } /** * Rotates the image with the given options. * * - Parameters: * - rotationAngleRadians: the angle to rotate the image by * - options: Options while rendering, eg: whether or not to flip on an axis * * - Returns: A rotated image, or nil if the image could not be rendered. */ func rotated(by rotationAngleRadians: CGFloat, options: RotationOptions = []) -> UIImage? { guard let cgImage = self.cgImage else { return nil } let rotationInRadians = rotationAngleRadians let transform = CGAffineTransform(rotationAngle: rotationInRadians) var rect = CGRect(origin: .zero, size: self.size).applying(transform) rect.origin = .zero let renderer = UIGraphicsImageRenderer(size: rect.size) return renderer.image { renderContext in renderContext.cgContext.translateBy(x: rect.midX, y: rect.midY) renderContext.cgContext.rotate(by: rotationInRadians) let x: CGFloat = options.contains(.flipOnVerticalAxis) ? -1.0 : 1.0 let y: CGFloat = options.contains(.flipOnHorizontalAxis) ? 1.0 : -1.0 renderContext.cgContext.scaleBy(x: x, y: y) let drawRect = CGRect(origin: CGPoint(x: -self.size.width/2, y: -self.size.height/2), size: self.size) renderContext.cgContext.draw(cgImage, in: drawRect) } } } /** * Represents the result of diff-ing two collections */ public struct DiffResult<T: Hashable> { /** * Items only found in the first collection * * > [1,2].diff(other: [2,3]).uniqueToFirst * Set([1]) * * - Note: Does not retain the original order of items. */ public let uniqueToFirst: Set<T> /** * Items only found in the second collection * * > [1,2].diff(other: [2,3]).uniqueToFirst * Set([3]) * * - Note: Does not retain the original order of items. */ public let uniqueToSecond: Set<T> /** * Items only found in both collections * * > [1,2].diff(other: [2,3]).uniqueToFirst * Set([2]) * * - Note: Does not retain the original order of items. */ public let containedInBoth: Set<T> /** * (computed) Items in the first collection * * > [1,2].diff(other: [2,3]).uniqueToFirst * Set([1,2]) * * - Note: Does not retain the original order of items. */ public var containedInFirst: Set<T> { return self.uniqueToFirst.union(self.containedInBoth) } /** * (computed) Items in the second collection * * > [1,2].diff(other: [2,3]).uniqueToFirst * Set([2,3]) * * - Note: Does not retain the original order of items. */ public var containedInSecond: Set<T> { return self.uniqueToSecond.union(self.containedInBoth) } } public extension Array where Element: Hashable { /** * Returns the difference between two given arrays * * - Parameter other: Other array to compare against ('second' in the DiffResult) * * - Returns: A DiffResult object repressenting the differences between the arrays */ public func diff(other: Array<Element>) -> DiffResult<Element> { let firstSet = Set(self) let secondSet = Set(other) return DiffResult<Element>(uniqueToFirst: firstSet.subtracting(secondSet), uniqueToSecond: secondSet.subtracting(firstSet), containedInBoth: firstSet.intersection(secondSet)) } } public extension NSLayoutConstraint { #if swift(>=3.2) // Not required, added to the language in Swift 4 #else /** * Convenience initalizer to also set the priority during init */ public convenience init( item: Any, attribute firstAttribute: NSLayoutAttribute, relatedBy: NSLayoutRelation, toItem: Any?, attribute secondAttribute: NSLayoutAttribute, multiplier: CGFloat, constant: CGFloat, priority: UILayoutPriority ) { self.init(item: item, attribute: firstAttribute, relatedBy: relatedBy, toItem: toItem, attribute: secondAttribute, multiplier: multiplier, constant: constant) self.priority = priority } #endif } public extension URL { /** * Convenience optional initializer to avoid another 'if let' block */ public init?(string: String?, relativeTo: URL? = nil) { if let string = string { self.init(string: string, relativeTo: relativeTo) } else { return nil } } } public extension UIImage { /** * Scales image to given width, preserving ratio. * * - Parameter width: width to scale to */ public func scaleImage(toWidth width: CGFloat) -> UIImage? { let scalingRatio = width / self.size.width let newHeight = scalingRatio * self.size.height return self.scaleImage(toSize: CGSize(width: width, height: newHeight)) } /** * Scales image to given height, preserving ratio. * * - Parameter height: height to scale to */ public func scaleImage(toHeight height: CGFloat) -> UIImage? { let scalingRatio = height / self.size.height let newWidth = scalingRatio * self.size.width return self.scaleImage(toSize: CGSize(width: newWidth, height: height)) } /** * Scales image to given size, ignoring original ratio. * * - Parameter size: to scale to */ public func scaleImage(toSize size: CGSize) -> UIImage? { let newRect = CGRect(x: 0, y: 0, width: size.width, height: size.height).integral UIGraphicsBeginImageContextWithOptions(size, false, 0) if let context = UIGraphicsGetCurrentContext() { context.interpolationQuality = .high let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height) context.concatenate(flipVertical) context.draw(self.cgImage!, in: newRect) let newImage = UIImage(cgImage: context.makeImage()!) UIGraphicsEndImageContext() return newImage } return nil } } public extension URL { public enum URLQueryItemsError: Error { case CannotGetComponents(fromUrl: URL) case CannotGetUrl(fromComponents: URLComponents) } private func getComponents() throws -> URLComponents { // Get components from current URL guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true) else { throw URLQueryItemsError.CannotGetComponents(fromUrl: self) } return components } /** * Replaces the given query items. * * Also adds missing keys if they were not in the original query items. * * let aUrl = "http://example.com?foo=bar" * let replacements = [ "foo" : "replaced", "bar": "added" ] * print( * URL(string: aUrl) * .replacing(queryItems: replacements) * .absoluteString * ) * * output: * * "http://example.com?foo=baz&bar=added" * * - Parameter queryItems: String Dictionary of keys to replace in query items */ public func replacing(queryItems: [String:String]) throws -> URL { var components = try self.getComponents() let bannedKeys = Array(queryItems.keys) components.queryItems = (components.queryItems ?? []).filter({ !bannedKeys.contains($0.name) }) for (key, value) in queryItems { components.queryItems?.append(URLQueryItem(name: key, value: value)) } guard let url = components.url else { throw URLQueryItemsError.CannotGetUrl(fromComponents: components) } return url } /** * Removes the given query item keys * * let aUrl = "http://example.com?foo=bar&baz=quux" * let removals = [ "foo", "corge" ] * print( * URL(string: aUrl) * .replacing(queryItems: replacements) * .absoluteString * ) * * output: * * "http://example.com?baz=quux" * * - Parameter queryItems: Array of keys to remove from query items */ public func removing(queryItems: [String]) throws -> URL { var components = try self.getComponents() let bannedKeys = queryItems components.queryItems = (components.queryItems ?? []).filter({ !bannedKeys.contains($0.name) }) guard let url = components.url else { throw URLQueryItemsError.CannotGetUrl(fromComponents: components) } return url } } public extension CGAffineTransform { /** * Calculates the X scale involved in the transformation * * - Note: this uses `sqrt` so is a relatively expensive calculation. If it is possible to record the scale some other way it may be more efficient. */ var xScale: CGFloat { return sqrt(self.a * self.a + self.c * self.c); } /** * Calculates the Y scale involved in the transformation * * - Note: this uses `sqrt` so is a relatively expensive calculation. If it is possible to record the scale some other way it may be more efficient. */ var yScale: CGFloat { return sqrt(self.b * self.b + self.d * self.d); } }
63c6a5132e015de6a3843e0da3f6fb27
31.04261
263
0.591423
false
false
false
false
toohotz/IQKeyboardManager
refs/heads/master
Demo/Swift_Demo/ViewController/SpecialCaseViewController.swift
mit
1
// // SpecialCaseViewController.swift // IQKeyboard // // Created by Iftekhar on 23/09/14. // Copyright (c) 2014 Iftekhar. All rights reserved. // import Foundation import UIKit class SpecialCaseViewController: UIViewController, UISearchBarDelegate, UITextFieldDelegate, UITextViewDelegate, UIPopoverPresentationControllerDelegate { @IBOutlet private var customWorkTextField : UITextField! @IBOutlet private var textField6 : UITextField! @IBOutlet private var textField7 : UITextField! @IBOutlet private var textField8 : UITextField! @IBOutlet private var switchInteraction1 : UISwitch! @IBOutlet private var switchInteraction2 : UISwitch! @IBOutlet private var switchInteraction3 : UISwitch! @IBOutlet private var switchEnabled1 : UISwitch! @IBOutlet private var switchEnabled2 : UISwitch! @IBOutlet private var switchEnabled3 : UISwitch! override func viewDidLoad() { super.viewDidLoad() textField6.userInteractionEnabled = switchInteraction1.on textField7.userInteractionEnabled = switchInteraction2.on textField8.userInteractionEnabled = switchInteraction3.on textField6.enabled = switchEnabled1.on textField7.enabled = switchEnabled2.on textField8.enabled = switchEnabled3.on updateUI() } @IBAction func showAlertClicked (barButton : UIBarButtonItem!) { let alertController = UIAlertController(title: "IQKeyboardManager", message: "It doesn't affect UIAlertController (Doesn't add IQToolbar on it's textField", preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) alertController.addTextFieldWithConfigurationHandler({ (textField : UITextField) in textField.placeholder = "Username" }) alertController.addTextFieldWithConfigurationHandler({ (textField : UITextField) in textField.placeholder = "Password" textField.secureTextEntry = true }) self.presentViewController(alertController, animated: true, completion: nil) } func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) } func searchBarTextDidEndEditing(searchBar: UISearchBar) { searchBar.setShowsCancelButton(false, animated: true) } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } func updateUI() { textField6.placeholder = (textField6.enabled ? "enabled" : "" ) + "," + (textField6.userInteractionEnabled ? "userInteractionEnabled" : "" ) textField7.placeholder = (textField7.enabled ? "enabled" : "" ) + "," + (textField7.userInteractionEnabled ? "userInteractionEnabled" : "" ) textField8.placeholder = (textField8.enabled ? "enabled" : "" ) + "," + (textField8.userInteractionEnabled ? "userInteractionEnabled" : "" ) } func switch1UserInteractionAction(sender: UISwitch) { textField6.userInteractionEnabled = sender.on updateUI() } func switch2UserInteractionAction(sender: UISwitch) { textField7.userInteractionEnabled = sender.on updateUI() } func switch3UserInteractionAction(sender: UISwitch) { textField8.userInteractionEnabled = sender.on updateUI() } func switch1Action(sender: UISwitch) { textField6.enabled = sender.on updateUI() } func switch2Action(sender: UISwitch) { textField7.enabled = sender.on updateUI() } func switch3Action(sender: UISwitch) { textField8.enabled = sender.on updateUI() } func textFieldShouldBeginEditing(textField: UITextField) -> Bool { if (textField == customWorkTextField) { if(textField.isAskingCanBecomeFirstResponder == false) { let alertController = UIAlertController(title: "IQKeyboardManager", message: "Do your custom work here", preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } return false } else { return true } } func textFieldDidBeginEditing(textField: UITextField) { switchEnabled1.enabled = false switchEnabled2.enabled = false switchEnabled3.enabled = false switchInteraction1.enabled = false switchInteraction2.enabled = false switchInteraction3.enabled = false } func textFieldDidEndEditing(textField: UITextField) { switchEnabled1.enabled = true switchEnabled2.enabled = true switchEnabled3.enabled = true switchInteraction1.enabled = true switchInteraction2.enabled = true switchInteraction3.enabled = true } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { if identifier == "SettingsNavigationController" { let controller = segue.destinationViewController controller.modalPresentationStyle = .Popover controller.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem let heightWidth = max(CGRectGetWidth(UIScreen.mainScreen().bounds), CGRectGetHeight(UIScreen.mainScreen().bounds)); controller.preferredContentSize = CGSizeMake(heightWidth, heightWidth) controller.popoverPresentationController?.delegate = self } } } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } func prepareForPopoverPresentation(popoverPresentationController: UIPopoverPresentationController) { self.view.endEditing(true) } override func shouldAutorotate() -> Bool { return true } }
a7c5338a2eba99582808a07eeae031f9
36.117647
188
0.665135
false
false
false
false
steelwheels/Coconut
refs/heads/master
CoconutData/Source/Value/CNStorage.swift
lgpl-2.1
1
/* * @file CNStorage.swift * @brief Define CNStorage class * @par Copyright * Copyright (C) 2021 Steel Wheels Project */ #if os(iOS) import UIKit #endif import Foundation private class CNStorageCache { private var mPath: CNValuePath private var mIsDirty: Bool public init(path p: CNValuePath){ mPath = p mIsDirty = true } public var path: CNValuePath { get { return mPath }} public var isDirty: Bool { get { return mIsDirty } set(newval) { mIsDirty = newval } } } private class CNStorageCallback { public typealias EventFunction = CNStorage.EventFunction private var mPath: CNValuePath private var mEventFunction: EventFunction public init(path p: CNValuePath, eventFunc efunc: @escaping EventFunction){ mPath = p mEventFunction = efunc } public var path: CNValuePath { get { return mPath }} public var eventFunc: EventFunction { get { return mEventFunction }} } public class CNStorage { public typealias EventFunction = () -> Void private var mSourceDirectory: URL private var mCacheDirectory: URL private var mFilePath: String private var mRootValue: CNMutableValue private var mCache: Dictionary<Int, CNStorageCache> private var mNextCacheId: Int private var mEventFunctions: Dictionary<Int, CNStorageCallback> private var mNextEventFuncId: Int private var mLock: NSLock // packdir: Root directory for package (*.jspkg) // fpath: The location of data file against packdir public init(sourceDirectory srcdir: URL, cacheDirectory cachedir: URL, filePath fpath: String) { mSourceDirectory = srcdir mCacheDirectory = cachedir mFilePath = fpath mRootValue = CNMutableDictionaryValue(sourceDirectory: srcdir, cacheDirectory: cachedir) mCache = [:] mNextCacheId = 0 mEventFunctions = [:] mNextEventFuncId = 0 mLock = NSLock() } public var description: String { get { return "{srcdir=\(mSourceDirectory.path), cachedir=\(mCacheDirectory.path), file=\(mFilePath)}" }} private var sourceFile: URL { get { return mSourceDirectory.appendingPathComponent(mFilePath) }} private var cacheFile: URL { get { return mCacheDirectory.appendingPathComponent(mFilePath) }} public func load() -> Result<CNValue, NSError> { /* Mutex lock */ mLock.lock() ; defer { mLock.unlock() } /* Copy source file to cache file */ let srcfile = self.sourceFile let cachefile = self.cacheFile guard let contents = CNStorage.createCacheFile(cacheFile: cachefile, sourceFile: srcfile) else { let err = NSError.fileError(message: "Failed to create cache file: \(cachefile.path)") return .failure(err) } let parser = CNValueParser() let result: Result<CNValue, NSError> switch parser.parse(source: contents as String) { case .success(let val): mRootValue = CNMutableValue.valueToMutableValue(from: val, sourceDirectory: mSourceDirectory, cacheDirectory: mCacheDirectory) result = .success(val) case .failure(let err): result = .failure(err) } return result } public static func createCacheFile(cacheFile cache: URL, sourceFile source: URL) -> String? { let fmanager = FileManager.default guard fmanager.fileExists(atURL: source) else { CNLog(logLevel: .error, message: "Source file \(source.path) is NOT exist", atFunction: #function, inFile: #file) return nil } if fmanager.fileExists(atURL: cache){ /* Already exist */ return cache.loadContents() as String? } else { /* File is not exist */ if fmanager.copyFile(sourceFile: source, destinationFile: cache, doReplace: false) { return cache.loadContents() as String? } else { CNLog(logLevel: .error, message: "Failed to create cache file: \(cache.path)", atFunction: #function, inFile: #file) return nil } } } public func removeCacheFile() -> Result<CNValue, NSError> { if let err = FileManager.default.removeFile(atURL: self.cacheFile) { return .failure(err) } else { return self.load() } } public func allocateCache(forPath path: CNValuePath) -> Int { /* Mutex lock */ mLock.lock() ; defer { mLock.unlock() } let cache = CNStorageCache(path: path) let cid = mNextCacheId mCache[mNextCacheId] = cache mNextCacheId += 1 return cid } public func removeCache(cacheId cid: Int) { /* Mutex lock */ mLock.lock() ; defer { mLock.unlock() } mCache[cid] = nil } public func isDirty(cacheId cid: Int) -> Bool { if let cache = mCache[cid] { return cache.isDirty } else { CNLog(logLevel: .error, message: "Unknown cache id: \(cid)", atFunction: #function, inFile: #file) return false } } private func setDirty(at path: CNValuePath) { for cache in mCache.values { if cache.path.isIncluded(in: path) { cache.isDirty = true } } } public func setClean(cacheId cid: Int) { if let cache = mCache[cid] { cache.isDirty = false } else { CNLog(logLevel: .error, message: "Unknown cache id: \(cid)", atFunction: #function, inFile: #file) } } public func allocateEventFunction(forPath path: CNValuePath, eventFunc efunc: @escaping EventFunction) -> Int { /* Mutex lock */ mLock.lock() ; defer { mLock.unlock() } let cbfunc = CNStorageCallback(path: path, eventFunc: efunc) let eid = mNextEventFuncId mEventFunctions[mNextEventFuncId] = cbfunc mNextEventFuncId += 1 return eid } public func removeEventFunction(eventFuncId eid: Int) { /* Mutex lock */ mLock.lock() ; defer { mLock.unlock() } mEventFunctions[eid] = nil } public func value(forPath path: CNValuePath) -> CNValue? { /* Mutex lock */ mLock.lock() ; defer { mLock.unlock() } if let elms = normalizeValuePath(valuePath: path) { switch mRootValue.value(forPath: elms) { case .success(let val): return val case .failure(let err): CNLog(logLevel: .error, message: "Error: \(err.toString())", atFunction: #function, inFile: #file) } } return nil } public func set(value val: CNValue, forPath path: CNValuePath) -> Bool { /* Mutex lock and unlock */ mLock.lock() ; defer { mLock.unlock() ; triggerCallbacks(path: path)} var result: Bool if let elms = normalizeValuePath(valuePath: path) { if let err = mRootValue.set(value: val, forPath: elms) { /* Some error occured */ CNLog(logLevel: .error, message: "Error: \(err.toString())", atFunction: #function, inFile: #file) result = false } else { /* No error */ mRootValue.labelTable().clear() setDirty(at: path) result = true } } else { result = false } return result } public func append(value val: CNValue, forPath path: CNValuePath) -> Bool { /* Mutex lock and unlock */ mLock.lock() ; defer { mLock.unlock() ; triggerCallbacks(path: path)} if let elms = normalizeValuePath(valuePath: path) { if let err = mRootValue.append(value: val, forPath: elms) { CNLog(logLevel: .error, message: "Error: \(err.toString())", atFunction: #function, inFile: #file) return false } else { mRootValue.labelTable().clear() setDirty(at: path) return true } } else { return false } } public func delete(forPath path: CNValuePath) -> Bool { /* Mutex lock and unlock */ mLock.lock() ; defer { mLock.unlock() } setDirty(at: path) if let elms = normalizeValuePath(valuePath: path) { if let err = mRootValue.delete(forPath: elms) { CNLog(logLevel: .error, message: "Error: \(err.toString())", atFunction: #function, inFile: #file) return false } else { /* No error */ mRootValue.labelTable().clear() return true } } else { return false } } private func normalizeValuePath(valuePath path: CNValuePath) -> Array<CNValuePath.Element>? { if let ident = path.identifier { if var topelms = mRootValue.labelTable().labelToPath(label: ident, in: mRootValue) { topelms.append(contentsOf: path.elements) return topelms } else { CNLog(logLevel: .error, message: "Failed to find label: \(ident)", atFunction: #function, inFile: #file) } } return path.elements } private func triggerCallbacks(path pth: CNValuePath) { for event in mEventFunctions.values { if event.path.isIncluded(in: pth) { event.eventFunc() } } } public func segments(traceOption trace: CNValueSegmentTraceOption) -> Array<CNMutableValueSegment> { return CNSegmentsInValue(value: mRootValue, traceOption: trace) } public func save() -> Bool { /* Mutex lock */ mLock.lock() ; defer { mLock.unlock() } let cachefile = self.cacheFile let pathes = cachefile.deletingLastPathComponent() if !FileManager.default.fileExists(atPath: pathes.path) { if let err = FileManager.default.createDirectories(directory: pathes) { CNLog(logLevel: .error, message: err.toString(), atFunction: #function, inFile: #file) return false // stop the save operation } } /* Save into the file */ if save(value: mRootValue, outFile: cachefile) { return true } else { CNLog(logLevel: .error, message: "Failed to store storage: \(cachefile.path)", atFunction: #function, inFile: #file) return false } } private func save(value val: CNMutableValue, outFile file: URL) -> Bool { /* save it self */ var result = true if mRootValue.isDirty { let txt = val.toValue().toScript().toStrings().joined(separator: "\n") if file.storeContents(contents: txt + "\n") { val.isDirty = false } else { CNLog(logLevel: .error, message: "Failed to store storage: \(file.path)", atFunction: #function, inFile: #file) result = false } } /* save segmented values */ let refs = CNSegmentsInValue(value: val, traceOption: .traceNonNull) for ref in refs { if let cval = ref.context { if !save(value: cval, outFile: ref.cacheFile) { result = false } } } return result } public func toValue() -> CNValue { /* Mutex lock */ mLock.lock() ; defer { mLock.unlock() } return mRootValue.toValue() } }
4f8c228586dfa11315379cf1db8687c7
27.709302
129
0.685703
false
false
false
false
Alan007/iOS-Study-Demo
refs/heads/master
Swift版的FMDB和CoreData学习_转/SwiftFMDB/DB.swift
apache-2.0
28
// // DB.swift // SwiftFMDBDemo // // Created by Limin Du on 11/15/14. // Copyright (c) 2014 GoldenFire.Do. All rights reserved. // import Foundation class DB { class var sharedInstance: DB { struct Static { static var instance: DB? static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { Static.instance = DB() Static.instance?.initDatabase() } return Static.instance! } class var tableName:String { return "table1" } private var db:FMDatabase? func getDatabase()->FMDatabase? { return db } private func initDatabase()->Bool { var result:Bool = false let table_name = DB.tableName let documentPath : AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0] let dbPath:String = documentPath.stringByAppendingPathComponent("demo.db") let filemanager = NSFileManager.defaultManager() if !filemanager.fileExistsAtPath(dbPath) { result = filemanager.createFileAtPath(dbPath, contents: nil, attributes: nil) if !result { return false } } db = FMDatabase(path: dbPath) if db == nil { return false } db!.logsErrors = true if db!.open() { //db!.shouldCacheStatements() /*if db!.tableExists(table_name) { db!.executeUpdate("DROP TABLE \(table_name)", withArgumentsInArray: nil) }*/ if !db!.tableExists(table_name) { var creat_table = "CREATE TABLE \(table_name) (id INTEGER PRIMARY KEY, name VARCHAR(80), description VARCHAR(80))" result = db!.executeUpdate(creat_table, withArgumentsInArray: nil) } } println("init : \(result)") return result } func closeDatabase() { db?.close() } }
1b35136d32d082e7a6f77beea24e87e2
25.3625
130
0.53817
false
false
false
false
Snail93/iOSDemos
refs/heads/dev
AutoSQLite.swift/Pods/SQLite.swift/Sources/SQLite/Core/Statement.swift
apache-2.0
13
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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 SQLITE_SWIFT_STANDALONE import sqlite3 #elseif SQLITE_SWIFT_SQLCIPHER import SQLCipher #elseif os(Linux) import CSQLite #else import SQLite3 #endif /// A single SQL statement. public final class Statement { fileprivate var handle: OpaquePointer? = nil fileprivate let connection: Connection init(_ connection: Connection, _ SQL: String) throws { self.connection = connection try connection.check(sqlite3_prepare_v2(connection.handle, SQL, -1, &handle, nil)) } deinit { sqlite3_finalize(handle) } public lazy var columnCount: Int = Int(sqlite3_column_count(self.handle)) public lazy var columnNames: [String] = (0..<Int32(self.columnCount)).map { String(cString: sqlite3_column_name(self.handle, $0)) } /// A cursor pointing to the current row. public lazy var row: Cursor = Cursor(self) /// Binds a list of parameters to a statement. /// /// - Parameter values: A list of parameters to bind to the statement. /// /// - Returns: The statement object (useful for chaining). public func bind(_ values: Binding?...) -> Statement { return bind(values) } /// Binds a list of parameters to a statement. /// /// - Parameter values: A list of parameters to bind to the statement. /// /// - Returns: The statement object (useful for chaining). public func bind(_ values: [Binding?]) -> Statement { if values.isEmpty { return self } reset() guard values.count == Int(sqlite3_bind_parameter_count(handle)) else { fatalError("\(sqlite3_bind_parameter_count(handle)) values expected, \(values.count) passed") } for idx in 1...values.count { bind(values[idx - 1], atIndex: idx) } return self } /// Binds a dictionary of named parameters to a statement. /// /// - Parameter values: A dictionary of named parameters to bind to the /// statement. /// /// - Returns: The statement object (useful for chaining). public func bind(_ values: [String: Binding?]) -> Statement { reset() for (name, value) in values { let idx = sqlite3_bind_parameter_index(handle, name) guard idx > 0 else { fatalError("parameter not found: \(name)") } bind(value, atIndex: Int(idx)) } return self } fileprivate func bind(_ value: Binding?, atIndex idx: Int) { if value == nil { sqlite3_bind_null(handle, Int32(idx)) } else if let value = value as? Blob { sqlite3_bind_blob(handle, Int32(idx), value.bytes, Int32(value.bytes.count), SQLITE_TRANSIENT) } else if let value = value as? Double { sqlite3_bind_double(handle, Int32(idx), value) } else if let value = value as? Int64 { sqlite3_bind_int64(handle, Int32(idx), value) } else if let value = value as? String { sqlite3_bind_text(handle, Int32(idx), value, -1, SQLITE_TRANSIENT) } else if let value = value as? Int { self.bind(value.datatypeValue, atIndex: idx) } else if let value = value as? Bool { self.bind(value.datatypeValue, atIndex: idx) } else if let value = value { fatalError("tried to bind unexpected value \(value)") } } /// - Parameter bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement object (useful for chaining). @discardableResult public func run(_ bindings: Binding?...) throws -> Statement { guard bindings.isEmpty else { return try run(bindings) } reset(clearBindings: false) repeat {} while try step() return self } /// - Parameter bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement object (useful for chaining). @discardableResult public func run(_ bindings: [Binding?]) throws -> Statement { return try bind(bindings).run() } /// - Parameter bindings: A dictionary of named parameters to bind to the /// statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement object (useful for chaining). @discardableResult public func run(_ bindings: [String: Binding?]) throws -> Statement { return try bind(bindings).run() } /// - Parameter bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. public func scalar(_ bindings: Binding?...) throws -> Binding? { guard bindings.isEmpty else { return try scalar(bindings) } reset(clearBindings: false) _ = try step() return row[0] } /// - Parameter bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. public func scalar(_ bindings: [Binding?]) throws -> Binding? { return try bind(bindings).scalar() } /// - Parameter bindings: A dictionary of named parameters to bind to the /// statement. /// /// - Returns: The first value of the first row returned. public func scalar(_ bindings: [String: Binding?]) throws -> Binding? { return try bind(bindings).scalar() } public func step() throws -> Bool { return try connection.sync { try self.connection.check(sqlite3_step(self.handle)) == SQLITE_ROW } } fileprivate func reset(clearBindings shouldClear: Bool = true) { sqlite3_reset(handle) if (shouldClear) { sqlite3_clear_bindings(handle) } } } extension Statement : Sequence { public func makeIterator() -> Statement { reset(clearBindings: false) return self } } public protocol FailableIterator : IteratorProtocol { func failableNext() throws -> Self.Element? } extension FailableIterator { public func next() -> Element? { return try! failableNext() } } extension Array { public init<I: FailableIterator>(_ failableIterator: I) throws where I.Element == Element { self.init() while let row = try failableIterator.failableNext() { append(row) } } } extension Statement : FailableIterator { public typealias Element = [Binding?] public func failableNext() throws -> [Binding?]? { return try step() ? Array(row) : nil } } extension Statement : CustomStringConvertible { public var description: String { return String(cString: sqlite3_sql(handle)) } } public struct Cursor { fileprivate let handle: OpaquePointer fileprivate let columnCount: Int fileprivate init(_ statement: Statement) { handle = statement.handle! columnCount = statement.columnCount } public subscript(idx: Int) -> Double { return sqlite3_column_double(handle, Int32(idx)) } public subscript(idx: Int) -> Int64 { return sqlite3_column_int64(handle, Int32(idx)) } public subscript(idx: Int) -> String { return String(cString: UnsafePointer(sqlite3_column_text(handle, Int32(idx)))) } public subscript(idx: Int) -> Blob { if let pointer = sqlite3_column_blob(handle, Int32(idx)) { let length = Int(sqlite3_column_bytes(handle, Int32(idx))) return Blob(bytes: pointer, length: length) } else { // The return value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. // https://www.sqlite.org/c3ref/column_blob.html return Blob(bytes: []) } } // MARK: - public subscript(idx: Int) -> Bool { return Bool.fromDatatypeValue(self[idx]) } public subscript(idx: Int) -> Int { return Int.fromDatatypeValue(self[idx]) } } /// Cursors provide direct access to a statement’s current row. extension Cursor : Sequence { public subscript(idx: Int) -> Binding? { switch sqlite3_column_type(handle, Int32(idx)) { case SQLITE_BLOB: return self[idx] as Blob case SQLITE_FLOAT: return self[idx] as Double case SQLITE_INTEGER: return self[idx] as Int64 case SQLITE_NULL: return nil case SQLITE_TEXT: return self[idx] as String case let type: fatalError("unsupported column type: \(type)") } } public func makeIterator() -> AnyIterator<Binding?> { var idx = 0 return AnyIterator { if idx >= self.columnCount { return Optional<Binding?>.none } else { idx += 1 return self[idx - 1] } } } }
22d2e30eca51509b4bcf63c8acd5d3ca
31.053628
106
0.623954
false
false
false
false
wireapp/wire-ios-data-model
refs/heads/develop
Source/Model/Conversation/ZMConversation+Message.swift
gpl-3.0
1
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation private let log = ZMSLog(tag: "Conversations") extension ZMConversation { /// An error describing why a message couldn't be appended to the conversation. public enum AppendMessageError: LocalizedError, Equatable { case missingManagedObjectContext case malformedNonce case failedToProcessMessageData(reason: String) case messageIsEmpty case failedToRemoveImageMetadata case invalidImageUrl case invalidFileUrl case fileSharingIsRestricted public var errorDescription: String? { switch self { case .missingManagedObjectContext: return "The managed object context is missing." case .malformedNonce: return "Encountered a malformed nonce." case .failedToProcessMessageData(let reason): return "Failed to process generic message data. Reason: \(reason)" case .messageIsEmpty: return "Can not send empty text messages." case .failedToRemoveImageMetadata: return "Failed to remove image metatdata." case .invalidImageUrl: return "Invalid image url." case .invalidFileUrl: return "Invalid file url." case .fileSharingIsRestricted: return "File sharing is restricted." } } } /// Appends a button action message. /// /// - Parameters: /// - id: The id of the button action. /// - referenceMessageId: The id of the message which this action references. /// - nonce: The nonce of the button action message. /// /// - Throws: /// - `AppendMessageError` if the message couldn't be appended. /// /// - Returns: /// The appended message. @discardableResult func appendButtonAction(havingId id: String, referenceMessageId: UUID, nonce: UUID = UUID()) throws -> ZMClientMessage { let buttonAction = ButtonAction(buttonId: id, referenceMessageId: referenceMessageId) return try appendClientMessage(with: GenericMessage(content: buttonAction, nonce: nonce), hidden: true) } /// Appends a location message. /// /// - Parameters: /// - locationData: The data describing the location. /// - nonce: The nonce of the location message. /// /// - Throws: /// - `AppendMessageError` if the message couldn't be appended. /// /// - Returns: /// The appended message. @discardableResult public func appendLocation(with locationData: LocationData, nonce: UUID = UUID()) throws -> ZMConversationMessage { let locationContent = Location.with { if let name = locationData.name { $0.name = name } $0.latitude = locationData.latitude $0.longitude = locationData.longitude $0.zoom = locationData.zoomLevel } let message = GenericMessage(content: locationContent, nonce: nonce, expiresAfter: activeMessageDestructionTimeoutValue) return try appendClientMessage(with: message) } /// Appends a knock message. /// /// - Parameters: /// - nonce: The nonce of the knock message. /// /// - Throws: /// `AppendMessageError` if the message couldn't be appended. /// /// - Returns: /// The appended message. @discardableResult public func appendKnock(nonce: UUID = UUID()) throws -> ZMConversationMessage { let content = Knock.with { $0.hotKnock = false } let message = GenericMessage(content: content, nonce: nonce, expiresAfter: activeMessageDestructionTimeoutValue) return try appendClientMessage(with: message) } /// Appends a text message. /// /// - Parameters: /// - content: The message content. /// - mentions: The list of mentioned participants. /// - quotedMessage: The message being replied to. /// - fetchLinkPreview: Whether link previews should be fetched. /// - nonce: The nonce of the message. /// /// - Throws: /// - `AppendMessageError` if the message couldn't be appended. /// /// - Returns: /// The appended message. @discardableResult public func appendText(content: String, mentions: [Mention] = [], replyingTo quotedMessage: ZMConversationMessage? = nil, fetchLinkPreview: Bool = true, nonce: UUID = UUID()) throws -> ZMConversationMessage { guard !(content as NSString).zmHasOnlyWhitespaceCharacters() else { throw AppendMessageError.messageIsEmpty } let text = Text(content: content, mentions: mentions, linkPreviews: [], replyingTo: quotedMessage as? ZMOTRMessage) let genericMessage = GenericMessage(content: text, nonce: nonce, expiresAfter: activeMessageDestructionTimeoutValue) let clientMessage = try appendClientMessage(with: genericMessage, expires: true, hidden: false, configure: { $0.linkPreviewState = fetchLinkPreview ? .waitingToBeProcessed : .done $0.needsLinkAttachmentsUpdate = fetchLinkPreview $0.quote = quotedMessage as? ZMMessage }) if let notificationContext = managedObjectContext?.notificationContext { NotificationInContext(name: ZMConversation.clearTypingNotificationName, context: notificationContext, object: self).post() } return clientMessage } /// Append an image message. /// /// - Parameters: /// - url: A url locating some image data. /// - nonce: The nonce of the message. /// /// - Throws: /// - `AppendMessageError` if the message couldn't be appended. /// /// - Returns: /// The appended message. @discardableResult public func appendImage(at URL: URL, nonce: UUID = UUID()) throws -> ZMConversationMessage { guard URL.isFileURL, ZMImagePreprocessor.sizeOfPrerotatedImage(at: URL) != .zero, let imageData = try? Data.init(contentsOf: URL, options: []) else { throw AppendMessageError.invalidImageUrl } return try appendImage(from: imageData) } /// Append an image message. /// /// - Parameters: /// - imageData: Data representing an image. /// - nonce: The nonce of the message. /// /// - Throws: /// - `AppendMessageError` if the message couldn't be appended. /// /// - Returns: /// The appended message. @discardableResult public func appendImage(from imageData: Data, nonce: UUID = UUID()) throws -> ZMConversationMessage { guard let moc = managedObjectContext else { throw AppendMessageError.missingManagedObjectContext } guard let imageData = try? imageData.wr_removingImageMetadata() else { throw AppendMessageError.failedToRemoveImageMetadata } // mimeType is assigned first, to make sure UI can handle animated GIF file correctly. let mimeType = imageData.mimeType ?? "" // We update the size again when the the preprocessing is done. let imageSize = ZMImagePreprocessor.sizeOfPrerotatedImage(with: imageData) let asset = WireProtos.Asset(imageSize: imageSize, mimeType: mimeType, size: UInt64(imageData.count)) return try append(asset: asset, nonce: nonce, expires: true, prepareMessage: { message in moc.zm_fileAssetCache.storeAssetData(message, format: .original, encrypted: false, data: imageData) }) } /// Append a file message. /// /// - Parameters: /// - fileMetadata: Data describing the file. /// - nonce: The nonce of the message. /// /// - Throws: /// - `AppendMessageError` if the message couldn't be appended. /// /// - Returns: /// The appended message. @discardableResult public func appendFile(with fileMetadata: ZMFileMetadata, nonce: UUID = UUID()) throws -> ZMConversationMessage { guard let moc = managedObjectContext else { throw AppendMessageError.missingManagedObjectContext } guard let data = try? Data.init(contentsOf: fileMetadata.fileURL, options: .mappedIfSafe) else { throw AppendMessageError.invalidFileUrl } return try append(asset: fileMetadata.asset, nonce: nonce, expires: false) { (message) in moc.zm_fileAssetCache.storeAssetData(message, encrypted: false, data: data) if let thumbnailData = fileMetadata.thumbnail { moc.zm_fileAssetCache.storeAssetData(message, format: .original, encrypted: false, data: thumbnailData) } } } private func append(asset: WireProtos.Asset, nonce: UUID, expires: Bool, prepareMessage: (ZMAssetClientMessage) -> Void) throws -> ZMAssetClientMessage { guard let moc = managedObjectContext else { throw AppendMessageError.missingManagedObjectContext } let message: ZMAssetClientMessage do { message = try ZMAssetClientMessage(asset: asset, nonce: nonce, managedObjectContext: moc, expiresAfter: activeMessageDestructionTimeoutValue?.rawValue) } catch { throw AppendMessageError.failedToProcessMessageData(reason: error.localizedDescription) } guard !message.isRestricted else { throw AppendMessageError.fileSharingIsRestricted } message.sender = ZMUser.selfUser(in: moc) if expires { message.setExpirationDate() } append(message) unarchiveIfNeeded() prepareMessage(message) message.updateCategoryCache() message.prepareToSend() return message } /// Appends a new message to the conversation. /// /// - Parameters: /// - genericMessage: The generic message that should be appended. /// - expires: Whether the message should expire or tried to be send infinitively. /// - hidden: Whether the message should be hidden in the conversation or not /// /// - Throws: /// - `AppendMessageError` if the message couldn't be appended. @discardableResult public func appendClientMessage(with genericMessage: GenericMessage, expires: Bool = true, hidden: Bool = false, configure: ((ZMClientMessage) -> Void)? = nil) throws -> ZMClientMessage { guard let moc = managedObjectContext else { throw AppendMessageError.missingManagedObjectContext } guard let nonce = UUID(uuidString: genericMessage.messageID) else { throw AppendMessageError.malformedNonce } let message = ZMClientMessage(nonce: nonce, managedObjectContext: moc) configure?(message) do { try message.setUnderlyingMessage(genericMessage) } catch { moc.delete(message) throw AppendMessageError.failedToProcessMessageData(reason: error.localizedDescription) } do { try append(message, expires: expires, hidden: hidden) } catch { moc.delete(message) throw error } return message } /// Appends a new message to the conversation. /// /// - Parameters: /// - message: The message that should be appended. /// - expires: Whether the message should expire or tried to be send infinitively. /// - hidden: Whether the message should be hidden in the conversation or not /// /// - Throws: /// - `AppendMessageError` if the message couldn't be appended. private func append(_ message: ZMClientMessage, expires: Bool, hidden: Bool) throws { guard let moc = managedObjectContext else { throw AppendMessageError.missingManagedObjectContext } message.sender = ZMUser.selfUser(in: moc) if expires { message.setExpirationDate() } if hidden { message.hiddenInConversation = self } else { append(message) unarchiveIfNeeded() message.updateCategoryCache() message.prepareToSend() } } } @objc extension ZMConversation { // MARK: - Objective-C compability methods @discardableResult @objc(appendMessageWithText:) public func _appendText(content: String) -> ZMConversationMessage? { return try? appendText(content: content) } @discardableResult @objc(appendMessageWithText:fetchLinkPreview:) public func _appendText(content: String, fetchLinkPreview: Bool) -> ZMConversationMessage? { return try? appendText(content: content, fetchLinkPreview: fetchLinkPreview) } @discardableResult @objc(appendText:mentions:fetchLinkPreview:nonce:) public func _appendText(content: String, mentions: [Mention], fetchLinkPreview: Bool, nonce: UUID) -> ZMConversationMessage? { return try? appendText(content: content, mentions: mentions, fetchLinkPreview: fetchLinkPreview, nonce: nonce) } @discardableResult @objc(appendText:mentions:replyingToMessage:fetchLinkPreview:nonce:) public func _appendText(content: String, mentions: [Mention], replyingTo quotedMessage: ZMConversationMessage?, fetchLinkPreview: Bool, nonce: UUID) -> ZMConversationMessage? { return try? appendText(content: content, mentions: mentions, replyingTo: quotedMessage, fetchLinkPreview: fetchLinkPreview, nonce: nonce) } @discardableResult @objc(appendKnock) public func _appendKnock() -> ZMConversationMessage? { return try? appendKnock() } @discardableResult @objc(appendMessageWithLocationData:) public func _appendLocation(with locationData: LocationData) -> ZMConversationMessage? { return try? appendLocation(with: locationData) } @discardableResult @objc(appendMessageWithImageData:) public func _appendImage(from imageData: Data) -> ZMConversationMessage? { return try? appendImage(from: imageData) } @discardableResult @objc(appendImageFromData:nonce:) public func _appendImage(from imageData: Data, nonce: UUID) -> ZMConversationMessage? { return try? appendImage(from: imageData, nonce: nonce) } @discardableResult @objc(appendImageAtURL:nonce:) public func _appendImage(at URL: URL, nonce: UUID) -> ZMConversationMessage? { return try? appendImage(at: URL, nonce: nonce) } @discardableResult @objc(appendMessageWithFileMetadata:) public func _appendFile(with fileMetadata: ZMFileMetadata) -> ZMConversationMessage? { return try? appendFile(with: fileMetadata) } @discardableResult @objc(appendFile:nonce:) public func _appendFile(with fileMetadata: ZMFileMetadata, nonce: UUID) -> ZMConversationMessage? { return try? appendFile(with: fileMetadata, nonce: nonce) } }
a8adc221076a0d2d75c10f0c9a9bb4b0
35.701099
128
0.613929
false
false
false
false
MTTHWBSH/Short-Daily-Devotions
refs/heads/master
Pods/Kanna/Sources/libxmlParserOption.swift
mit
2
/**@file libxmlParserOption.swift Kanna Copyright (c) 2015 Atsushi Kiwaki (@_tid_) 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 /* Libxml2HTMLParserOptions */ public struct Libxml2HTMLParserOptions : OptionSet { public typealias RawValue = UInt private var value: UInt = 0 init(_ value: UInt) { self.value = value } private init(_ opt: htmlParserOption) { self.value = UInt(opt.rawValue) } public init(rawValue value: UInt) { self.value = value } public init(nilLiteral: ()) { self.value = 0 } public static var allZeros: Libxml2HTMLParserOptions { return .init(0) } static func fromMask(raw: UInt) -> Libxml2HTMLParserOptions { return .init(raw) } public var rawValue: UInt { return self.value } public static let STRICT = Libxml2HTMLParserOptions(0) public static let RECOVER = Libxml2HTMLParserOptions(HTML_PARSE_RECOVER) public static let NODEFDTD = Libxml2HTMLParserOptions(HTML_PARSE_NODEFDTD) public static let NOERROR = Libxml2HTMLParserOptions(HTML_PARSE_NOERROR) public static let NOWARNING = Libxml2HTMLParserOptions(HTML_PARSE_NOWARNING) public static let PEDANTIC = Libxml2HTMLParserOptions(HTML_PARSE_PEDANTIC) public static let NOBLANKS = Libxml2HTMLParserOptions(HTML_PARSE_NOBLANKS) public static let NONET = Libxml2HTMLParserOptions(HTML_PARSE_NONET) public static let NOIMPLIED = Libxml2HTMLParserOptions(HTML_PARSE_NOIMPLIED) public static let COMPACT = Libxml2HTMLParserOptions(HTML_PARSE_COMPACT) public static let IGNORE_ENC = Libxml2HTMLParserOptions(HTML_PARSE_IGNORE_ENC) } /* Libxml2XMLParserOptions */ public struct Libxml2XMLParserOptions: OptionSet { public typealias RawValue = UInt private var value: UInt = 0 init(_ value: UInt) { self.value = value } private init(_ opt: xmlParserOption) { self.value = UInt(opt.rawValue) } public init(rawValue value: UInt) { self.value = value } public init(nilLiteral: ()) { self.value = 0 } public static var allZeros: Libxml2XMLParserOptions { return .init(0) } static func fromMask(raw: UInt) -> Libxml2XMLParserOptions { return .init(raw) } public var rawValue: UInt { return self.value } public static let STRICT = Libxml2XMLParserOptions(0) public static let RECOVER = Libxml2XMLParserOptions(XML_PARSE_RECOVER) public static let NOENT = Libxml2XMLParserOptions(XML_PARSE_NOENT) public static let DTDLOAD = Libxml2XMLParserOptions(XML_PARSE_DTDLOAD) public static let DTDATTR = Libxml2XMLParserOptions(XML_PARSE_DTDATTR) public static let DTDVALID = Libxml2XMLParserOptions(XML_PARSE_DTDVALID) public static let NOERROR = Libxml2XMLParserOptions(XML_PARSE_NOERROR) public static let NOWARNING = Libxml2XMLParserOptions(XML_PARSE_NOWARNING) public static let PEDANTIC = Libxml2XMLParserOptions(XML_PARSE_PEDANTIC) public static let NOBLANKS = Libxml2XMLParserOptions(XML_PARSE_NOBLANKS) public static let SAX1 = Libxml2XMLParserOptions(XML_PARSE_SAX1) public static let XINCLUDE = Libxml2XMLParserOptions(XML_PARSE_XINCLUDE) public static let NONET = Libxml2XMLParserOptions(XML_PARSE_NONET) public static let NODICT = Libxml2XMLParserOptions(XML_PARSE_NODICT) public static let NSCLEAN = Libxml2XMLParserOptions(XML_PARSE_NSCLEAN) public static let NOCDATA = Libxml2XMLParserOptions(XML_PARSE_NOCDATA) public static let NOXINCNODE = Libxml2XMLParserOptions(XML_PARSE_NOXINCNODE) public static let COMPACT = Libxml2XMLParserOptions(XML_PARSE_COMPACT) public static let OLD10 = Libxml2XMLParserOptions(XML_PARSE_OLD10) public static let NOBASEFIX = Libxml2XMLParserOptions(XML_PARSE_NOBASEFIX) public static let HUGE = Libxml2XMLParserOptions(XML_PARSE_HUGE) public static let OLDSAX = Libxml2XMLParserOptions(XML_PARSE_OLDSAX) public static let IGNORE_ENC = Libxml2XMLParserOptions(XML_PARSE_IGNORE_ENC) public static let BIG_LINES = Libxml2XMLParserOptions(XML_PARSE_BIG_LINES) }
c42e90e9d9b2b51509511ffaf1e588d0
54.206522
85
0.758417
false
false
false
false
GoodMorningCody/EverybodySwift
refs/heads/master
WeatherDemo/WeatherDemo/WeatherViewController.swift
mit
1
// // WeatherViewController.swift // WeatherDemo // // Created by Cody on 2015. 1. 11.. // Copyright (c) 2015년 TIEKLE. All rights reserved. // import UIKit import CoreLocation class WeatherViewController: UIViewController, CLLocationManagerDelegate { var locationManager = CLLocationManager() var currentLocation : CLLocation? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. updateCurrentLocation() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateCurrentLocation() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyKilometer if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined && locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization")) == true { locationManager.requestWhenInUseAuthorization() } locationManager.startUpdatingLocation() } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { currentLocation = locations[locations.count - 1] as? CLLocation manager.stopUpdatingLocation() getWehaterButton?.enabled = true } @IBOutlet var getWehaterButton : UIButton? @IBOutlet var gettedWehaterTextView : UITextView? @IBAction func touchedGetWeatherButton(sender: UIButton) { let urlString = "http://api.openweathermap.org/data/2.5/weather?lat=\(currentLocation!.coordinate.latitude)&lon=\(currentLocation!.coordinate.longitude)" if let url = NSURL(string: urlString) { let request = NSURLRequest(URL: url) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.currentQueue(), completionHandler: { (response, data, error) -> Void in let jsonObject : AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) if let weather = jsonObject?["weather"] as? NSArray { if weather.count>0 { self.gettedWehaterTextView?.text = weather[0]["description"] as? NSString return } } self.gettedWehaterTextView?.text = "날씨 정보를 가져오지 못했습니다." }) } } }
0a0349eb6590da77764d4488615fd477
37.738462
180
0.661239
false
false
false
false
jad6/CV
refs/heads/master
Swift/Jad's CV/Sections/ExperienceDetail/ExperienceDetailView.swift
bsd-3-clause
1
// // ExperienceDetailView.swift // Jad's CV // // Created by Jad Osseiran on 24/07/2014. // Copyright (c) 2014 Jad. All rights reserved. // import UIKit class ExperienceDetailView: DynamicTypeView { //MARK:- Constants private struct LayoutConstants { struct Padding { static let top: CGFloat = 20.0 static let betweenVerticalLarge: CGFloat = 15.0 static let betweenVerticalSmall: CGFloat = 3.0 } static let imagveViewSize = CGSize(width: 70.0, height: 70.0) static let imageViewMaskingRadius: CGFloat = 18.0 } //MARK:- Properties let organisationImageView = UIImageView() let positionLabel = UILabel() let organisationLabel = UILabel() let dateLabel = UILabel() let textView = FormattedTextView() //MARK:- Init required init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) self.organisationImageView.frame.size = LayoutConstants.imagveViewSize self.organisationImageView.maskToRadius(LayoutConstants.imageViewMaskingRadius) self.addSubview(self.organisationImageView) self.addSubview(self.positionLabel) self.addSubview(self.organisationLabel) self.addSubview(self.dateLabel) if UIDevice.isPad() { self.textView.textContainerInset = UIEdgeInsets(top: 0.0, left: 44.0, bottom: 0.0, right: 44.0) } else { self.textView.textContainerInset = UIEdgeInsets(top: 0.0, left: 20.0, bottom: 0.0, right: 20.0) } self.addSubview(self.textView) self.backgroundColor = UIColor.backgroundGrayColor() } convenience init() { self.init(frame: CGRectZero) } //MARK:- Layout override func layoutSubviews() { super.layoutSubviews() organisationImageView.frame.origin.y = LayoutConstants.Padding.top organisationImageView.centerHorizontallyWithReferenceRect(self.bounds) positionLabel.frame.size = positionLabel.sizeThatFits(bounds.size).ceilSize positionLabel.frame.origin.y = organisationImageView.frame.maxY + LayoutConstants.Padding.betweenVerticalLarge positionLabel.centerHorizontallyWithReferenceRect(self.bounds) organisationLabel.frame.size = organisationLabel.sizeThatFits(bounds.size).ceilSize organisationLabel.frame.origin.y = positionLabel.frame.maxY + LayoutConstants.Padding.betweenVerticalSmall organisationLabel.centerHorizontallyWithReferenceRect(self.bounds) dateLabel.frame.size = dateLabel.sizeThatFits(bounds.size).ceilSize dateLabel.frame.origin.y = organisationLabel.frame.maxY + LayoutConstants.Padding.betweenVerticalSmall dateLabel.centerHorizontallyWithReferenceRect(self.bounds) textView.frame.origin.y = dateLabel.frame.maxY + LayoutConstants.Padding.betweenVerticalLarge textView.frame.size.width = bounds.size.width textView.frame.size.height = bounds.size.height - textView.frame.origin.y } //MARK:- Dynamic type override func reloadDynamicTypeContent() { positionLabel.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleHeadline) organisationLabel.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleSubheadline) dateLabel.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleSubheadline) textView.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleBody) } }
8b5de3c21cdaf228186f1b277cdeabbc
36.428571
118
0.693566
false
false
false
false
beyerss/CalendarKit
refs/heads/master
CalendarKit/Month.swift
mit
1
// // Month.swift // CalendarKit // // Created by Steven Beyers on 6/7/15. // Copyright (c) 2015 Beyers Apps, LLC. All rights reserved. // import UIKit private let monthFormatter = MonthFormatter() internal class Month: NSObject { var date: NSDate /** * Creates a Month object for the date given * * @param monthDate Any date in the month that needs to be created **/ required init(monthDate: NSDate) { date = monthDate } /** * Returns the name of the month that this object represents. * * @return The string representation of the current month **/ func monthName() -> String { return monthFormatter.formatter.stringFromDate(date) } /** * Will determine if the current month is equal to the object specified. * The items will be equal if the following conditions are met: * 1) The object specified is a Month object * 2) The month of the Month object specified is the same as the current Month's month * 3) The year of the Month object specified is the same as the current Month's year * * @param object AnyObject that needs to be compared against the current Month * @return A Bool. True if the two objects are equal, otherwise false. **/ override func isEqual(object: AnyObject?) -> Bool { if let otherMonth = object as? Month { let myComponents = NSCalendar.currentCalendar().components([.Month, .Year], fromDate: date) let otherComponents = NSCalendar.currentCalendar().components([.Month, .Year], fromDate: otherMonth.date) if (myComponents.month == otherComponents.month && myComponents.year == otherComponents.year) { return true } } return false } /** Sets the format used when getting the month name. */ func useMonthFormat(format: String) { monthFormatter.formatter.dateFormat = format } } /** * This extension will give us class methods to create a month based off of a previous month **/ extension Month { /** * Convenience initializer so that a month can be created based * on another month. * * @param otherMonth The base month used as a reference to create a new Month * @param offset The number of months between the otherMonth and the desired month **/ convenience init(otherMonth: Month, offsetMonths offset: Int) { let date = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: offset, toDate: otherMonth.date, options: [])! self.init(monthDate: date) } } /** * This extension will provide helpers for determining the correct date **/ extension Month { /** * This returns the days in the current month **/ func numberOfDaysInMonth() -> Int { let calendar = NSCalendar.currentCalendar() var components = calendar.components([.Day, .Month, .Year], fromDate: date) components.day = 1 let firstDayDate = calendar.dateFromComponents(components) let delta : NSDateComponents = NSDateComponents() delta.month = 1 delta.day = -1 let newDate = calendar.dateByAddingComponents(delta, toDate: firstDayDate!, options: []) if let lastDayDate = newDate { components = calendar.components(.Day, fromDate: lastDayDate) return components.day } return -1 } /** * This returns the first day of the week as an integer value from 0-6 (Sunday - Saturday) **/ func firstDayOfWeek() -> Int { let calendar = NSCalendar.currentCalendar() var components = calendar.components([.Day, .Month, .Year, .Weekday], fromDate: date) components.day = 1 components = calendar.components([.Day, .Month, .Year, .Weekday], fromDate: calendar.dateFromComponents(components)!) var day = components.weekday day -= 1 return day } /** * This returns the number of weeks for this month **/ func weeksInMonth() -> Int { let numberOfDays = numberOfDaysInMonth() let firstDay = firstDayOfWeek() let totalDaysNeeded = numberOfDays + firstDay var numberOfWeeks = totalDaysNeeded / 7 let remainder = totalDaysNeeded % 7 if (remainder > 0) { numberOfWeeks += 1 } return numberOfWeeks } func getDateForCell(indexPath path: NSIndexPath) -> NSDate { let calendar = NSCalendar.currentCalendar() let components = calendar.components([.Day, .Month, .Year, .Weekday], fromDate: date) var dayOfMonth = path.row let firstDay = firstDayOfWeek() // subtract the offset to account for the first day of the week dayOfMonth -= (firstDay - 1) var dateToReturn: NSDate? components.day = dayOfMonth // The date is in the current month let newDate = calendar.dateFromComponents(components) dateToReturn = newDate if let returnDate = dateToReturn { return returnDate } else { // If I was not able to determine the date I'm just going to return toay's date return date } } func isDateOutOfMonth(testDate: NSDate) -> Bool { let calendar = NSCalendar.currentCalendar() let components = calendar.components([.Month], fromDate: testDate) let currentComponents = calendar.components([.Month], fromDate: date) if (components.month == currentComponents.month) { return false } return true } } /** This is a singleton so that we only ever have to create one month formatter */ private class MonthFormatter { lazy var formatter: NSDateFormatter = { let newFormatter = NSDateFormatter() newFormatter.dateFormat = "MMMM" return newFormatter }() }
edd33c385c7adc5287ad2238e299a638
30.242268
126
0.62102
false
false
false
false
sseitov/v-Chess-Swift
refs/heads/master
v-Chess/MainController.swift
gpl-3.0
1
// // MainController.swift // WD Content // // Created by Сергей Сейтов on 24.02.17. // Copyright © 2017 V-Channel. All rights reserved. // import UIKit import AMSlideMenu class MainController: AMSlideMenuMainViewController, AMSlideMenuDelegate { private var rightMenuIsOpened = false override open var supportedInterfaceOrientations : UIInterfaceOrientationMask { return .all } override func viewDidLoad() { super.viewDidLoad() self.isInitialStart = false self.slideMenuDelegate = self } func disableSlider() { self.disableSlidePanGestureForRightMenu() self.disableSlidePanGestureForLeftMenu() } override func primaryMenu() -> AMPrimaryMenu { return AMPrimaryMenuRight } // MARK: - Right menu override func initialIndexPathForRightMenu() -> IndexPath! { if let choice = UserDefaults.standard.value(forKey: "lastMenuChoice") as? Int { return IndexPath(row: choice, section: 0) } else { return IndexPath(row: 0, section: 0) } } override func segueIdentifierForIndexPath(inRightMenu indexPath: IndexPath!) -> String! { switch indexPath.row { case 1: return "archive" case 2: return "community" default: return "play" } } override func rightMenuWidth() -> CGFloat { return IS_PAD() ? 320 : 260 } override func deepnessForRightMenu() -> Bool { return true } override func maxDarknessWhileRightMenu() -> CGFloat { return 0.5 } // MARK: - Common override func configureSlideLayer(_ layer: CALayer!) { layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 1 layer.shadowOffset = CGSize(width: 0, height: 0) layer.shadowRadius = 5 layer.masksToBounds = false layer.shadowPath = UIBezierPath(rect: self.view.layer.bounds).cgPath } override func openAnimationCurve() -> UIViewAnimationOptions { return .curveEaseOut } override func closeAnimationCurve() -> UIViewAnimationOptions { return .curveEaseOut } private func rightMenuFrame() -> CGRect { return CGRect(x: self.view.bounds.size.width - rightMenuWidth(), y: 0, width: rightMenuWidth(), height: self.view.bounds.size.height) } override func openRightMenu(animated: Bool) { super.openRightMenu(animated: animated) self.rightMenu.view.frame = rightMenuFrame() } func rightMenuWillOpen() { rightMenuIsOpened = true } func rightMenuDidClose() { rightMenuIsOpened = false } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) if rightMenuIsOpened { self.currentActiveNVC.view.alpha = 0 coordinator.animate(alongsideTransition: { (context: UIViewControllerTransitionCoordinatorContext) in self.rightMenu.view.frame = self.rightMenuFrame() }) { (context: UIViewControllerTransitionCoordinatorContext) in UIView.animate(withDuration: 0.2, animations: { self.currentActiveNVC.view.alpha = 1 }) } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
3c649fd2806aab1d9d1cff19f978e0fa
28.78125
141
0.633526
false
false
false
false
JGiola/swift
refs/heads/main
benchmark/single-source/ArrayLiteral.swift
apache-2.0
10
//===--- ArrayLiteral.swift -----------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks performance of creating array from literal and array value // propagation. // It is reported to be slow: <rdar://problem/17297449> import TestsUtils public let benchmarks = [ BenchmarkInfo(name: "ArrayLiteral2", runFunction: run_ArrayLiteral, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayValueProp", runFunction: run_ArrayValueProp, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayValueProp2", runFunction: run_ArrayValueProp2, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayValueProp3", runFunction: run_ArrayValueProp3, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "ArrayValueProp4", runFunction: run_ArrayValueProp4, tags: [.validation, .api, .Array]), ] @inline(never) func makeArray() -> [Int] { return [1,2,3] } @inline(never) public func run_ArrayLiteral(_ n: Int) { for _ in 1...10000*n { blackHole(makeArray()) } } @inline(never) func addLiteralArray() -> Int { let arr = [1, 2, 3] return arr[0] + arr[1] + arr[2] } @inline(never) public func run_ArrayValueProp(_ n: Int) { var res = 123 for _ in 1...10000*n { res += addLiteralArray() res -= addLiteralArray() } check(res == 123) } @inline(never) func addLiteralArray2() -> Int { let arr = [1, 2, 3] var r = 0 for elt in arr { r += elt } return r } @inline(never) func addLiteralArray3() -> Int { let arr = [1, 2, 3] var r = 0 for i in 0..<arr.count { r += arr[i] } return r } @inline(never) func addLiteralArray4() -> Int { let arr = [1, 2, 3] var r = 0 for i in 0..<3 { r += arr[i] } return r } @inline(never) public func run_ArrayValueProp2(_ n: Int) { var res = 123 for _ in 1...10000*n { res += addLiteralArray2() res -= addLiteralArray2() } check(res == 123) } @inline(never) public func run_ArrayValueProp3(_ n: Int) { var res = 123 for _ in 1...10000*n { res += addLiteralArray3() res -= addLiteralArray3() } check(res == 123) } @inline(never) public func run_ArrayValueProp4(_ n: Int) { var res = 123 for _ in 1...10000*n { res += addLiteralArray4() res -= addLiteralArray4() } check(res == 123) }
8274fd5537e3d7a25f8ae02df9e86681
22.946903
110
0.616408
false
false
false
false
cuappdev/podcast-ios
refs/heads/master
old/Podcast/PlayButton.swift
mit
1
// // PlayButton.swift // Podcast // // Created by Kevin Greer on 3/11/17. // Copyright © 2017 Cornell App Development. All rights reserved. // import UIKit class PlayButton: Button { let buttonTitlePadding: CGFloat = 7 override init() { super.init() setImage(#imageLiteral(resourceName: "play_feed_icon"), for: .normal) setImage(#imageLiteral(resourceName: "play_feed_icon_selected"), for: .selected) setImage(#imageLiteral(resourceName: "error_icon"), for: .disabled) setTitle("Play", for: .normal) setTitle("Playing", for: .selected) setTitle("", for: .disabled) titleLabel?.font = ._12RegularFont() contentHorizontalAlignment = .left setTitleColor(.offBlack, for: .normal) setTitleColor(.sea, for: .selected) titleEdgeInsets = UIEdgeInsets(top: 0, left: buttonTitlePadding, bottom: 0, right: 0) } func configure(for episode: Episode) { if let _ = episode.audioURL { isEnabled = true isSelected = episode.isPlaying titleEdgeInsets = UIEdgeInsets(top: 0, left: buttonTitlePadding, bottom: 0, right: 0) } else { titleEdgeInsets = .zero isEnabled = false isUserInteractionEnabled = false titleLabel?.numberOfLines = 2 } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
c04e7bed44493cca895b4596ca85aa5b
31.130435
97
0.61705
false
false
false
false
ibrdrahim/TopBarMenu
refs/heads/master
TopBarMenu/View1.swift
mit
1
// // View1.swift // TopBarMenu // // Created by ibrahim on 11/21/16. // Copyright © 2016 Indosytem. All rights reserved. // import UIKit class View1: UIView { var contentView : UIView? override init(frame: CGRect) { super.init(frame: frame) xibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetup() // additional option } func xibSetup() { contentView = loadViewFromNib() // use bounds not frame or it'll be offset contentView!.frame = bounds // Make the view stretch with containing view contentView!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] // Adding custom subview on top of our view (over any custom drawing > see note below) addSubview(contentView!) } func loadViewFromNib() -> UIView! { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView return view } }
97fb52764424c4265274988ed465f4f1
23.86
109
0.589702
false
false
false
false
newlix/swift-syncable-api
refs/heads/master
Tests/NSJSONSerializationTests.swift
mit
1
import XCTest import LessMock import SyncableAPI import RealmSwift class JSONSerializationTests: XCTestCase { override func setUp() { super.setUp() clearBeforeTesting() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSkipUnderscore() { let fake = Fake() fake._hidden = "not show" let json = NSJSONSerialization.JSONObjectWithRealmObject(fake) XCTAssertNil(json["_hidden"]) } func testReferenceClassId() { let fake = Fake() fake.id = "567" let parent = Parent() parent.fake = fake let json = NSJSONSerialization.JSONObjectWithRealmObject(parent) let fakeId = json["fakeId"] as! String XCTAssertEqual(fakeId, "567") } func testAttribute() { let fake = Fake() fake.updateTimestamp = 0.02 let json = NSJSONSerialization.JSONObjectWithRealmObject(fake) let updateTimestamp = json["updateTimestamp"] as! Double XCTAssertEqualWithAccuracy(updateTimestamp, 0.02, accuracy: 0.001) } }
67999e6633ba15520794c3df5e1a3967
26.840909
111
0.626939
false
true
false
false
abertelrud/swift-package-manager
refs/heads/main
Tests/PackagePluginAPITests/PathTests.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import PackagePlugin import XCTest class PathAPITests: XCTestCase { func testBasics() throws { let path = Path("/tmp/file.foo") XCTAssertEqual(path.lastComponent, "file.foo") XCTAssertEqual(path.stem, "file") XCTAssertEqual(path.extension, "foo") XCTAssertEqual(path.removingLastComponent(), Path("/tmp")) } func testEdgeCases() throws { let path = Path("/tmp/file.foo") XCTAssertEqual(path.removingLastComponent().removingLastComponent().removingLastComponent(), Path("/")) } }
759265ab8a9275ead08b895735aafe4e
34.366667
111
0.589067
false
true
false
false
pupboss/vfeng
refs/heads/master
vfeng/ShowDetailViewController.swift
gpl-2.0
1
// // ShowDetailViewController.swift // vfeng // // Created by Li Jie on 10/25/15. // Copyright © 2015 PUPBOSS. All rights reserved. // import UIKit class ShowDetailViewController: UIViewController { var detailArr: Array<String> = [] @IBOutlet weak var imgView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var rewardLabel: UILabel! @IBOutlet weak var infoLabel: UITextView! override func viewDidLoad() { super.viewDidLoad() self.imgView.image = UIImage.init(data: NSData.init(contentsOfURL: NSURL(string: self.detailArr[0])!)!) self.nameLabel.text = detailArr[1] self.rewardLabel.text = detailArr[3] self.infoLabel.text = detailArr[2] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
98594141397049f8ab672b8c446c42bb
23.236842
111
0.65798
false
false
false
false
chicio/RangeUISlider
refs/heads/master
Source/Logic/KnobGestureManager.swift
mit
1
// // KnobGestureManager.swift // RangeUISlider // // Created by Fabrizio Duroni on 03/02/21. // 2021 Fabrizio Duroni. // import UIKit class KnobGestureManager { private unowned let bar: Bar private unowned let knobs: Knobs private unowned let knobGestureManagerDelegate: KnobGestureManagerDelegate private let stepCalculator: StepCalculator init(bar: Bar, knobs: Knobs, knobGestureManagerDelegate: KnobGestureManagerDelegate) { self.bar = bar self.knobs = knobs self.knobGestureManagerDelegate = knobGestureManagerDelegate self.stepCalculator = StepCalculator() } func moveLeftKnob(gesture: GestureData) { recognize(gesture: gesture, updateKnob: updateLeftKnobPositionUsing) } func moveRightKnob(gesture: GestureData) { recognize(gesture: gesture, updateKnob: updateRightKnobPositionUsing) } private func recognize(gesture: GestureData, updateKnob: (GestureData) -> Void) { if gesture.gestureRecognizer.state == .began { rangeSelectionStartedForKnobUsing(gesture: gesture, updateKnob: updateKnob) } if gesture.gestureRecognizer.state == .changed { updateKnobAndRangeUsing(gesture: gesture, updateKnob: updateKnob) } if gesture.gestureRecognizer.state == .ended { knobGestureManagerDelegate.rangeSelectionFinished(userInteraction: true) } } private func rangeSelectionStartedForKnobUsing(gesture: GestureData, updateKnob: (GestureData) -> Void) { updateKnob(gesture) knobGestureManagerDelegate.rangeChangeStarted() } private func updateKnobAndRangeUsing(gesture: GestureData, updateKnob: (GestureData) -> Void) { updateKnob(gesture) knobGestureManagerDelegate.rangeSelectionUpdate() } private func updateLeftKnobPositionUsing(gesture: GestureData) { let userInterfaceDirection = UIView.userInterfaceLayoutDirection(for: gesture.semanticContentAttribute) if userInterfaceDirection == UIUserInterfaceLayoutDirection.rightToLeft { let positionForKnob = bar.frame.width - positionForKnobGiven( xLocationInBar: gesture.gestureRecognizer.location(in: bar).x, gesture: gesture ) let positionRightKnob = -1 * knobs.rightKnob.xPositionConstraint.constant if positionForKnob >= 0 && (bar.frame.width - positionForKnob) >= positionRightKnob { knobs.leftKnob.xPositionConstraint.constant = positionForKnob } } else { let positionForKnob = positionForKnobGiven( xLocationInBar: gesture.gestureRecognizer.location(in: bar).x, gesture: gesture ) let positionRightKnob = bar.frame.width + knobs.rightKnob.xPositionConstraint.constant if positionForKnob >= 0 && positionForKnob <= positionRightKnob { knobs.leftKnob.xPositionConstraint.constant = positionForKnob } } } private func updateRightKnobPositionUsing(gesture: GestureData) { let userInterfaceDirection = UIView.userInterfaceLayoutDirection(for: gesture.semanticContentAttribute) if userInterfaceDirection == UIUserInterfaceLayoutDirection.rightToLeft { let xLocationInBar = gesture.gestureRecognizer.location(in: bar).x let positionForKnob = -1 * positionForKnobGiven( xLocationInBar: xLocationInBar, gesture: gesture ) if positionForKnob <= 0 && xLocationInBar <= (bar.frame.width - knobs.leftKnob.xPositionConstraint.constant) { knobs.rightKnob.xPositionConstraint.constant = positionForKnob } } else { let xLocationInBar = gesture.gestureRecognizer.location(in: bar).x let positionForKnob = positionForKnobGiven( xLocationInBar: xLocationInBar - bar.frame.width, gesture: gesture ) if positionForKnob <= 0 && xLocationInBar >= knobs.leftKnob.xPositionConstraint.constant { knobs.rightKnob.xPositionConstraint.constant = positionForKnob } } } private func positionForKnobGiven(xLocationInBar: CGFloat, gesture: GestureData) -> CGFloat { let stepWidth = stepCalculator.calculateStepWidth( stepIncrement: gesture.stepIncrement, scale: gesture.scale, barWidth: bar.frame.width ) return (xLocationInBar / stepWidth).rounded(FloatingPointRoundingRule.down) * stepWidth } }
faff4e9e0bb3556b70e2fb5a36071c76
41.678899
111
0.674549
false
false
false
false
jagajithmk/SubmitButton
refs/heads/master
SubmitButton/Classes/SubmitButton.swift
mit
1
// // SubmitButton.swift // // Created by Jagajith M Kalarickal on 02/12/16. // Copyright © 2016 Jagajith M Kalarickal. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and // associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit public enum ButtonState { case ready case loading case finishing case finished } public enum ButtonLoadingType { case continuous case timeLimited } public enum ButtonCompletionStatus { case success case canceled case failed } private struct Constants { static let contextID = "kAnimationIdentifier" static let layerAnimation = "kLayerAnimation" static let cancelButtonTitle = "Cancelled" static let prepareLoadingAnimDuration: TimeInterval = 0.2 static let resetLinesPositionAnimDuration: TimeInterval = 0.2 static let finishLoadingAnimDuration: TimeInterval = 0.3 static let bounceDuration: TimeInterval = 0.3 static let borderWidth: CGFloat = 5 static let minFontSize: CGFloat = 17 static let maxFontSize: CGFloat = 19 static let minOpacity: Float = 0 static let maxOpacity: Float = 1 static let minStrokeEndPosition: CGFloat = 0 static let maxStrokeEndPosition: CGFloat = 1 static let requestDuration: CGFloat = 1.0 static let frequencyUpdate: CGFloat = 0.1 static let borderBounceKeyTime: [NSNumber] = [0, 0.9, 1] static let errorCrossMarkXShift: CGFloat = 15 static let errorCrossMarkYShift: CGFloat = 15 static let cancelButtonTag: Int = 100 static let cancelMarkXShift: CGFloat = 17 static let cancelMarkYShift: CGFloat = 17 static let cancelButtonHeight: CGFloat = 40 static let cancelButtonWidth: CGFloat = 40 } private struct AnimKeys { static let bounds = "bounds" static let backgroundColor = "backgroundColor" static let position = "position" static let lineRotation = "lineRotation" static let transform = "transform" static let borderWidth = "borderWidth" static let opacity = "opacity" static let transformRotationZ = "transform.rotation.z" } enum AnimContext: String { case LoadingStart case LoadingFinishing } public typealias CompletionType = (SubmitButton) -> Void @IBDesignable open class SubmitButton: UIButton { // MARK: - Public variables /// Button loading type open var loadingType: ButtonLoadingType = ButtonLoadingType.timeLimited /// Color of dots and line in loading state @IBInspectable open var dotColor: UIColor = #colorLiteral(red: 0, green: 0.8250309825, blue: 0.6502585411, alpha: 1) /// Color of error button @IBInspectable open var errorColor: UIColor = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1) /// Color of cancelled button state @IBInspectable open var cancelledButtonColor: UIColor = #colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1) /// Line width of the border @IBInspectable open var lineWidth: CGFloat = 3 /// Border Color @IBInspectable open var borderColor: UIColor = #colorLiteral(red: 0, green: 0.8250309825, blue: 0.6502585411, alpha: 1) { didSet { borderLayer.borderColor = borderColor.cgColor } } /// Lines count on loading state open var linesCount: UInt = 2 /// Measure in radians @IBInspectable open var dotLength: CGFloat = 0.1 /// Time for pass one lap @IBInspectable open var velocity: Double = 2 /// Loading center Color @IBInspectable open var loadingCenterColor: UIColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) /// Button background color @IBInspectable open var startBackgroundColor: UIColor! = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) { didSet { layer.backgroundColor = startBackgroundColor.cgColor } } /// Button title color @IBInspectable open var startTitleColor: UIColor! = #colorLiteral(red: 0, green: 0.8250309825, blue: 0.6502585411, alpha: 1) { didSet { setTitleColor(startTitleColor, for: UIControlState()) } } /// Show cancel option while loading @IBInspectable open var cancelEnabled: Bool = false /// Color of error button @IBInspectable open var cancelOptionColor: UIColor = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1) @IBInspectable open var startText: String = "Submit" { didSet { setTitle(startText, for: UIControlState()) } } open var currState: ButtonState { return buttonState } open var frequencyOfUpdate: CGFloat { return Constants.frequencyUpdate } // MARK: - Private Vars fileprivate lazy var borderLayer: CALayer = { let layer = CALayer() layer.borderWidth = Constants.borderWidth layer.borderColor = self.borderColor.cgColor layer.backgroundColor = nil return layer }() fileprivate lazy var progressLayer: CAShapeLayer = { let layer = CAShapeLayer() layer.fillColor = nil layer.strokeColor = self.dotColor.cgColor layer.bounds = self.circleBounds layer.path = UIBezierPath(arcCenter: self.boundsCenter, radius: self.boundsCenter.y - self.lineWidth / 2, startAngle: CGFloat(-M_PI_2), endAngle: 3*CGFloat(M_PI_2), clockwise: true).cgPath layer.strokeEnd = Constants.minStrokeEndPosition layer.lineCap = kCALineCapRound layer.lineWidth = self.lineWidth return layer }() fileprivate lazy var checkMarkLayer: CAShapeLayer = { return self.createCheckMark() }() fileprivate lazy var errorCrossMarkLayer: CAShapeLayer = { return self.createErrorCrossMark() }() fileprivate lazy var cancelLayer: CAShapeLayer = { return self.createCancel() }() fileprivate var buttonState: ButtonState = .ready { didSet { handleButtonState( buttonState ) } } fileprivate var circleBounds: CGRect { var newRect = startBounds newRect?.size.width = startBounds.height return newRect! } fileprivate var boundsCenter: CGPoint { return CGPoint(x: circleBounds.midX, y: circleBounds.midY) } fileprivate var boundsStartCenter: CGPoint { return CGPoint(x: startBounds.midX, y: startBounds.midY) } fileprivate var isCancelEnabled: Bool = false // Constraints for button fileprivate var conWidth: NSLayoutConstraint! fileprivate var conHeight: NSLayoutConstraint! fileprivate var startBounds: CGRect! fileprivate let prepareGroup = DispatchGroup() fileprivate let finishLoadingGroup = DispatchGroup() fileprivate var progress: CGFloat = 0 fileprivate var timer: Timer? fileprivate var taskCompletion: CompletionType? //intiate the update of the progress of progress bar func updateLoadingProgress() { guard progress <= 1 else { timer?.invalidate() self.stopAnimate() progress = 0 return } progress += self.progressPerFrequency self.updateProgress( progress ) } // MARK: - UIButton public override init(frame: CGRect) { super.init(frame: frame) setupCommon() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupCommon() } open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setupCommon() } open override func layoutSubviews() { super.layoutSubviews() if buttonState == .ready { layoutStartBounds() } layer.cornerRadius = bounds.midY } // MARK: - Public Methods //Function to reset button view open func resetToReady() { progress = 0 isCancelEnabled = false buttonState = .ready borderLayer.removeAllAnimations() layer.removeAllAnimations() checkMarkLayer.removeAllAnimations() errorCrossMarkLayer.removeAllAnimations() clearLayerContext() CATransaction.begin() CATransaction.setDisableActions( true ) layer.backgroundColor = startBackgroundColor.cgColor checkMarkLayer.opacity = Constants.minOpacity errorCrossMarkLayer.opacity = Constants.minOpacity borderLayer.borderWidth = Constants.borderWidth borderLayer.borderColor = borderColor.cgColor progressLayer.removeFromSuperlayer() progressLayer.strokeEnd = Constants.minStrokeEndPosition CATransaction.commit() setTitle(startText, for: UIControlState()) setTitleColor(startTitleColor, for: UIControlState()) titleLabel?.layer.opacity = Constants.maxOpacity } open func startAnimate() { if buttonState != .ready { resetToReady() } buttonState = .loading } open func stopAnimate() { guard buttonState != .finishing && buttonState != .finished else { return } buttonState = .finishing } // update of the progress of progress bar open func updateProgress(_ progress: CGFloat) { progressLayer.strokeEnd = progress } open func taskCompletion(completion: @escaping CompletionType) { taskCompletion = completion } lazy var progressPerFrequency: CGFloat = { let progressPerSecond = 1.0 / Constants.requestDuration return CGFloat(progressPerSecond * Constants.frequencyUpdate) }() // MARK: - Selector && Action func touchUpInside(_ sender: SubmitButton) { if self.buttonState != .loading { //*Code to reset buton after submit, comment these if not needed guard !isSelected else { if currState == .finished { resetToReady() isSelected = false } return }//* titleLabel?.font = UIFont.systemFont(ofSize: Constants.minFontSize) guard buttonState != .finished else { return } startAnimate() } } } // MARK: - Private Methods extension SubmitButton { fileprivate func layoutStartBounds() { startBounds = bounds borderLayer.bounds = startBounds borderLayer.cornerRadius = startBounds.midY borderLayer.position = CGPoint(x: startBounds.midX, y: startBounds.midY) } // MARK: Button Setup fileprivate func setupCommon() { addTarget(self, action: #selector(SubmitButton.touchUpInside(_:)), for: .touchUpInside) contentEdgeInsets = UIEdgeInsets(top: 5, left: 20, bottom: 5, right: 20) setupButton() } //Function to setup button properties fileprivate func setupButton() { setTitle(startText, for: UIControlState()) layer.cornerRadius = bounds.midY layer.borderColor = borderColor.cgColor layer.addSublayer( borderLayer ) setTitleColor(startTitleColor, for: UIControlState()) } //Function to remove temporary layer fileprivate func clearLayerContext() { for sublayer in layer.sublayers! { if sublayer == borderLayer || sublayer == checkMarkLayer || sublayer == errorCrossMarkLayer { continue } if sublayer is CAShapeLayer { sublayer.removeFromSuperlayer() } } } // MARK: Managing button state fileprivate func handleButtonState(_ state: ButtonState) { switch state { case .ready: break case .loading: prepareLoadingAnimation({ if self.loadingType == ButtonLoadingType.timeLimited { self.startProgressLoadingAnimation() } else { self.startLoadingAnimation() } }) case .finishing: finishAnimation() case .finished: break } } // MARK: Animations Configuring //add button width animation fileprivate func addButtonWidthAnimation() { let boundAnim = CABasicAnimation(keyPath: AnimKeys.bounds) boundAnim.toValue = NSValue(cgRect: circleBounds) let colorAnim = CABasicAnimation(keyPath: AnimKeys.backgroundColor) colorAnim.toValue = startTitleColor.cgColor let layerGroup = CAAnimationGroup() layerGroup.animations = [boundAnim, colorAnim] layerGroup.duration = Constants.prepareLoadingAnimDuration layerGroup.delegate = self layerGroup.fillMode = kCAFillModeForwards layerGroup.isRemovedOnCompletion = false layerGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) assignContext(.LoadingStart, anim: layerGroup) layer.add(layerGroup, forKey: AnimKeys.bounds) } //add button border position and size animation fileprivate func addBorderPositionAndSizeDecreasingAnimation() { let borderAnim = CABasicAnimation(keyPath: AnimKeys.borderWidth) borderAnim.toValue = lineWidth let borderBounds = CABasicAnimation(keyPath: AnimKeys.bounds) borderBounds.toValue = NSValue(cgRect: circleBounds) let borderPosition = CABasicAnimation(keyPath: AnimKeys.position) borderPosition.toValue = NSValue(cgPoint: boundsCenter) let borderGroup = CAAnimationGroup() borderGroup.animations = [borderAnim, borderBounds, borderPosition] borderGroup.duration = Constants.prepareLoadingAnimDuration borderGroup.delegate = self borderGroup.fillMode = kCAFillModeForwards borderGroup.isRemovedOnCompletion = false borderGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) assignContext(.LoadingStart, anim: borderGroup) borderLayer.add(borderGroup, forKey: nil) } // For adding time for loading fileprivate func addTimerForLimitedTimeLoadingAnimation() { timer?.invalidate() timer = Timer.scheduledTimer(timeInterval: TimeInterval(frequencyOfUpdate), target:self, selector: #selector(SubmitButton.updateLoadingProgress), userInfo: nil, repeats: true) } // animate button to loading state, use completion to start loading animation fileprivate func prepareLoadingAnimation(_ completion: (() -> Void)?) { addButtonWidthAnimation() prepareGroup.enter() addBorderPositionAndSizeDecreasingAnimation() prepareGroup.enter() borderLayer.borderColor = UIColor.lightGray.cgColor isSelected = true if self.loadingType == ButtonLoadingType.timeLimited { addTimerForLimitedTimeLoadingAnimation() } prepareGroup.notify(queue: DispatchQueue.main) { self.borderLayer.borderWidth = self.lineWidth self.borderLayer.bounds = self.circleBounds self.borderLayer.position = self.boundsCenter self.layer.backgroundColor = self.loadingCenterColor.cgColor self.bounds = self.circleBounds self.borderLayer.removeAllAnimations() self.layer.removeAllAnimations() completion?() } titleLabel?.layer.opacity = Constants.minOpacity } // start loading animation, that show progress fileprivate func startProgressLoadingAnimation() { progressLayer.position = boundsCenter layer.insertSublayer(progressLayer, above: borderLayer) if cancelEnabled { addCancelOptionWhileLoading() } } // start default loading fileprivate func startLoadingAnimation() { let arCenter = boundsCenter let radius = circleBounds.midX - lineWidth / 2 var lines = [CAShapeLayer]() let lineOffset: CGFloat = 2 * CGFloat(M_PI) / CGFloat(linesCount) for i in 0..<linesCount { let line = CAShapeLayer() let startAngle = lineOffset * CGFloat(i) line.path = UIBezierPath(arcCenter: arCenter, radius: radius, startAngle: startAngle, endAngle: startAngle + dotLength, clockwise: true).cgPath line.bounds = circleBounds line.strokeColor = dotColor.cgColor line.lineWidth = lineWidth line.fillColor = dotColor.cgColor line.lineCap = kCALineCapRound layer.insertSublayer(line, above: borderLayer) line.position = arCenter lines.append( line ) } let opacityAnim = CABasicAnimation(keyPath: AnimKeys.opacity) opacityAnim.fromValue = 0 let rotation = CABasicAnimation(keyPath: AnimKeys.transformRotationZ) rotation.byValue = NSNumber(value: 2*M_PI as Double) rotation.duration = velocity rotation.repeatCount = Float.infinity for line in lines { line.add(rotation, forKey: AnimKeys.lineRotation) line.add(opacityAnim, forKey: nil) } if cancelEnabled { addCancelOptionWhileLoading() } } // Finishing animation fileprivate func finishAnimation() { layer.masksToBounds = true // lines let lines = layer.sublayers!.filter { guard $0 != checkMarkLayer && $0 != borderLayer else { return false } return $0 is CAShapeLayer } // rotation for lines let rotation = CABasicAnimation(keyPath: AnimKeys.transform) rotation.toValue = NSValue(caTransform3D: CATransform3DIdentity) rotation.duration = Constants.finishLoadingAnimDuration rotation.delegate = self assignContext(.LoadingFinishing, anim: rotation) for line in lines { rotation.fromValue = NSValue(caTransform3D: ((line.presentation() as? CAShapeLayer)?.transform)!) line.add(rotation, forKey: AnimKeys.lineRotation) finishLoadingGroup.enter() } finishLoadingGroup.notify(queue: DispatchQueue.main) { self.taskCompletion!(self) } } //Complete animation based on user input open func completeAnimation(status: ButtonCompletionStatus) { if cancelEnabled && isCancelEnabled && status != .canceled { return } timer?.invalidate() viewWithTag(Constants.cancelButtonTag)?.removeFromSuperview() self.checkMarkAndBoundsAnimation(completionStatus: status) self.clearLayerContext() } //Add button border expanding fileprivate func addButtonBorderIncreasingAnimation() { let proportions: [CGFloat] = [ circleBounds.width / startBounds.width, 0.9, 1] var bounces = [NSValue]() for i in 0..<proportions.count { let rect = CGRect(origin: startBounds.origin, size: CGSize(width: startBounds.width * proportions[i], height: startBounds.height)) bounces.append( NSValue(cgRect: rect) ) } let borderBounce = CAKeyframeAnimation(keyPath: AnimKeys.bounds) borderBounce.keyTimes = Constants.borderBounceKeyTime borderBounce.values = bounces borderBounce.duration = Constants.bounceDuration borderBounce.beginTime = CACurrentMediaTime() + Constants.resetLinesPositionAnimDuration borderBounce.delegate = self borderBounce.isRemovedOnCompletion = false borderBounce.fillMode = kCAFillModeBoth assignContext(.LoadingFinishing, anim: borderBounce) borderLayer.add(borderBounce, forKey: nil) finishLoadingGroup.enter() } //Add button border position animation fileprivate func addButtonBorderPositionUpdationAnimation() { let borderPosition = CABasicAnimation(keyPath: AnimKeys.position) borderPosition.toValue = NSValue(cgPoint: boundsStartCenter) borderPosition.duration = Constants.bounceDuration * Constants.borderBounceKeyTime[1].doubleValue borderPosition.beginTime = CACurrentMediaTime() + Constants.resetLinesPositionAnimDuration borderPosition.delegate = self borderPosition.isRemovedOnCompletion = false borderPosition.fillMode = kCAFillModeBoth assignContext(.LoadingFinishing, anim: borderPosition) borderLayer.add(borderPosition, forKey: nil) finishLoadingGroup.enter() } //Add button bound animation fileprivate func addButtonBoundsAnimation(completionStatus: ButtonCompletionStatus) { let boundsAnim = CABasicAnimation(keyPath: AnimKeys.bounds) boundsAnim.fromValue = NSValue(cgRect: (layer.presentation()!).bounds) boundsAnim.toValue = NSValue(cgRect: startBounds) let colorAnim = CABasicAnimation(keyPath: AnimKeys.backgroundColor) if completionStatus == .success { colorAnim.toValue = dotColor.cgColor colorAnim.fromValue = dotColor.cgColor } else if completionStatus == .failed { colorAnim.toValue = errorColor.cgColor colorAnim.fromValue = errorColor.cgColor } else { colorAnim.toValue = cancelledButtonColor.cgColor colorAnim.fromValue = cancelledButtonColor.cgColor } let layerGroup = CAAnimationGroup() layerGroup.animations = [boundsAnim, colorAnim] layerGroup.duration = Constants.bounceDuration * Constants.borderBounceKeyTime[1].doubleValue layerGroup.beginTime = CACurrentMediaTime() + Constants.resetLinesPositionAnimDuration layerGroup.delegate = self layerGroup.fillMode = kCAFillModeBoth layerGroup.isRemovedOnCompletion = false assignContext(.LoadingFinishing, anim: layerGroup) layer.add(layerGroup, forKey: AnimKeys.bounds) layer.bounds = startBounds finishLoadingGroup.enter() } //Add button expanding animation fileprivate func addButtonPositionAndSizeIncreasingAnimation(status: ButtonCompletionStatus) { addButtonBorderIncreasingAnimation() addButtonBorderPositionUpdationAnimation() addButtonBoundsAnimation(completionStatus: status) } //Add check mark and border expanding animation fileprivate func checkMarkAndBoundsAnimation(completionStatus: ButtonCompletionStatus) { self.borderLayer.opacity = Constants.maxOpacity layer.masksToBounds = false addButtonPositionAndSizeIncreasingAnimation(status: completionStatus) if completionStatus == .success { //Adding tick mark self.layer.backgroundColor = self.dotColor.cgColor borderLayer.borderColor = dotColor.cgColor checkMarkLayer.position = CGPoint(x: layer.bounds.midX, y: layer.bounds.midY) if checkMarkLayer.superlayer == nil { checkMarkLayer.path = pathForMark().cgPath layer.addSublayer( checkMarkLayer ) } } else if completionStatus == .failed { self.layer.backgroundColor = errorColor.cgColor borderLayer.borderColor = errorColor.cgColor errorCrossMarkLayer.position = CGPoint(x: layer.bounds.midX, y: layer.bounds.midY) if errorCrossMarkLayer.superlayer == nil { errorCrossMarkLayer.path = pathForCrossMark(XShift: Constants.errorCrossMarkXShift, YShift: Constants.errorCrossMarkYShift).cgPath layer.addSublayer( errorCrossMarkLayer ) } } else { self.layer.backgroundColor = cancelledButtonColor.cgColor borderLayer.borderColor = cancelledButtonColor.cgColor setTitle(Constants.cancelButtonTitle, for: UIControlState()) setTitleColor(UIColor.white, for: UIControlState()) } finishLoadingGroup.notify(queue: DispatchQueue.main) { UIView.animate(withDuration: 0.5, animations: { if completionStatus == .success { self.checkMarkLayer.opacity = Constants.maxOpacity } else if completionStatus == .failed { self.errorCrossMarkLayer.opacity = Constants.maxOpacity } else { self.titleLabel?.alpha = CGFloat(Constants.maxOpacity) } }) self.buttonState = .finished } } // MARK: Check mark // Configuring check mark layer fileprivate func createMarkLayer() -> CAShapeLayer { // configure layer let layer = CAShapeLayer() layer.bounds = circleBounds layer.opacity = Constants.minOpacity layer.fillColor = nil layer.strokeColor = startBackgroundColor.cgColor layer.lineCap = kCALineCapRound layer.lineJoin = kCALineJoinRound layer.lineWidth = lineWidth return layer } //Function for creating the check mark layer fileprivate func createCheckMark() -> CAShapeLayer { let checkmarkLayer = createMarkLayer() return checkmarkLayer } fileprivate func createErrorCrossMark() -> CAShapeLayer { let crossmarkLayer = createMarkLayer() return crossmarkLayer } fileprivate func createCancel() -> CAShapeLayer { let cancelLayer = createMarkLayer() return cancelLayer } //Function for drawing the check mark fileprivate func pathForMark() -> UIBezierPath { // geometry of the layer let percentShiftY: CGFloat = 0.4 let percentShiftX: CGFloat = -0.2 let firstRadius = 0.5 * circleBounds.midY let lastRadius = 1 * circleBounds.midY let firstAngle = CGFloat(-3 * M_PI_4) let lastAngle = CGFloat(-1 * M_PI_4) var startPoint = CGPoint(x: firstRadius * cos(firstAngle), y: firstRadius * sin(firstAngle)) var midPoint = CGPoint.zero var endPoint = CGPoint(x: lastRadius * cos(lastAngle), y: lastRadius * sin(lastAngle)) let correctedPoint = CGPoint(x: boundsCenter.x + (boundsCenter.x * percentShiftX), y: boundsCenter.y + (boundsCenter.y * percentShiftY)) startPoint.addPoint( correctedPoint ) midPoint.addPoint( correctedPoint ) endPoint.addPoint( correctedPoint ) let path = UIBezierPath() path.move( to: startPoint ) path.addLine( to: midPoint ) path.addLine( to: endPoint ) return path } fileprivate func pathForCrossMark(XShift: CGFloat, YShift: CGFloat) -> UIBezierPath { // geometry for crossmark layer let firstStartPoint = CGPoint(x: XShift, y: YShift) let firstEndPoint = CGPoint(x: circleBounds.maxX - XShift, y: circleBounds.maxY - XShift) let secondStartPoint = CGPoint(x: circleBounds.maxX - XShift, y: circleBounds.minY + YShift) let secondEndPoint = CGPoint(x: circleBounds.minX + XShift, y: circleBounds.maxY - YShift) let path = UIBezierPath() path.move(to: firstStartPoint) path.addLine(to: firstEndPoint) path.move(to: secondStartPoint) path.addLine(to: secondEndPoint) return path } fileprivate func addCancelOptionWhileLoading() { let button = UIButton(type: .custom) button.tag = Constants.cancelButtonTag button.frame = CGRect(x: layer.bounds.midX-Constants.cancelButtonWidth/2, y: layer.bounds.midY-Constants.cancelButtonHeight/2, width: Constants.cancelButtonWidth, height: Constants.cancelButtonHeight) button.layer.cornerRadius = 0.5 * button.bounds.size.width button.clipsToBounds = true let tempLayer = CAShapeLayer() tempLayer.bounds = button.frame tempLayer.fillColor = nil tempLayer.strokeColor = cancelOptionColor.cgColor tempLayer.lineCap = kCALineCapRound tempLayer.lineJoin = kCALineJoinRound tempLayer.lineWidth = lineWidth tempLayer.position = CGPoint(x: button.layer.bounds.midX, y: button.layer.bounds.midY) tempLayer.path = pathForCrossMark(XShift: Constants.cancelMarkXShift, YShift: Constants.cancelMarkYShift).cgPath button.layer.addSublayer( tempLayer ) button.addTarget(self, action: #selector(cancelButtonPressed), for: .touchUpInside) self.addSubview(button) } func cancelButtonPressed() { isCancelEnabled = true completeAnimation(status: .canceled) } fileprivate func assignContext(_ context: AnimContext, anim: CAAnimation ) { anim.setValue(context.rawValue, forKey: Constants.contextID) } fileprivate func assignLayer(_ aLayer: CALayer, anim: CAAnimation) { anim.setValue(aLayer, forKey: Constants.layerAnimation) } } // MARK: - Animation Delegate extension SubmitButton : CAAnimationDelegate { public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { guard flag else { return } guard let contextRawValue = anim.value( forKey: Constants.contextID ) as? String else { return } let context = AnimContext(rawValue: contextRawValue)! switch context { case .LoadingStart: prepareGroup.leave() case .LoadingFinishing: finishLoadingGroup.leave() } } } // MARK: CGPoint customization extension CGPoint { fileprivate mutating func addPoint(_ point: CGPoint) { x += point.x y += point.y } }
f82bf63ff011bce7436992a7401a1a97
41.846047
141
0.657031
false
false
false
false
darthpelo/TimerH2O
refs/heads/develop
TimerH2O/TimerH2O/Views/TH2OWaterPickerView.swift
mit
1
// // TH2OWaterPickerView.swift // TimerH2O // // Created by Alessio Roberto on 29/10/16. // Copyright © 2016 Alessio Roberto. All rights reserved. // import UIKit class TH2OWaterPickerView: UIView { @IBOutlet weak var pickerTitleLabel: UILabel! @IBOutlet weak var doneButton: UIButton! @IBOutlet weak var pickerView: UIPickerView! fileprivate let numbers = (0...9).map {"\($0)"} fileprivate var amount = ["0", "0", "0", "0"] typealias DoneAmount = (Int) -> Void fileprivate var doneAmount: DoneAmount? private var parentView: UIView? @IBAction func doneButtonPressed(_ sender: AnyObject) { guard let amount = Converter.convert(amount: amount) else { return } doneAmount?(amount) } func loadPickerView() -> TH2OWaterPickerView? { guard let view = R.nib.th2OWaterPickerView.firstView(owner: self) else { return nil } view.frame.origin.y = UIScreen.main.bounds.height view.frame.size.width = UIScreen.main.bounds.width return view } func configure(onView: UIView, withCallback: @escaping DoneAmount) { doneAmount = withCallback parentView = onView self.frame.origin.y = onView.frame.size.height pickerTitleLabel.text = R.string.localizable.setsessionWaterpickerTitle() doneButton.setTitle(R.string.localizable.done(), for: .normal) pickerView.selectRow(2, inComponent: 0, animated: false) amount[0] = "2" UIApplication.shared.keyWindow?.addSubview(self) } func isTo(show: Bool) { guard let height = parentView?.frame.size.height else { return } UIView.animate(withDuration: 0.3, animations: { if show { self.frame.origin.y = height - self.frame.size.height } else { self.frame.origin.y = height } }, completion: nil) } } extension TH2OWaterPickerView: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 4 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return numbers.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return numbers[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { amount[component] = numbers[row] } }
c4c88e25a27bcbbe4d8ee1e9b7965540
30.045455
111
0.601757
false
false
false
false
steryokhin/AsciiArtPlayer
refs/heads/master
src/AsciiArtPlayer/AsciiArtPlayer/Classes/Presentation/User Stories/Player/View/PlayerViewController.swift
mit
1
// // PlayerPlayerViewController.swift // AsciiArtPlayer // // Created by Sergey Teryokhin on 20/12/2016. // Copyright © 2016 iMacDev. All rights reserved. // import QorumLogs import AsyncDisplayKit import UIKit import SwiftyAttributes import SnapKit class PlayerViewController: UIViewController, PlayerViewInput { @IBOutlet var scrollView: UIScrollView! var displayNode: ASTextNode! var asciiArtString: NSAttributedString? { didSet { guard let myString = asciiArtString else { return } self.displayNode?.attributedText = myString self.displayNode?.view.frame.size = CGSize(width: myString.size().width + 2.0, height: myString.size().height + 2.0) self.updateMinZoomScaleForSize(size: self.view.bounds.size) } } var output: PlayerViewOutput! // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() output.viewIsReady() } // MARK: PlayerViewInput func setupInitialState() { self.setupUI() } //MARK: UI func setupUI() { let node = ASTextNode() let myAttributedString = NSAttributedString(string: "") node.attributedText = myAttributedString node.isUserInteractionEnabled = true self.scrollView.contentSize = CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height) self.automaticallyAdjustsScrollViewInsets = false self.scrollView.addSubnode(node) node.view.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.centerY.equalToSuperview() make.left.equalToSuperview().offset(5) make.right.equalToSuperview().offset(-5) make.top.equalToSuperview().offset(5) make.bottom.equalToSuperview().offset(-5) } node.backgroundColor = UIColor.white self.displayNode = node self.navigationItem.hidesBackButton = true let backButton = UIBarButtonItem(title: "My Back", style: .plain, target: self, action: #selector(backAction)) self.navigationItem.leftBarButtonItem = backButton } func displayText(_ text: String, font: UIFont) { let string = NSAttributedString(string: text) self.asciiArtString = string.withFont(font) } private func updateMinZoomScaleForSize(size: CGSize) { guard let calculatedSize = self.displayNode.attributedText?.size() else { return } let widthScale = size.width / calculatedSize.width let heightScale = size.height / calculatedSize.height let minScale = min(widthScale, heightScale) scrollView.minimumZoomScale = minScale scrollView.maximumZoomScale = minScale*10 scrollView.zoomScale = minScale } ///MARK: Action func backAction() { self.output.cancelAction() } } extension PlayerViewController: UIScrollViewDelegate { func viewForZooming(in: UIScrollView) -> UIView? { return displayNode.view } }
5b7caf6122113100e107fb7f4c59d60c
28.842593
118
0.630779
false
false
false
false
IvanKalaica/GitHubSearch
refs/heads/master
GitHubSearch/GitHubSearch/Extensions/FormViewController+Extensions.swift
mit
1
// // FormViewController+Extensions.swift // GitHubSearch // // Created by Ivan Kalaica on 21/09/2017. // Copyright © 2017 Kalaica. All rights reserved. // import Eureka typealias TitleValuePair = (title: String, value: String?) extension FormViewController { func set(_ titleValuePair: TitleValuePair, forTag: String) { guard let row = self.form.rowBy(tag: forTag) as? LabelRow else { return } row.value = titleValuePair.value row.title = titleValuePair.title row.reload() } } class EurekaLogoView: UIView { let imageView: UIImageView override init(frame: CGRect) { self.imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 320, height: 130)) self.imageView.image = UIImage(named: "icon_github") self.imageView.autoresizingMask = .flexibleWidth super.init(frame: frame) self.frame = CGRect(x: 0, y: 0, width: 320, height: 130) self.imageView.contentMode = .scaleAspectFit addSubview(self.imageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
c74b96cf75a6b2eeec64416df6886862
29.837838
88
0.662577
false
false
false
false
BeanstalkData/beanstalk-ios-sdk
refs/heads/master
Example/Pods/Alamofire/Source/ServerTrustPolicy.swift
mit
2
// // 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 `ServerTrustPolicy` objects to a given host. public class ServerTrustPolicyManager { /// The dictionary of policies mapped to a particular host. public let policies: [String: ServerTrustPolicy] /** Initializes the `ServerTrustPolicyManager` instance with the given policies. Since different servers and web services can have different leaf certificates, intermediate and even root certficates, 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. - parameter policies: A dictionary of all policies mapped to a particular host. - returns: The new `ServerTrustPolicyManager` instance. */ public init(policies: [String: ServerTrustPolicy]) { self.policies = policies } /** Returns the `ServerTrustPolicy` for the given host if applicable. 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 server trust policy for the given host if found. */ public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { return policies[host] } } // MARK: - extension NSURLSession { private struct AssociatedKeys { static var ManagerKey = "NSURLSession.ServerTrustPolicyManager" } var serverTrustPolicyManager: ServerTrustPolicyManager? { get { return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager } set (manager) { objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } // MARK: - ServerTrustPolicy /** The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust with a given set of criteria to determine whether the server trust is valid and the connection should be made. Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with pinning enabled. - PerformDefaultEvaluation: 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. - PinCertificates: 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. - PinPublicKeys: 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. - DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. - CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust. */ public enum ServerTrustPolicy { case PerformDefaultEvaluation(validateHost: Bool) case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) case DisableEvaluation case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool) // MARK: - Bundle Location /** Returns all certificates within the given bundle with a `.cer` file extension. - parameter bundle: The bundle to search for all `.cer` files. - returns: All certificates within the given bundle. */ public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] { var certificates: [SecCertificate] = [] let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in bundle.pathsForResourcesOfType(fileExtension, inDirectory: nil) }.flatten()) for path in paths { if let certificateData = NSData(contentsOfFile: path), certificate = SecCertificateCreateWithData(nil, certificateData) { certificates.append(certificate) } } return certificates } /** Returns all public keys within the given bundle with a `.cer` file extension. - parameter bundle: The bundle to search for all `*.cer` files. - returns: All public keys within the given bundle. */ public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] { var publicKeys: [SecKey] = [] for certificate in certificatesInBundle(bundle) { if let publicKey = publicKeyForCertificate(certificate) { publicKeys.append(publicKey) } } return publicKeys } // MARK: - Evaluation /** Evaluates whether the server trust is valid for the given host. - parameter serverTrust: The server trust to evaluate. - parameter host: The host of the challenge protection space. - returns: Whether the server trust is valid. */ public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool { var serverTrustIsValid = false switch self { case let .PerformDefaultEvaluation(validateHost): let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) #if swift(>=2.3) SecTrustSetPolicies(serverTrust, policy) #else SecTrustSetPolicies(serverTrust, [policy]) #endif serverTrustIsValid = trustIsValid(serverTrust) case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost): if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) #if swift(>=2.3) SecTrustSetPolicies(serverTrust, policy) #else SecTrustSetPolicies(serverTrust, [policy]) #endif SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates) SecTrustSetAnchorCertificatesOnly(serverTrust, true) serverTrustIsValid = trustIsValid(serverTrust) } else { let serverCertificatesDataArray = certificateDataForTrust(serverTrust) let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates) outerLoop: for serverCertificateData in serverCertificatesDataArray { for pinnedCertificateData in pinnedCertificatesDataArray { if serverCertificateData.isEqualToData(pinnedCertificateData) { serverTrustIsValid = true break outerLoop } } } } case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): var certificateChainEvaluationPassed = true if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) #if swift(>=2.3) SecTrustSetPolicies(serverTrust, policy) #else SecTrustSetPolicies(serverTrust, [policy]) #endif certificateChainEvaluationPassed = trustIsValid(serverTrust) } if certificateChainEvaluationPassed { outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] { for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { if serverPublicKey.isEqual(pinnedPublicKey) { serverTrustIsValid = true break outerLoop } } } } case .DisableEvaluation: serverTrustIsValid = true case let .CustomEvaluation(closure): serverTrustIsValid = closure(serverTrust: serverTrust, host: host) } return serverTrustIsValid } // MARK: - Private - Trust Validation private func trustIsValid(trust: SecTrust) -> Bool { var isValid = false #if swift(>=2.3) var result = SecTrustResultType(rawValue: SecTrustResultType.Invalid.rawValue) let status = SecTrustEvaluate(trust, &result!) #else var result = SecTrustResultType(SecTrustResultType.Invalid) let status = SecTrustEvaluate(trust, &result) #endif if status == errSecSuccess { #if swift(>=2.3) let unspecified = SecTrustResultType(rawValue: SecTrustResultType.Unspecified.rawValue) let proceed = SecTrustResultType(rawValue: SecTrustResultType.Proceed.rawValue) #else let unspecified = SecTrustResultType(SecTrustResultType.Unspecified) let proceed = SecTrustResultType(SecTrustResultType.Proceed) #endif isValid = result == unspecified || result == proceed } return isValid } // MARK: - Private - Certificate Data private func certificateDataForTrust(trust: SecTrust) -> [NSData] { var certificates: [SecCertificate] = [] for index in 0..<SecTrustGetCertificateCount(trust) { if let certificate = SecTrustGetCertificateAtIndex(trust, index) { certificates.append(certificate) } } return certificateDataForCertificates(certificates) } private func certificateDataForCertificates(certificates: [SecCertificate]) -> [NSData] { return certificates.map { SecCertificateCopyData($0) as NSData } } // MARK: - Private - Public Key Extraction private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] { var publicKeys: [SecKey] = [] for index in 0..<SecTrustGetCertificateCount(trust) { if let certificate = SecTrustGetCertificateAtIndex(trust, index), publicKey = publicKeyForCertificate(certificate) { publicKeys.append(publicKey) } } return publicKeys } private static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey? { var publicKey: SecKey? let policy = SecPolicyCreateBasicX509() var trust: SecTrust? let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) if let trust = trust where trustCreationStatus == errSecSuccess { publicKey = SecTrustCopyPublicKey(trust) } return publicKey } }
495b9cb233a0df402151cede9408277b
41.53681
120
0.655297
false
false
false
false
brentsimmons/Evergreen
refs/heads/ios-candidate
iOS/MasterFeed/UpdateSelectionOperation.swift
mit
1
// // UpdateSelectionOperation.swift // NetNewsWire-iOS // // Created by Maurice Parker on 2/22/20. // Copyright © 2020 Ranchero Software. All rights reserved. // import UIKit import RSCore class UpdateSelectionOperation: MainThreadOperation { // MainThreadOperation public var isCanceled = false public var id: Int? public weak var operationDelegate: MainThreadOperationDelegate? public var name: String? = "UpdateSelectionOperation" public var completionBlock: MainThreadOperation.MainThreadOperationCompletionBlock? private var coordinator: SceneCoordinator private var dataSource: MasterFeedDataSource private var tableView: UITableView private var animations: Animations init(coordinator: SceneCoordinator, dataSource: MasterFeedDataSource, tableView: UITableView, animations: Animations) { self.coordinator = coordinator self.dataSource = dataSource self.tableView = tableView self.animations = animations } func run() { if dataSource.snapshot().numberOfItems > 0 { if let indexPath = coordinator.currentFeedIndexPath { CATransaction.begin() CATransaction.setCompletionBlock { self.operationDelegate?.operationDidComplete(self) } tableView.selectRowAndScrollIfNotVisible(at: indexPath, animations: animations) CATransaction.commit() } else { if let indexPath = tableView.indexPathForSelectedRow { if animations.contains(.select) { CATransaction.begin() CATransaction.setCompletionBlock { self.operationDelegate?.operationDidComplete(self) } tableView.deselectRow(at: indexPath, animated: true) CATransaction.commit() } else { tableView.deselectRow(at: indexPath, animated: false) self.operationDelegate?.operationDidComplete(self) } } else { self.operationDelegate?.operationDidComplete(self) } } } else { self.operationDelegate?.operationDidComplete(self) } } }
a80bbdcad1755cf661b345631aa6f910
29.15625
120
0.750777
false
false
false
false
Hendrik44/pi-weather-app
refs/heads/master
Carthage/Checkouts/Charts/Source/Charts/Data/Implementations/Standard/CombinedChartData.swift
apache-2.0
8
// // CombinedChartData.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation open class CombinedChartData: BarLineScatterCandleBubbleChartData { private var _lineData: LineChartData! private var _barData: BarChartData! private var _scatterData: ScatterChartData! private var _candleData: CandleChartData! private var _bubbleData: BubbleChartData! public override init() { super.init() } public override init(dataSets: [IChartDataSet]?) { super.init(dataSets: dataSets) } @objc open var lineData: LineChartData! { get { return _lineData } set { _lineData = newValue notifyDataChanged() } } @objc open var barData: BarChartData! { get { return _barData } set { _barData = newValue notifyDataChanged() } } @objc open var scatterData: ScatterChartData! { get { return _scatterData } set { _scatterData = newValue notifyDataChanged() } } @objc open var candleData: CandleChartData! { get { return _candleData } set { _candleData = newValue notifyDataChanged() } } @objc open var bubbleData: BubbleChartData! { get { return _bubbleData } set { _bubbleData = newValue notifyDataChanged() } } open override func calcMinMax() { _dataSets.removeAll() _yMax = -Double.greatestFiniteMagnitude _yMin = Double.greatestFiniteMagnitude _xMax = -Double.greatestFiniteMagnitude _xMin = Double.greatestFiniteMagnitude _leftAxisMax = -Double.greatestFiniteMagnitude _leftAxisMin = Double.greatestFiniteMagnitude _rightAxisMax = -Double.greatestFiniteMagnitude _rightAxisMin = Double.greatestFiniteMagnitude let allData = self.allData for data in allData { data.calcMinMax() let sets = data.dataSets _dataSets.append(contentsOf: sets) if data.yMax > _yMax { _yMax = data.yMax } if data.yMin < _yMin { _yMin = data.yMin } if data.xMax > _xMax { _xMax = data.xMax } if data.xMin < _xMin { _xMin = data.xMin } for dataset in sets { if dataset.axisDependency == .left { if dataset.yMax > _leftAxisMax { _leftAxisMax = dataset.yMax } if dataset.yMin < _leftAxisMin { _leftAxisMin = dataset.yMin } } else { if dataset.yMax > _rightAxisMax { _rightAxisMax = dataset.yMax } if dataset.yMin < _rightAxisMin { _rightAxisMin = dataset.yMin } } } } } /// All data objects in row: line-bar-scatter-candle-bubble if not null. @objc open var allData: [ChartData] { var data = [ChartData]() if lineData !== nil { data.append(lineData) } if barData !== nil { data.append(barData) } if scatterData !== nil { data.append(scatterData) } if candleData !== nil { data.append(candleData) } if bubbleData !== nil { data.append(bubbleData) } return data } @objc open func dataByIndex(_ index: Int) -> ChartData { return allData[index] } open func dataIndex(_ data: ChartData) -> Int? { return allData.firstIndex(of: data) } open override func removeDataSet(_ dataSet: IChartDataSet) -> Bool { return allData.contains { $0.removeDataSet(dataSet) } } open override func removeDataSetByIndex(_ index: Int) -> Bool { print("removeDataSet(index) not supported for CombinedData", terminator: "\n") return false } open override func removeEntry(_ entry: ChartDataEntry, dataSetIndex: Int) -> Bool { print("removeEntry(entry, dataSetIndex) not supported for CombinedData", terminator: "\n") return false } open override func removeEntry(xValue: Double, dataSetIndex: Int) -> Bool { print("removeEntry(xValue, dataSetIndex) not supported for CombinedData", terminator: "\n") return false } open override func notifyDataChanged() { if _lineData !== nil { _lineData.notifyDataChanged() } if _barData !== nil { _barData.notifyDataChanged() } if _scatterData !== nil { _scatterData.notifyDataChanged() } if _candleData !== nil { _candleData.notifyDataChanged() } if _bubbleData !== nil { _bubbleData.notifyDataChanged() } super.notifyDataChanged() // recalculate everything } /// Get the Entry for a corresponding highlight object /// /// - Parameters: /// - highlight: /// - Returns: The entry that is highlighted open override func entryForHighlight(_ highlight: Highlight) -> ChartDataEntry? { if highlight.dataIndex >= allData.count { return nil } let data = dataByIndex(highlight.dataIndex) if highlight.dataSetIndex >= data.dataSetCount { return nil } // The value of the highlighted entry could be NaN - if we are not interested in highlighting a specific value. let entries = data.getDataSetByIndex(highlight.dataSetIndex).entriesForXValue(highlight.x) return entries.first { $0.y == highlight.y || highlight.y.isNaN } } /// Get dataset for highlight /// /// - Parameters: /// - highlight: current highlight /// - Returns: dataset related to highlight @objc open func getDataSetByHighlight(_ highlight: Highlight) -> IChartDataSet! { if highlight.dataIndex >= allData.count { return nil } let data = dataByIndex(highlight.dataIndex) if highlight.dataSetIndex >= data.dataSetCount { return nil } return data.dataSets[highlight.dataSetIndex] } }
525a606f4de2dd97377f961c5f441114
23.644518
119
0.498787
false
false
false
false
keyacid/keyacid-iOS
refs/heads/master
keyacid/EncryptViewController.swift
bsd-3-clause
1
// // EncryptViewController.swift // keyacid // // Created by Yuan Zhou on 6/24/17. // Copyright © 2017 yvbbrjdr. All rights reserved. // import UIKit class EncryptViewController: UIViewController { @IBOutlet weak var textView: UITextView! @IBOutlet weak var signedAnonymous: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() textView.inputAccessoryView = DoneView.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 40), textBox: textView) } func getSelectedRemoteProfile() -> RemoteProfile? { if ProfilesTableViewController.selectedRemoteProfileIndex == -1 { let remoteProfileNotSelected: UIAlertController = UIAlertController.init(title: "Error", message: "You have to select a remote profile!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in self.performSegue(withIdentifier: "ShowProfiles", sender: self) }) remoteProfileNotSelected.addAction(OKAction) self.present(remoteProfileNotSelected, animated: true, completion: nil) return nil } return ProfilesTableViewController.remoteProfiles[ProfilesTableViewController.selectedRemoteProfileIndex] } func getSelectedLocalProfile() -> LocalProfile? { if ProfilesTableViewController.selectedLocalProfileIndex == -1 { let localProfileNotSelected: UIAlertController = UIAlertController.init(title: "Error", message: "You have to select a local profile!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in self.performSegue(withIdentifier: "ShowProfiles", sender: self) }) localProfileNotSelected.addAction(OKAction) self.present(localProfileNotSelected, animated: true, completion: nil) return nil } return ProfilesTableViewController.localProfiles[ProfilesTableViewController.selectedLocalProfileIndex] } @IBAction func encryptClicked() { let plainText: String = textView.text var cipherText: String = "" if plainText == "" { let empty: UIAlertController = UIAlertController.init(title: "Error", message: "You have to encrypt something!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in self.textView.becomeFirstResponder() }) empty.addAction(OKAction) self.present(empty, animated: true, completion: nil) return } if signedAnonymous.selectedSegmentIndex == 0 { let remoteProfile: RemoteProfile? = getSelectedRemoteProfile() if remoteProfile == nil { return } let localProfile: LocalProfile? = getSelectedLocalProfile() if localProfile == nil { return } cipherText = Crypto.encrypt(data: plainText.data(using: String.Encoding.utf8)!, from: localProfile!, to: remoteProfile!).base64EncodedString() if cipherText == "" { let empty: UIAlertController = UIAlertController.init(title: "Error", message: "Corrputed profile!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) empty.addAction(OKAction) self.present(empty, animated: true, completion: nil) return } textView.text = cipherText } else { let remoteProfile: RemoteProfile? = getSelectedRemoteProfile() if remoteProfile == nil { return } cipherText = Crypto.sealedEncrypt(data: plainText.data(using: String.Encoding.utf8)!, to: remoteProfile!).base64EncodedString() if cipherText == "" { let empty: UIAlertController = UIAlertController.init(title: "Error", message: "Corrputed profile!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) empty.addAction(OKAction) self.present(empty, animated: true, completion: nil) return } textView.text = cipherText } UIPasteboard.general.string = cipherText } @IBAction func decryptClicked() { let cipher: Data? = Data.init(base64Encoded: textView.text) if cipher == nil { let notBase64: UIAlertController = UIAlertController.init(title: "Error", message: "Invalid cipher!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) notBase64.addAction(OKAction) self.present(notBase64, animated: true, completion: nil) return } if signedAnonymous.selectedSegmentIndex == 0 { let remoteProfile: RemoteProfile? = getSelectedRemoteProfile() if remoteProfile == nil { return } let localProfile: LocalProfile? = getSelectedLocalProfile() if localProfile == nil { return } let plainText: String = String.init(data: Crypto.decrypt(data: cipher!, from: remoteProfile!, to: localProfile!), encoding: String.Encoding.utf8)! if plainText == "" { let empty: UIAlertController = UIAlertController.init(title: "Error", message: "Wrong profile or tampered data!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) empty.addAction(OKAction) self.present(empty, animated: true, completion: nil) return } textView.text = plainText } else { let localProfile: LocalProfile? = getSelectedLocalProfile() if localProfile == nil { return } let plainText: String = String.init(data: Crypto.sealedDecrypt(data: cipher!, to: localProfile!), encoding: String.Encoding.utf8)! if plainText == "" { let empty: UIAlertController = UIAlertController.init(title: "Error", message: "Wrong profile or tampered data!", preferredStyle: .alert) let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil) empty.addAction(OKAction) self.present(empty, animated: true, completion: nil) return } textView.text = plainText } } }
36d32a38173612b497fe16b84c85d380
49.036232
173
0.623896
false
false
false
false
CodaFi/swift
refs/heads/main
test/SILOptimizer/diagnostic_constant_propagation_int_arch64.swift
apache-2.0
33
// RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify // // REQUIRES: PTRSIZE=64 // // This file tests diagnostics for arithmetic and bitwise operations on `Int` // and `UInt` types for 64 bit architectures. // // FIXME: This test should be merged back into // diagnostic_constant_propagation.swift when we have fixed: // <rdar://problem/19434979> -verify does not respect #if // // FIXME: <rdar://problem/29937936> False negatives when using integer initializers // // FIXME: <rdar://problem/39193272> A false negative that happens only in REPL import StdlibUnittest func testArithmeticOverflow_Int_64bit() { do { // Literals. var _: Int = 0x7fff_ffff_ffff_ffff // OK var _: Int = 0x8000_0000_0000_0000 // expected-error {{integer literal '9223372036854775808' overflows when stored into 'Int'}} var _: Int = -0x8000_0000_0000_0000 // OK var _: Int = -0x8000_0000_0000_0001 // expected-error {{integer literal '-9223372036854775809' overflows when stored into 'Int'}} } do { // Negation. var _: Int = -(-0x7fff_ffff_ffff_ffff) // OK var _: Int = -(-0x8000_0000_0000_0000) // expected-error {{arithmetic operation '0 - -9223372036854775808' (on signed 64-bit integer type) results in an overflow}} // FIXME: Missing diagnostic in REPL: // <rdar://problem/39193272> Overflow in arithmetic negation is not detected // at compile time when running in REPL } do { // Addition. var _: Int = 0x7fff_ffff_ffff_fffe + 1 // OK var _: Int = 0x7fff_ffff_ffff_fffe + 2 // expected-error {{arithmetic operation '9223372036854775806 + 2' (on type 'Int') results in an overflow}} var _: Int = -0x7fff_ffff_ffff_ffff + (-1) // OK var _: Int = -0x7fff_ffff_ffff_ffff + (-2) // expected-error {{arithmetic operation '-9223372036854775807 + -2' (on type 'Int') results in an overflow}} } do { // Subtraction. var _: Int = 0x7fff_ffff_ffff_fffe - (-1) // OK var _: Int = 0x7fff_ffff_ffff_fffe - (-2) // expected-error {{arithmetic operation '9223372036854775806 - -2' (on type 'Int') results in an overflow}} var _: Int = -0x7fff_ffff_ffff_ffff - 1 // OK var _: Int = -0x7fff_ffff_ffff_ffff - 2 // expected-error {{arithmetic operation '-9223372036854775807 - 2' (on type 'Int') results in an overflow}} } do { // Multiplication. var _: Int = 0x7fff_ffff_ffff_fffe * 1 // OK var _: Int = 0x7fff_ffff_ffff_fffe * 2 // expected-error {{arithmetic operation '9223372036854775806 * 2' (on type 'Int') results in an overflow}} var _: Int = -0x7fff_ffff_ffff_ffff * 1 // OK var _: Int = -0x7fff_ffff_ffff_ffff * 2 // expected-error {{arithmetic operation '-9223372036854775807 * 2' (on type 'Int') results in an overflow}} } do { // Division. var _: Int = 0x7fff_ffff_ffff_fffe / 2 // OK var _: Int = 0x7fff_ffff_ffff_fffe / 0 // expected-error {{division by zero}} var _: Int = -0x7fff_ffff_ffff_ffff / 2 // OK var _: Int = -0x7fff_ffff_ffff_ffff / 0 // expected-error {{division by zero}} var _: Int = -0x8000_0000_0000_0000 / -1 // expected-error {{division '-9223372036854775808 / -1' results in an overflow}} } do { // Remainder. var _: Int = 0x7fff_ffff_ffff_fffe % 2 // OK var _: Int = 0x7fff_ffff_ffff_fffe % 0 // expected-error {{division by zero}} var _: Int = -0x7fff_ffff_ffff_ffff % 2 // OK var _: Int = -0x7fff_ffff_ffff_ffff % 0 // expected-error {{division by zero}} var _: Int = -0x8000_0000_0000_0000 % -1 // expected-error {{division '-9223372036854775808 % -1' results in an overflow}} } do { // Right shift. // Due to "smart shift" introduction, there can be no overflows errors // during shift operations var _: Int = 0 >> 0 var _: Int = 0 >> 1 var _: Int = 0 >> (-1) var _: Int = 123 >> 0 var _: Int = 123 >> 1 var _: Int = 123 >> (-1) var _: Int = (-1) >> 0 var _: Int = (-1) >> 1 var _: Int = 0x7fff_ffff_ffff_ffff >> 63 var _ :Int = 0x7fff_ffff_ffff_ffff >> 64 var _ :Int = 0x7fff_ffff_ffff_ffff >> 65 } do { // Left shift. // Due to "smart shift" introduction, there can be no overflows errors // during shift operations var _: Int = 0 << 0 var _: Int = 0 << 1 var _: Int = 0 << (-1) var _: Int = 123 << 0 var _: Int = 123 << 1 var _: Int = 123 << (-1) var _: Int = (-1) << 0 var _: Int = (-1) << 1 var _: Int = 0x7fff_ffff_ffff_ffff << 63 var _ :Int = 0x7fff_ffff_ffff_ffff << 64 var _ :Int = 0x7fff_ffff_ffff_ffff << 65 } do { var _ : Int = ~0 var _ : Int = (0x7fff_ffff_ffff_fff) | (0x4000_0000_0000_0000 << 1) var _ : Int = (0x7fff_ffff_ffff_ffff) | 0x8000_0000_0000_0000 // expected-error {{integer literal '9223372036854775808' overflows when stored into 'Int'}} } } func testArithmeticOverflow_UInt_64bit() { do { // Literals. var _: UInt = 0x7fff_ffff_ffff_ffff // OK var _: UInt = 0x8000_0000_0000_0000 var _: UInt = 0xffff_ffff_ffff_ffff var _: UInt = -1 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}} var _: UInt = -0xffff_ffff_ffff_ffff // expected-error {{negative integer '-18446744073709551615' overflows when stored into unsigned type 'UInt'}} } do { // Addition. var _: UInt = 0 + 0 // OK var _: UInt = 0xffff_ffff_ffff_ffff + 0 // OK var _: UInt = 0xffff_ffff_ffff_ffff + 1 // expected-error {{arithmetic operation '18446744073709551615 + 1' (on type 'UInt') results in an overflow}} var _: UInt = 0xffff_ffff_ffff_fffe + 1 // OK var _: UInt = 0xffff_ffff_ffff_fffe + 2 // expected-error {{arithmetic operation '18446744073709551614 + 2' (on type 'UInt') results in an overflow}} } do { // Subtraction. var _: UInt = 0xffff_ffff_ffff_fffe - 1 // OK var _: UInt = 0xffff_ffff_ffff_fffe - 0xffff_ffff_ffff_ffff // expected-error {{arithmetic operation '18446744073709551614 - 18446744073709551615' (on type 'UInt') results in an overflow}} var _: UInt = 0 - 0 // OK var _: UInt = 0 - 1 // expected-error {{arithmetic operation '0 - 1' (on type 'UInt') results in an overflow}} } do { // Multiplication. var _: UInt = 0xffff_ffff_ffff_ffff * 0 // OK var _: UInt = 0xffff_ffff_ffff_ffff * 1 // OK var _: UInt = 0xffff_ffff_ffff_ffff * 2 // expected-error {{arithmetic operation '18446744073709551615 * 2' (on type 'UInt') results in an overflow}} var _: UInt = 0xffff_ffff_ffff_ffff * 0xffff_ffff_ffff_ffff // expected-error {{arithmetic operation '18446744073709551615 * 18446744073709551615' (on type 'UInt') results in an overflow}} var _: UInt = 0x7fff_ffff_ffff_fffe * 0 // OK var _: UInt = 0x7fff_ffff_ffff_fffe * 1 // OK var _: UInt = 0x7fff_ffff_ffff_fffe * 2 // OK var _: UInt = 0x7fff_ffff_ffff_fffe * 3 // expected-error {{arithmetic operation '9223372036854775806 * 3' (on type 'UInt') results in an overflow}} } do { // Division. var _: UInt = 0x7fff_ffff_ffff_fffe / 2 // OK var _: UInt = 0x7fff_ffff_ffff_fffe / 0 // expected-error {{division by zero}} var _: UInt = 0xffff_ffff_ffff_ffff / 2 // OK var _: UInt = 0xffff_ffff_ffff_ffff / 0 // expected-error {{division by zero}} } do { // Remainder. var _: UInt = 0x7fff_ffff_ffff_fffe % 2 // OK var _: UInt = 0x7fff_ffff_ffff_fffe % 0 // expected-error {{division by zero}} var _: UInt = 0xffff_ffff_ffff_ffff % 2 // OK var _: UInt = 0xffff_ffff_ffff_ffff % 0 // expected-error {{division by zero}} } do { // Shift operations don't result in overflow errors but note that // one cannot use negative values while initializing of an unsigned value var _: UInt = 0 >> 0 var _: UInt = 0 >> 1 var _: UInt = 123 >> 0 var _: UInt = 123 >> 1 var _: UInt = (-1) >> 0 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}} var _: UInt = (-1) >> 1 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}} var _: UInt = 0x7fff_ffff_ffff_ffff >> 63 var _: UInt = 0x7fff_ffff_ffff_ffff >> 64 var _: UInt = 0x7fff_ffff_ffff_ffff >> 65 } do { // Shift operations don't result in overflow errors but note that // one cannot use negative values while initializing of an unsigned value var _: UInt = 0 << 0 var _: UInt = 0 << 1 var _: UInt = 123 << 0 var _: UInt = 123 << 1 var _: UInt = (-1) << 0 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}} var _: UInt = (-1) << 1 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}} var _: UInt = 0x7fff_ffff_ffff_ffff << 63 var _: UInt = 0x7fff_ffff_ffff_ffff << 64 var _: UInt = 0x7fff_ffff_ffff_ffff << 65 } do { // bitwise operations. No overflows can happen during these operations var _ : UInt = ~0 var _ : UInt = (0x7fff_ffff_ffff_ffff) | (0x4000_0000_0000_0000 << 1) var _ : UInt = (0x7fff_ffff) | 0x8000_0000_0000_0000 } } func testIntToFloatConversion() { // No warnings are emitted for conversion through explicit constructor calls. _blackHole(Double(9_007_199_254_740_993)) }
3217c3c914485ba7bf3c3d0c5ca1de0e
37.31405
192
0.620039
false
false
false
false
davidkuchar/codepath-04-twitterredux
refs/heads/master
Twitter/SidePanelViewController.swift
mit
1
// // SidePanelViewController.swift // Twitter // // Created by David Kuchar on 5/31/15. // Copyright (c) 2015 David Kuchar. All rights reserved. // import UIKit @objc enum MenuItem: Int { case Mentions = -1 case Profile case Timeline } @objc protocol SidePanelViewControllerDelegate { optional func onMenuItemSelected(sender: AnyObject?, menuItem: MenuItem) } class SidePanelViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! weak var delegate: SidePanelViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("SelectCell", forIndexPath: indexPath) as! SelectCell switch MenuItem(rawValue: indexPath.row) { case .Some(.Profile): cell.nameLabel.text = "Your Profile" case .Some(.Timeline): cell.nameLabel.text = "Your Timeline" default: break } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch MenuItem(rawValue: indexPath.row) { case .Some(.Profile): delegate?.onMenuItemSelected?(self, menuItem: .Profile) case .Some(.Timeline): delegate?.onMenuItemSelected?(self, menuItem: .Timeline) default: break } } @IBAction func onTapMentions(sender: AnyObject) { delegate?.onMenuItemSelected?(self, menuItem: .Mentions) } }
84510adcf3bf4c754fc6ba854856c648
26.902778
116
0.653386
false
false
false
false
kiwitechnologies/ServiceClientiOS
refs/heads/master
ServiceClient/ServiceClient/TSGServiceClient/Utliity/TSGStringConstants.swift
mit
1
// // StringConstants.swift // ServiceSample // // Created by Yogesh Bhatt on 13/05/16. // Copyright © 2016 kiwitech. All rights reserved. // import Foundation let KEYS:String = "KEYS" let MissingKeys:String = "MISSING_KEYS" let INVALID_KEYS:String = "INVALID_KEYS" let HEADERS:String = "HEADERS" let Actions:String = "ACTIONS" var errorStatus:[String:NSMutableArray]? var missingParamKeys:[String:NSMutableArray]? var missingInvalidParamKeys:[String:NSMutableArray]? var missingHeaderKeys:[String:NSMutableArray]? var missingHeaderParamKeys:[String:NSMutableArray]? var invalidKeys:[String:NSMutableArray]? = [:] var invalidHeaderKeys:[String:NSMutableArray]? = [:] var alphaKey:NSMutableArray? = [] var alphaNumericKey:NSMutableArray? = [] var lengthKey:NSMutableArray? = [] var fileSizeKey:NSMutableArray? = [] var requiredKeys:NSMutableArray? = [] var emailKeys:NSMutableArray? = [] var numericKeys:NSMutableArray? = []
93575281e32ac4c464f099e8bfdc304a
22.525
52
0.756642
false
false
false
false
hustlzp/bemyeyes-ios
refs/heads/development
BeMyEyes Tests/ClientTest.swift
mit
2
// // ClientTest.swift // BeMyEyes // // Created by Tobias Due Munk on 18/11/14. // Copyright (c) 2014 Be My Eyes. All rights reserved. // import UIKit import XCTest class ClientTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func newUser() -> (email: String, firstName: String, lastName: String, password: String, role: BMERole) { let email = "iOSAppTest_" + String.random() + "@tt.com" let firstName = "iOS App" let lastName = "Tester" let password = "12345678" let role = BMERole.Blind return (email, firstName, lastName, password, role) } func testSignup() { let expectation = expectationWithDescription("Signup") let (email, firstName, lastName, password, role) = newUser() BMEClient.sharedClient().createUserWithEmail(email, password: password, firstName: firstName, lastName: lastName, role: role) { (success, error) in expectation.fulfill() XCTAssert(success, "Failed sign up") if let error = error { XCTFail("...with error: " + error.localizedDescription) } if let user = BMEClient.sharedClient().currentUser { XCTAssert(user.email == email, "Wrong email") XCTAssert(user.firstName == firstName, "Wrong first name") XCTAssert(user.lastName == lastName, "Wrong last name") XCTAssert(user.role == role, "Wrong role") } else { XCTFail("No current user") } let token = BMEClient.sharedClient().token() XCTAssert(token != nil, "No token") } waitForExpectationsWithTimeout(3, handler: nil) } func testLogin() { let expectation = expectationWithDescription("Login") let (email, firstName, lastName, password, role) = newUser() BMEClient.sharedClient().createUserWithEmail(email, password: password, firstName: firstName, lastName: lastName, role: role) { (success, error) in BMEClient.sharedClient().loginWithEmail(email, password: password, deviceToken: nil, success: { token in expectation.fulfill() if let user = BMEClient.sharedClient().currentUser { XCTAssert(user.email == email, "Wrong email") XCTAssert(user.firstName == firstName, "Wrong first name") XCTAssert(user.lastName == lastName, "Wrong last name") XCTAssert(user.role == role, "Wrong role") } else { XCTFail("No current user") } let token = BMEClient.sharedClient().token() XCTAssert(token != nil, "No token") }, failure: { (error) -> Void in XCTFail("Failed log in: " + error.localizedDescription) expectation.fulfill() }) } waitForExpectationsWithTimeout(3, handler: nil) } func testLogout() { let expectation = expectationWithDescription("Logout") let (email, firstName, lastName, password, role) = newUser() BMEClient.sharedClient().createUserWithEmail(email, password: password, firstName: firstName, lastName: lastName, role: role) { (success, error) in BMEClient.sharedClient().logoutWithCompletion(){ success, error in expectation.fulfill() XCTAssert(success, "Failed log out") if let error = error { XCTFail("...with error: " + error.localizedDescription) } let user = BMEClient.sharedClient().currentUser XCTAssert(user == nil, "Shouldn't have current user") } } waitForExpectationsWithTimeout(3, handler: nil) } func testInsertDeviceToken() { let expectation = expectationWithDescription("Insert token") let (email, firstName, lastName, password, role) = newUser() BMEClient.sharedClient().createUserWithEmail(email, password: password, firstName: firstName, lastName: lastName, role: role) { success, error in let newToken = "0f744707bebcf74f9b7c25d48e3358945f6aa01da5ddb387462c7eaf61bbad78" BMEClient.sharedClient().upsertDeviceWithNewToken(newToken, production: false, completion: { (success, error) in expectation.fulfill() XCTAssert(success, "Failed insert") if let error = error { XCTFail("...with error: " + error.localizedDescription) } XCTAssert(GVUserDefaults.standardUserDefaults().deviceToken == newToken, "Wrong token") }) } waitForExpectationsWithTimeout(3, handler: nil) } } extension String { subscript (i: Int) -> String { return String(Array(self)[i]) } static func random() -> String { return NSUUID().UUIDString } }
ab7bb19a9f1186621d507501d8aee98b
41.384
155
0.594753
false
true
false
false
iamjono/clingon
refs/heads/master
Sources/clingon/utilities/makeInitialize.swift
apache-2.0
1
// // makeInitialize.swift // clingon // // Created by Jonathan Guthrie on 2017-04-02. // // import PerfectLib func makeInitialize() throws { let nl = "//" let el = "" var str: [String] = ["//"] str.append("// initializeObjects.swift") str.append("// \(fconfig.projectName)") str.append(nl) str.append("// Created by Jonathan Guthrie on 2017-02-20.") str.append("// Copyright (C) 2017 PerfectlySoft, Inc.") str.append(nl) str.append("// Modified by Clingon: https://github.com/iamjono/clingon") str.append(nl) str.append("import PerfectLib") str.append(el) str.append("extension Utility {") str.append(" static func initializeObjects() {") var counter = 0 for cc in fconfig.classes { if cc.includeSetup { str.append(el) str.append(" let a\(counter) = \(cc.name)()") str.append(" try? a\(counter).setup()") counter += 1 } } str.append(el) str.append(" }") str.append("}") str.append("") // Write file do { try writeFile("\(fconfig.destinationDir)/Sources/\(fconfig.projectName)/objects/initializeObjects.swift", contents: str) } catch { throw scaffoldError.fileWriteError } }
f4dc40122a3fa5bacf0a51c56f49b092
20.090909
122
0.644828
false
true
false
false
DylanModesitt/Verb
refs/heads/master
Verb/Verb/Event.swift
apache-2.0
1
// // Event.swift // noun // // Created by dcm on 12/23/15. // Copyright © 2015 noun. All rights reserved. // import Foundation import Parse /* @brief Create a new event given the desired name and the noun it belongs to @init This method begins creates a new event object @param name The name of the event to be created @return The event PFObject created */ class Event { /* The heart of Verb */ let event = PFObject(className: "Event") var eventName: String var numberOfMembers: Int var upvotes: Int var timeOfEvent: String var isPrivate: Bool var downvotes: Int var nounParentObjectId: String init(givenName: String, timeOfEvent: String, isPrivate: Bool, userCreatingEvent: PFUser, nounParentObjectId: String) throws { self.eventName = givenName self.timeOfEvent = timeOfEvent self.isPrivate = isPrivate self.numberOfMembers = 1 self.upvotes = 0 self.downvotes = 0 self.nounParentObjectId = nounParentObjectId // Initialize the properties of the object event["name"] = eventName event["numberOfMembers"] = numberOfMembers event["upvotes"] = upvotes event["downvotes"] = downvotes // Contact parent (noun the event is under) and save it to the parent. Otherwise, abandon the object. do { try ServerRequests().updateArray("Noun", objectID: nounParentObjectId, key: "events", valueToUpdate: event) try ServerRequests().changeKeyByOne("Noun", objectID: nounParentObjectId, keyToIncrement: "numberOfEvents", increment: true) } catch { try event.delete() throw errors.failureToAddEventToNoun } // TODO- Ad users and such. Users have a relationship with events // Attempt to save directly. If not, save the object to the server eventually do { try event.save() } catch { event.saveEventually() throw errors.failureToSaveData } } // @returns The event PFObject func getEvent() -> PFObject { return event } // @returns the event's objectId func getEventObjectID() -> String? { if let _ = event.objectId { return event.objectId! } else { return nil } } }
a6ea10c9e09abdac419fd37649ae9fd8
26.455556
136
0.600162
false
false
false
false
matsuda/MuddlerKit
refs/heads/master
MuddlerKit/NSHTTPCookieStorageExtensions.swift
mit
1
// // NSHTTPCookieStorageExtensions.swift // MuddlerKit // // Created by Kosuke Matsuda on 2015/12/28. // Copyright © 2015年 Kosuke Matsuda. All rights reserved. // import Foundation // // MARK: - archive & unarchive // extension Extension where Base: HTTPCookieStorage { public func archivedData() -> Data? { guard let cookies = base.cookies else { return nil } return NSKeyedArchiver.archivedData(withRootObject: cookies) } public func unarchive(data: Data) { guard let cookies = NSKeyedUnarchiver.unarchiveObject(with: data) as? [HTTPCookie] else { return } cookies.forEach { base.setCookie($0) } } } // // MARK: - clear // extension Extension where Base: HTTPCookieStorage { public func clearAll() { guard let cookies = base.cookies else { return } for cookie in cookies { base.mk.clearCookie(cookie) } } public func clear(forURL url: URL) { guard let cookies = base.cookies(for: url) else { return } for cookie in cookies { base.mk.clearCookie(cookie) } } /// /// http://mmasashi.hatenablog.com/entry/20101202/1292763345 /// public func clearCookie(_ cookie: HTTPCookie) { guard var property = cookie.properties else { base.deleteCookie(cookie) return } base.deleteCookie(cookie) property[HTTPCookiePropertyKey.expires] = Date(timeIntervalSinceNow: -3600) if let newCookie = HTTPCookie(properties: property) { base.setCookie(newCookie) } } }
9fcfea6ed023154f3fe078c26a32873e
25.933333
97
0.623762
false
false
false
false
hironytic/Kiretan0
refs/heads/master
Kiretan0/View/Setting/TeamSelectionViewModel.swift
mit
1
// // TeamSelectionViewModel.swift // Kiretan0 // // Copyright (c) 2017 Hironori Ichimiya <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import RxSwift public protocol TeamSelectionViewModel: ViewModel { var tableData: Observable<[TableSectionViewModel]> { get } } public protocol TeamSelectionViewModelResolver { func resolveTeamSelectionViewModel() -> TeamSelectionViewModel } extension DefaultResolver: TeamSelectionViewModelResolver { public func resolveTeamSelectionViewModel() -> TeamSelectionViewModel { return DefaultTeamSelectionViewModel(resolver: self) } } public class DefaultTeamSelectionViewModel: TeamSelectionViewModel { public typealias Resolver = NullResolver public let tableData: Observable<[TableSectionViewModel]> private let _resolver: Resolver public init(resolver: Resolver) { _resolver = resolver let checkSubject = PublishSubject<String>() let checkedItem = checkSubject.scan("") { $1 } tableData = Observable.just([ StaticTableSectionViewModel(cells: [ CheckableTableCellViewModel(text: "うちのいえ", checked: checkedItem.map { $0 == "0" }, onSelect: checkSubject.mapObserver { "0" }), CheckableTableCellViewModel(text: "バスケ部", checked: checkedItem.map { $0 == "1" }, onSelect: checkSubject.mapObserver { "1" }), CheckableTableCellViewModel(text: "ほげほげ", checked: checkedItem.map { $0 == "2" }, onSelect: checkSubject.mapObserver { "2" }), ]) ]) } }
788921836ffd7d315ad4a466ee4bf66c
40.15625
143
0.719438
false
false
false
false
digipost/ios
refs/heads/master
Digipost/NSDate+Extensions.swift
apache-2.0
1
// // Copyright (C) Posten Norge AS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit extension Date { func prettyStringWithJPGExtension()-> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd MMM YY HH:mm:ss" var dateString = "IMG " dateString = dateString + dateFormatter.string(from: self) dateString = dateString + ".jpg" return dateString } func prettyStringWithMOVExtension()-> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd MMM YY HH:mm:ss" var dateString = "MOV " dateString = dateString + dateFormatter.string(from: self) dateString = dateString + ".mov" return dateString } func dateOnly() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd.MM.YYYY" return "\(dateFormatter.string(from: self))" } func timeOnly() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" return "\(dateFormatter.string(from: self))" } func dateByAdding(seconds: Int?) -> Date? { if seconds == nil { return nil } let calendar = Calendar.current var components = DateComponents() components.second = seconds! return (calendar as NSCalendar).date(byAdding: components, to: self, options: NSCalendar.Options()) } func isLaterThan(_ aDate: Date) -> Bool { let isLater = self.compare(aDate) == ComparisonResult.orderedDescending return isLater } }
c1c61501f07275939911034ea6c7eebd
31.848485
107
0.643911
false
true
false
false
LiskUser1234/SwiftyLisk
refs/heads/master
Lisk/Multisignature/Operations/MultisignatureSignOperation.swift
mit
1
/* The MIT License Copyright (C) 2017 LiskUser1234 - Github: https://github.com/liskuser1234 Please vote LiskUser1234 for delegate to support this project. For donations: - Lisk: 6137947831033853925L - Bitcoin: 1NCTZwBJF7ZFpwPeQKiSgci9r2pQV3G7RG 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 SwiftyJSON open class MultisignatureSignOperation : APIOperation { private let passphrase: String private let publicKey: String? private let secondPassphrase: String? private let transactionId: String private let transactionIdPtr: UnsafeMutablePointer<String>? public init(passphrase: String, publicKey: String?, secondPassphrase: String?, transactionId: String, transactionIdPtr: UnsafeMutablePointer<String>?, errorPtr: UnsafeMutablePointer<String?>) { self.passphrase = passphrase self.publicKey = publicKey self.secondPassphrase = secondPassphrase self.transactionId = transactionId self.transactionIdPtr = transactionIdPtr super.init(errorPtr: errorPtr) } override open func start() { MultisignatureAPI.sign(passphrase: passphrase, publicKey: publicKey, secondPassphrase: secondPassphrase, transactionId: transactionId, callback: callback) } override internal func processResponse(json: JSON) { self.transactionIdPtr?.pointee = json["transactionId"].stringValue } }
488a8683932e01ad75c4bd8112bdfd07
36
78
0.695946
false
false
false
false
robin24/bagtrack
refs/heads/master
BagTrack/View Controllers/Onboarding/OnboardingPushViewController.swift
mit
1
// // OnboardingPushViewController.swift // BagTrack // // Created by Robin Kipp on 13.10.17. // Copyright © 2017 Robin Kipp. All rights reserved. // import UIKit import UserNotifications class OnboardingPushViewController: UIViewController { // MARK: - Properties @IBOutlet weak var textView: UITextView! @IBOutlet weak var allowButton: UIButton! var center:UNUserNotificationCenter! var pushActivationFailed = false // MARK: - Methods override func viewDidLoad() { super.viewDidLoad() textView.text = NSLocalizedString("When you enable push notifications, BagTrack will inform you when you get too far from your bags.\n\nTap “Allow Push Notifications” and confirm the following prompt to enable notifications (recommended), or tap “Next” in order to skip this step.", comment: "Onboarding message informing the user about the advantages of enabling push notifications.") UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, textView) center = UNUserNotificationCenter.current() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onAllowButtonTapped(_ sender: UIButton) { if pushActivationFailed { guard let settingsURL = URL(string: UIApplicationOpenSettingsURLString) else { fatalError("Error retrieving settings URL.") } UIApplication.shared.open(settingsURL, options: [:]) { _ in DispatchQueue.main.async { self.textView.text = NSLocalizedString("Thank you!", comment: "Shown when returning to the app from the settings screen.") self.allowButton.isHidden = true } } return } center.requestAuthorization(options: [.alert, .sound]) { granted, error in if granted { DispatchQueue.main.async { self.textView.text = NSLocalizedString("Thank you for enabling push notifications!", comment: "Shown after push notifications were enabled.") self.allowButton.isHidden = true } } else { DispatchQueue.main.async { self.textView.text = NSLocalizedString("Oops, something went wrong! We were unable to activate push notifications. Please tap “Settings” now to enable notifications, or tap “Next” if you prefer to do so later.", comment: "Shown when unable to activate notifications.") self.pushActivationFailed = true self.allowButton.setTitle(NSLocalizedString("Settings", comment: "Settings button."), for: .normal) } } } } }
6dc90b50895b13aa9c3f88961ce864a1
44.95082
393
0.65751
false
false
false
false
DroidsOnRoids/SwiftCarousel
refs/heads/master
Source/SwiftCarousel.swift
mit
1
/* * Copyright (c) 2015 Droids on Roids 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 fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } open class SwiftCarousel: UIView { //MARK: - Properties /// Current target with velocity left internal var currentVelocityX: CGFloat? /// Maximum velocity that swipe can reach. internal var maxVelocity: CGFloat = 100.0 // Bool to know if item has been selected by Tapping fileprivate var itemSelectedByTap = false /// Number of items that were set at the start of init. fileprivate var originalChoicesNumber = 0 /// Items that carousel shows. It is 3x more items than originalChoicesNumber. fileprivate var choices: [UIView] = [] /// Main UIScrollView. fileprivate var scrollView = UIScrollView() /// Current selected index (between 0 and choices count). fileprivate var currentSelectedIndex: Int? /// Current selected index (between 0 and originalChoicesNumber). fileprivate var currentRealSelectedIndex: Int? /// Carousel delegate that handles events like didSelect. open weak var delegate: SwiftCarouselDelegate? /// Bool to set if by tap on item carousel should select it (scroll to it). open var selectByTapEnabled = true /// Scrolling type of carousel. You can constraint scrolling through items. open var scrollType: SwiftCarouselScroll = .default { didSet { if case .max(let number) = scrollType , number <= 0 { scrollType = .none } switch scrollType { case .none: scrollView.isScrollEnabled = false case .max, .freely, .default: scrollView.isScrollEnabled = true } } } /// Resize type of the carousel chosen from SwiftCarouselResizeType. open var resizeType: SwiftCarouselResizeType = .withoutResizing(0.0) { didSet { setupViews(choices) } } /// If selected index is < 0, set it as nil. /// We won't check with count number since it might be set before assigning items. open var defaultSelectedIndex: Int? { didSet { if (defaultSelectedIndex < 0) { defaultSelectedIndex = nil } } } /// If there is defaultSelectedIndex and was selected, the variable is true. /// Otherwise it is not. open var didSetDefaultIndex: Bool = false /// Current selected index (calculated by searching through views), /// It returns index between 0 and originalChoicesNumber. open var selectedIndex: Int? { let view = viewAtLocation(CGPoint(x: scrollView.contentOffset.x + scrollView.frame.width / 2.0, y: scrollView.frame.minY)) guard var index = choices.index(where: { $0 == view }) else { return nil } while index >= originalChoicesNumber { index -= originalChoicesNumber } return index } /// Current selected index (calculated by searching through views), /// It returns index between 0 and choices count. fileprivate var realSelectedIndex: Int? { let view = viewAtLocation(CGPoint(x: scrollView.contentOffset.x + scrollView.frame.width / 2.0, y: scrollView.frame.minY)) guard let index = choices.index(where: { $0 == view }) else { return nil } return index } /// Carousel items. You can setup your carousel using this method (static items), or /// you can also see `itemsFactory`, which uses closure for the setup. /// Warning: original views are copied internally and are not guaranteed to be complete when the `didSelect` and `didDeselect` delegate methods are called. Use `itemsFactory` instead to avoid this limitation. open var items: [UIView] { get { return [UIView](choices[choices.count / 3..<(choices.count / 3 + originalChoicesNumber)]) } set { originalChoicesNumber = newValue.count (0..<3).forEach { counter in let newViews: [UIView] = newValue.map { choice in // Return original view if middle section if counter == 1 { return choice } else { do { return try choice.copyView() } catch { fatalError("There was a problem with copying view.") } } } self.choices.append(contentsOf: newViews) } setupViews(choices) } } /// Factory for carousel items. Here you specify how many items do you want in carousel /// and you need to specify closure that will create that view. Remember that it should /// always create new view, not give the same reference all the time. /// If the factory closure returns a reference to a view that has already been returned, a SwiftCarouselError.ViewAlreadyAdded error is thrown. /// You can always setup your carousel using `items` instead. open func itemsFactory(itemsCount count: Int, factory: (_ index: Int) -> UIView) throws { guard count > 0 else { return } originalChoicesNumber = count try (0..<3).forEach { counter in let newViews: [UIView] = try stride(from: 0, to: count, by: 1).map { i in let view = factory(i) guard !self.choices.contains(view) else { throw SwiftCarouselError.viewAlreadyAdded } return view } self.choices.append(contentsOf: newViews) } setupViews(choices) } // MARK: - Inits public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } /** Initialize carousel with items & frame. - parameter frame: Carousel frame. - parameter items: Items to put in carousel. Warning: original views in `items` are copied internally and are not guaranteed to be complete when the `didSelect` and `didDeselect` delegate methods are called. Use `itemsFactory` instead to avoid this limitation. */ public convenience init(frame: CGRect, items: [UIView]) { self.init(frame: frame) setup() self.items = items } deinit { scrollView.removeObserver(self, forKeyPath: "contentOffset") } // MARK: - Setups /** Main setup function. Here should be everything that needs to be done once. */ fileprivate func setup() { scrollView = UIScrollView() scrollView.delegate = self scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.isScrollEnabled = true scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false addSubview(scrollView) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: .alignAllCenterX, metrics: nil, views: ["scrollView": scrollView]) ) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|", options: .alignAllCenterY, metrics: nil, views: ["scrollView": scrollView]) ) backgroundColor = .clear scrollView.backgroundColor = .clear scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.new, .old], context: nil) let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped(_:))) gestureRecognizer.cancelsTouchesInView = false gestureRecognizer.delegate = self scrollView.addGestureRecognizer(gestureRecognizer) } /** Setup views. Function that is fired up when setting the resizing type or items array. - parameter views: Current items to setup. */ fileprivate func setupViews(_ views: [UIView]) { var x: CGFloat = 0.0 if case .floatWithSpacing(_) = resizeType { views.forEach { $0.sizeToFit() } } views.forEach { choice in var additionalSpacing: CGFloat = 0.0 switch resizeType { case .withoutResizing(let spacing): additionalSpacing = spacing case .floatWithSpacing(let spacing): additionalSpacing = spacing case .visibleItemsPerPage(let visibleItems): choice.frame.size.width = scrollView.frame.width / CGFloat(visibleItems) if (choice.frame.height > 0.0) { let aspectRatio: CGFloat = choice.frame.width/choice.frame.height choice.frame.size.height = floor(choice.frame.width * aspectRatio) > frame.height ? frame.height : floor(choice.frame.width * aspectRatio) } else { choice.frame.size.height = frame.height } } choice.frame.origin.x = x x += choice.frame.width + additionalSpacing } scrollView.subviews.forEach { $0.removeFromSuperview() } views.forEach { scrollView.addSubview($0) } layoutIfNeeded() } override open func layoutSubviews() { super.layoutSubviews() guard (scrollView.frame.width > 0 && scrollView.frame.height > 0) else { return } var width: CGFloat = 0.0 switch resizeType { case .floatWithSpacing(_), .withoutResizing(_): width = choices.last!.frame.maxX case .visibleItemsPerPage(_): width = choices.reduce(0.0) { $0 + $1.frame.width } } scrollView.contentSize = CGSize(width: width, height: frame.height) maxVelocity = scrollView.contentSize.width / 6.0 // We do not want to change the selected index in case of hiding and // showing view, which also triggers layout. // On the other hand this method can be triggered when the defaultSelectedIndex // was set after the carousel init, so we check if the default index is != nil // and that it wasn't set before. guard currentSelectedIndex == nil || (didSetDefaultIndex == false && defaultSelectedIndex != nil) else { return } // Center the view if defaultSelectedIndex != nil { selectItem(defaultSelectedIndex!, animated: false) didSetDefaultIndex = true } else { selectItem(0, animated: false) } } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let _ = change?[NSKeyValueChangeKey.newKey] , keyPath == "contentOffset" { // with autolayout this seems to be quite usual, we want to wait // until we have some size we can actualy work with guard (scrollView.frame.width > 0 && scrollView.frame.height > 0) else { return } let newOffset = scrollView.contentOffset let segmentWidth = scrollView.contentSize.width / 3 var newOffsetX: CGFloat! if (newOffset.x >= segmentWidth * 2.0) { // in the 3rd part newOffsetX = newOffset.x - segmentWidth // move back one segment } else if (newOffset.x + scrollView.bounds.width) <= segmentWidth { // First part newOffsetX = newOffset.x + segmentWidth // move forward one segment } // We are in middle segment still so no need to scroll elsewhere guard newOffsetX != nil && newOffsetX > 0 else { return } self.scrollView.contentOffset.x = newOffsetX self.delegate?.didScroll?(toOffset: self.scrollView.contentOffset) } } // MARK: - Gestures open func viewTapped(_ gestureRecognizer: UIGestureRecognizer) { if selectByTapEnabled { let touchPoint = gestureRecognizer.location(in: scrollView) if let view = viewAtLocation(touchPoint), let index = choices.index(of: view) { itemSelectedByTap = true selectItem(index, animated: true, force: true) } } } // MARK: - Helpers /** Function that should be called when item was selected by Carousel. It will deselect all items that were selected before, and send notification to the delegate. */ internal func didSelectItem() { guard let selectedIndex = self.selectedIndex, let realSelectedIndex = self.realSelectedIndex else { return } didDeselectItem() delegate?.didSelectItem?(item: choices[realSelectedIndex], index: selectedIndex, tapped: itemSelectedByTap) itemSelectedByTap = false currentSelectedIndex = selectedIndex currentRealSelectedIndex = realSelectedIndex currentVelocityX = nil scrollView.isScrollEnabled = true } /** Function that should be called when item was deselected by Carousel. It will also send notification to the delegate. */ internal func didDeselectItem() { guard let currentRealSelectedIndex = self.currentRealSelectedIndex, let currentSelectedIndex = self.currentSelectedIndex else { return } delegate?.didDeselectItem?(item: choices[currentRealSelectedIndex], index: currentSelectedIndex) } /** Detects if new point to scroll to will change the part (from the 3 parts used by Carousel). First and third parts are not shown to the end user, we are managing the scrolling between them behind the stage. The second part is the part user thinks it sees. - parameter point: Destination point. - returns: Bool that says if the part will change. */ fileprivate func willChangePart(_ point: CGPoint) -> Bool { if (point.x >= scrollView.contentSize.width * 2.0 / 3.0 || point.x <= scrollView.contentSize.width / 3.0) { return true } return false } /** Get view (from the items array) at location (if it exists). - parameter touchLocation: Location point. - returns: UIView that contains that point (if it exists). */ fileprivate func viewAtLocation(_ touchLocation: CGPoint) -> UIView? { for subview in scrollView.subviews where subview.frame.contains(touchLocation) { return subview } return nil } /** Get nearest view to the specified point location. - parameter touchLocation: Location point. - returns: UIView that is the nearest to that point (or contains that point). */ internal func nearestViewAtLocation(_ touchLocation: CGPoint) -> UIView { var view: UIView! if let newView = viewAtLocation(touchLocation) { view = newView } else { // Now check left and right margins to nearest views var step: CGFloat = 1.0 switch resizeType { case .floatWithSpacing(let spacing): step = spacing case .withoutResizing(let spacing): step = spacing default: break } var targetX = touchLocation.x // Left var leftView: UIView? repeat { targetX -= step leftView = viewAtLocation(CGPoint(x: targetX, y: touchLocation.y)) } while (leftView == nil) let leftMargin = touchLocation.x - leftView!.frame.maxX // Right var rightView: UIView? repeat { targetX += step rightView = viewAtLocation(CGPoint(x: targetX, y: touchLocation.y)) } while (rightView == nil) let rightMargin = rightView!.frame.minX - touchLocation.x if rightMargin < leftMargin { view = rightView! } else { view = leftView! } } // Check if the view is in bounds of scrolling type if case .max(let maxItems) = scrollType, let currentRealSelectedIndex = currentRealSelectedIndex, var newIndex = choices.index (where: { $0 == view }) { if UInt(abs(newIndex - currentRealSelectedIndex)) > maxItems { if newIndex > currentRealSelectedIndex { newIndex = currentRealSelectedIndex + Int(maxItems) } else { newIndex = currentRealSelectedIndex - Int(maxItems) } } while newIndex < 0 { newIndex += originalChoicesNumber } while newIndex > choices.count { newIndex -= originalChoicesNumber } view = choices[newIndex] } return view } /** Select item in the Carousel. - parameter choice: Item index to select. If it contains number > than originalChoicesNumber, you need to set `force` flag to true. - parameter animated: If the method should try to animate the selection. - parameter force: Force should be set to true if choice index is out of items bounds. */ fileprivate func selectItem(_ choice: Int, animated: Bool, force: Bool) { var index = choice if !force { // allow scroll only in the range of original items guard choice < choices.count / 3 else { return } // move to same item in middle segment index = index + originalChoicesNumber } let choiceView = choices[index] let x = choiceView.center.x - scrollView.frame.width / 2.0 let newPosition = CGPoint(x: x, y: scrollView.contentOffset.y) let animationIsNotNeeded = newPosition.equalTo(scrollView.contentOffset) scrollView.setContentOffset(newPosition, animated: animated) if !animated || animationIsNotNeeded { didSelectItem() } } /** Select item in the Carousel. - parameter choice: Item index to select. - parameter animated: Bool to tell if the selection should be animated. */ open func selectItem(_ choice: Int, animated: Bool) { selectItem(choice, animated: animated, force: false) } }
f8297719a2168bf943dda608e1e52f08
37.382022
220
0.598946
false
false
false
false
alexth/Balkania-iPad
refs/heads/master
BalkaniaiPad/ViewControllers/MainViewController.swift
mit
1
// // MainViewController.swift // BalkaniaiPad // // Created by Alex Golub on 9/6/17. // Copyright © 2017 Alex Golub. All rights reserved. // import UIKit final class MainViewController: UIViewController { @IBOutlet weak var rsContainerView: UIView! @IBOutlet weak var srContainerView: UIView! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! fileprivate var selectedPlist: String! fileprivate var savedSelectedPlist = "savedSelectedPlist" fileprivate let russianSerbianPlist = "DICT_R-S" fileprivate let serbianRussianPlist = "DICT_S-R" fileprivate let rsSegueIdentifier = "rsSegue" fileprivate let srSegueIdentifier = "srSegue" fileprivate let animationDuration: TimeInterval = 0.3 override func viewDidLoad() { super.viewDidLoad() let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil) notificationCenter.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == rsSegueIdentifier { let dictionaryViewController = segue.destination as! DictionaryViewController dictionaryViewController.dictionaryName = russianSerbianPlist } else if segue.identifier == srSegueIdentifier { let dictionaryViewController = segue.destination as! DictionaryViewController dictionaryViewController.dictionaryName = serbianRussianPlist } } } extension MainViewController { @objc fileprivate func keyboardWillHide(notification: NSNotification) { UIView.animate(withDuration: animationDuration) { self.bottomConstraint.constant = 0 } } @objc fileprivate func keyboardWillShow(notification: NSNotification) { guard let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } UIView.animate(withDuration: animationDuration) { self.bottomConstraint.constant = keyboardSize.height } } }
eb71eb240ad0f2ff6f0155bcacf2118b
38.153846
120
0.658939
false
false
false
false
Yuanjihua1/SwiftyORM
refs/heads/master
SwiftyORM/StORMDataSourceCredentials.swift
mit
1
// // DataSourceCredentials.swift // StORM // // Created by Jonathan Guthrie on 2016-09-23. // // /// Storage for current datasource connection properties. public struct StORMDataSourceCredentials { /// Host, which is either a URL or an IP address. public var host: String = "localhost" /// Port at which the client will access the server. public var port: Int = 0 /// Username for authentication. public var username: String = "" /// Password for accessing the datasource. public var password: String = "" public init() {} /// Initializer to set properties at instantiation. public init(host: String, port: Int = 0, user: String = "", pass: String = "") { self.host = host self.port = port self.username = user self.password = pass } }
986481af90198fb5119172b12ecc62ed
22.575758
81
0.677378
false
false
false
false
nevyn/CoreDragon
refs/heads/master
Examples/DragonFrame/DragonFrame/PhotoFrameViewController.swift
apache-2.0
2
// // FirstViewController.swift // DragonFrame // // Created by Nevyn Bengtsson on 2015-12-20. // Copyright © 2015 ThirdCog. All rights reserved. // import UIKit class PhotoFrameViewController: UIViewController, DragonDropDelegate { @IBOutlet var imageView : UIImageView! override func viewDidLoad() { super.viewDidLoad() // Load image from last run. imageView.image = self.image // The user may drop things on the image view. // This view controller will be the delegate to determine if and how // drop operations will be handled. DragonController.sharedController().registerDropTarget(self.imageView, delegate: self) } // When a dragging operation starts, this method is called for each drop target // that this view controller is responsible for, to see if the drop target // is potentially able to accept the contents of that drag'n'drop. func dropTarget(droppable: UIView, canAcceptDrag drag: DragonInfo) -> Bool { // Is there something image-like on the pasteboard? Then accept it. if drag.pasteboard.pasteboardTypes().contains({ (str) -> Bool in return UIPasteboardTypeListImage.containsObject(str) }) { return true } return false } // Once the user drops the item on a drop target view, this method is responsible // for accepting the data and handling it. func dropTarget(droppable: UIView, acceptDrag drag: DragonInfo, atPoint p: CGPoint) { if let image = drag.pasteboard.image { // We handle it by setting the main image view's image to the one // that the user dropped, and ... self.imageView.image = image // ... also saving it to disk for next time. self.image = image } } // Helpers for loading/saving images from disk var imageURL : NSURL { get { let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! return NSURL.fileURLWithPath(documentsPath).URLByAppendingPathComponent("image.jpg") } } var image : UIImage? { get { return UIImage(contentsOfFile: self.imageURL.path!) } set { if let image = newValue { UIImageJPEGRepresentation(image, 0.8)?.writeToURL(self.imageURL, atomically: false) } } } }
d1118dbf16f110394baacf2ff2834b4e
29.873239
108
0.722958
false
false
false
false
Integreat/app-ios
refs/heads/master
Integreat/Integreat/RootNavigationController.swift
lgpl-3.0
2
import UIKit class RootNavigationController: UINavigationController { var apiService: IGApiService? var languagePickedObserver: NSObjectProtocol? override func viewDidLoad() { super.viewDidLoad() updateRootVC() languagePickedObserver = NSNotificationCenter.defaultCenter().addObserverForName(IGLanguagePickedNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: { [weak self] _ in self?.updateRootVC(animated: true) } ) } deinit { if let observer = languagePickedObserver { NSNotificationCenter.defaultCenter().removeObserver(observer, name: IGLanguagePickedNotification, object: nil ) } } @IBAction func showCityPicker(_: AnyObject?) { let cityPickerVC = instantiateCityPickerVC() setViewControllers([ cityPickerVC ], animated: true) } private func updateRootVC(animated animated: Bool = false) { let selection = getSelectedLocationAndLanguage() // Show pages if let location = selection.0, language = selection.1 { let pagesListVC = instantiatePagesListVCWithLocation(location, language: language) setViewControllers([ pagesListVC ], animated: animated) } // Pick city + language else { let cityPickerVC = instantiateCityPickerVC() setViewControllers([ cityPickerVC ], animated: animated) } } private func instantiateCityPickerVC() -> IGCityPickerVCCollectionViewController { let cityPickerVC = self.storyboard?.instantiateViewControllerWithIdentifier("CityPickerVC") as! IGCityPickerVCCollectionViewController cityPickerVC.apiService = apiService return cityPickerVC } private func instantiatePagesListVCWithLocation(location: Location, language: Language) -> IGPagesListVC { let pagesListVC = self.storyboard?.instantiateViewControllerWithIdentifier("PagesListVC") as! IGPagesListVC pagesListVC.apiService = apiService pagesListVC.selectedLocation = location pagesListVC.selectedLanguage = language return pagesListVC } private func getSelectedLocationAndLanguage() -> (Location?, Language?) { let location = NSUserDefaults.standardUserDefaults().stringForKey("location").flatMap { locationId in (self.apiService?.context).flatMap { context in Location.findLocationWithIdentifier(locationId, inContext: context) } } let language = NSUserDefaults.standardUserDefaults().stringForKey("language").flatMap { languageId in (self.apiService?.context).flatMap { context in Language.findLanguageWithIdentifier(languageId, inContext: context) } } return (location, language) } }
f221548e067f64b129119cd1247165fb
36.525
118
0.654231
false
false
false
false
alskipp/Argo
refs/heads/master
Argo/Types/StandardTypes.swift
mit
2
import Foundation extension String: Decodable { public static func decode(j: JSON) -> Decoded<String> { switch j { case let .String(s): return pure(s) default: return .typeMismatch("String", actual: j) } } } extension Int: Decodable { public static func decode(j: JSON) -> Decoded<Int> { switch j { case let .Number(n): return pure(n as Int) default: return .typeMismatch("Int", actual: j) } } } extension Int64: Decodable { public static func decode(j: JSON) -> Decoded<Int64> { switch j { case let .Number(n): return pure(n.longLongValue) case let .String(s): guard let i = Int64(s) else { fallthrough } return pure(i) default: return .typeMismatch("Int64", actual: j) } } } extension Double: Decodable { public static func decode(j: JSON) -> Decoded<Double> { switch j { case let .Number(n): return pure(n as Double) default: return .typeMismatch("Double", actual: j) } } } extension Bool: Decodable { public static func decode(j: JSON) -> Decoded<Bool> { switch j { case let .Number(n): return pure(n as Bool) default: return .typeMismatch("Bool", actual: j) } } } extension Float: Decodable { public static func decode(j: JSON) -> Decoded<Float> { switch j { case let .Number(n): return pure(n as Float) default: return .typeMismatch("Float", actual: j) } } } public extension Optional where Wrapped: Decodable, Wrapped == Wrapped.DecodedType { static func decode(j: JSON) -> Decoded<Wrapped?> { return .optional(Wrapped.decode(j)) } } public extension CollectionType where Generator.Element: Decodable, Generator.Element == Generator.Element.DecodedType { static func decode(j: JSON) -> Decoded<[Generator.Element]> { switch j { case let .Array(a): return sequence(a.map(Generator.Element.decode)) default: return .typeMismatch("Array", actual: j) } } } public func decodeArray<T: Decodable where T.DecodedType == T>(j: JSON) -> Decoded<[T]> { return [T].decode(j) } public extension DictionaryLiteralConvertible where Value: Decodable, Value == Value.DecodedType { static func decode(j: JSON) -> Decoded<[String: Value]> { switch j { case let .Object(o): return sequence(Value.decode <^> o) default: return .typeMismatch("Object", actual: j) } } } public func decodeObject<T: Decodable where T.DecodedType == T>(j: JSON) -> Decoded<[String: T]> { return [String: T].decode(j) } public func decodedJSON(json: JSON, forKey key: String) -> Decoded<JSON> { switch json { case let .Object(o): return guardNull(key, j: o[key] ?? .Null) default: return .typeMismatch("Object", actual: json) } } private func guardNull(key: String, j: JSON) -> Decoded<JSON> { switch j { case .Null: return .missingKey(key) default: return pure(j) } }
4282acab2c01abd6febbb64f4d8d68cf
26.413462
120
0.660821
false
false
false
false
matrix-org/matrix-ios-sdk
refs/heads/develop
MatrixSDK/Contrib/Swift/MXRestClient.swift
apache-2.0
1
/* Copyright 2017 Avery Pierce Copyright 2017 Vector Creations Ltd Copyright 2019 The Matrix.org Foundation C.I.C 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 /// Represents account data type public enum MXAccountDataType: Equatable, Hashable { case direct case pushRules case ignoredUserList case other(String) var rawValue: String { switch self { case .direct: return kMXAccountDataTypeDirect case .pushRules: return kMXAccountDataTypePushRules case .ignoredUserList: return kMXAccountDataKeyIgnoredUser case .other(let value): return value } } } /// Method of inviting a user to a room public enum MXRoomInvitee: Equatable, Hashable { /// Invite a user by username case userId(String) /// Invite a user by email case email(String) /// Invite a user using a third-party mechanism. /// `method` is the method to use, eg. "email". /// `address` is the address of the user. case thirdPartyId(MX3PID) } public extension MXRestClient { // MARK: - Initialization /** Create an instance based on homeserver url. - parameters: - homeServer: The homeserver address. - handler: the block called to handle unrecognized certificate (`nil` if unrecognized certificates are ignored). - returns: a `MXRestClient` instance. */ @nonobjc required convenience init(homeServer: URL, unrecognizedCertificateHandler handler: MXHTTPClientOnUnrecognizedCertificate?) { self.init(__homeServer: homeServer.absoluteString, andOnUnrecognizedCertificateBlock: handler) } /** Create an instance based on existing user credentials. - parameters: - credentials: A set of existing user credentials. - handler: the block called to handle unrecognized certificate (`nil` if unrecognized certificates are ignored). - returns: a `MXRestClient` instance. */ @nonobjc convenience init(credentials: MXCredentials, unrecognizedCertificateHandler handler: MXHTTPClientOnUnrecognizedCertificate? = nil, persistentTokenDataHandler: MXRestClientPersistTokenDataHandler? = nil, unauthenticatedHandler: MXRestClientUnauthenticatedHandler? = nil) { self.init(__credentials: credentials, andOnUnrecognizedCertificateBlock: handler, andPersistentTokenDataHandler: persistentTokenDataHandler, andUnauthenticatedHandler: unauthenticatedHandler) } // MARK: - Registration Operations /** Check whether a username is already in use. - parameters: - username: The user name to test. - completion: A block object called when the operation is completed. - inUse: Whether the username is in use - returns: a `MXHTTPOperation` instance. */ @available(*, deprecated, message: "Use isUsernameAvailable instead which calls the dedicated API and provides more information.") @nonobjc @discardableResult func isUserNameInUse(_ username: String, completion: @escaping (_ inUse: Bool) -> Void) -> MXHTTPOperation { return __isUserName(inUse: username, callback: completion) } /** Checks whether a username is available. - parameters: - username: The user name to test. - completion: A block object called when the operation is completed. - response: Provides the server response as an `MXUsernameAvailability` instance. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func isUsernameAvailable(_ username: String, completion: @escaping (_ response: MXResponse<MXUsernameAvailability>) -> Void) -> MXHTTPOperation { return __isUsernameAvailable(username, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the list of register flows supported by the home server. - parameters: - completion: A block object called when the operation is completed. - response: Provides the server response as an `MXAuthenticationSession` instance. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func getRegisterSession(completion: @escaping (_ response: MXResponse<MXAuthenticationSession>) -> Void) -> MXHTTPOperation { return __getRegisterSession(currySuccess(completion), failure: curryFailure(completion)) } /** Generic registration action request. As described in [the specification](http://matrix.org/docs/spec/client_server/r0.2.0.html#client-authentication), some registration flows require to complete several stages in order to complete user registration. This can lead to make several requests to the home server with different kinds of parameters. This generic method with open parameters and response exists to handle any kind of registration flow stage. At the end of the registration process, the SDK user should be able to construct a MXCredentials object from the response of the last registration action request. - parameters: - parameters: the parameters required for the current registration stage - completion: A block object called when the operation completes. - response: Provides the raw JSON response from the server. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func register(parameters: [String: Any], completion: @escaping (_ response: MXResponse<[String: Any]>) -> Void) -> MXHTTPOperation { return __register(withParameters: parameters, success: currySuccess(completion), failure: curryFailure(completion)) } /* TODO: This method accepts a nil username. Maybe this should be called "anonymous registration"? Would it make sense to have a separate API for that case? We could also create an enum called "MXRegistrationType" with associated values, e.g. `.username(String)` and `.anonymous` */ /** Register a user. This method manages the full flow for simple login types and returns the credentials of the newly created matrix user. - parameters: - loginType: the login type. Only `MXLoginFlowType.password` and `MXLoginFlowType.dummy` (m.login.password and m.login.dummy) are supported. - username: the user id (ex: "@bob:matrix.org") or the user id localpart (ex: "bob") of the user to register. Can be nil. - password: the user's password. - completion: A block object called when the operation completes. - response: Provides credentials to use to create a `MXRestClient`. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func register(loginType: MXLoginFlowType = .password, username: String?, password: String, completion: @escaping (_ response: MXResponse<MXCredentials>) -> Void) -> MXHTTPOperation { return __register(withLoginType: loginType.identifier, username: username, password: password, success: currySuccess(completion), failure: curryFailure(completion)) } /// The register fallback page to make registration via a web browser or a web view. var registerFallbackURL: URL { let fallbackString = __registerFallback()! return URL(string: fallbackString)! } // MARK: - Login Operation /** Get the list of login flows supported by the home server. - parameters: - completion: A block object called when the operation completes. - response: Provides the server response as an MXAuthenticationSession instance. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func getLoginSession(completion: @escaping (_ response: MXResponse<MXAuthenticationSession>) -> Void) -> MXHTTPOperation { return __getLoginSession(currySuccess(completion), failure: curryFailure(completion)) } /** Generic login action request. As described in [the specification](http://matrix.org/docs/spec/client_server/r0.2.0.html#client-authentication), some login flows require to complete several stages in order to complete authentication. This can lead to make several requests to the home server with different kinds of parameters. This generic method with open parameters and response exists to handle any kind of authentication flow stage. At the end of the registration process, the SDK user should be able to construct a MXCredentials object from the response of the last authentication action request. - parameters: - parameters: the parameters required for the current login stage - completion: A block object called when the operation completes. - response: Provides the raw JSON response from the server. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func login(parameters: [String: Any], completion: @escaping (_ response: MXResponse<[String: Any]>) -> Void) -> MXHTTPOperation { return __login(parameters, success: currySuccess(completion), failure: curryFailure(completion)) } /** Log a user in. This method manages the full flow for simple login types and returns the credentials of the logged matrix user. - parameters: - type: the login type. Only `MXLoginFlowType.password` (m.login.password) is supported. - username: the user id (ex: "@bob:matrix.org") or the user id localpart (ex: "bob") of the user to authenticate. - password: the user's password. - completion: A block object called when the operation succeeds. - response: Provides credentials for this user on `success` - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func login(type loginType: MXLoginFlowType = .password, username: String, password: String, completion: @escaping (_ response: MXResponse<MXCredentials>) -> Void) -> MXHTTPOperation { return __login(withLoginType: loginType.identifier, username: username, password: password, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the login fallback page to make login via a web browser or a web view. Presently only server auth v1 is supported. - returns: the fallback page URL. */ var loginFallbackURL: URL { let fallbackString = __loginFallback()! return URL(string: fallbackString)! } @nonobjc func generateLoginToken(withCompletion completion: @escaping (_ response: MXResponse<MXLoginToken>) -> Void) -> MXHTTPOperation { return __generateLoginToken(success: currySuccess(completion), failure: curryFailure(completion)) } /** Reset the account password. - parameters: - parameters: a set of parameters containing a threepid credentials and the new password. - completion: A block object called when the operation completes. - response: indicates whether the operation succeeded or not. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func resetPassword(parameters: [String: Any], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __resetPassword(withParameters: parameters, success: currySuccess(completion), failure: curryFailure(completion)) } /** Replace the account password. - parameters: - old: the current password to update. - new: the new password. - logoutDevices flag to log out all devices - completion: A block object called when the operation completes - response: indicates whether the operation succeeded or not. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func changePassword(from old: String, to new: String, logoutDevices: Bool, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __changePassword(old, with: new, logoutDevices: logoutDevices, success: currySuccess(completion), failure: curryFailure(completion)) } /** Invalidate the access token, so that it can no longer be used for authorization. - parameters: - completion: A block object called when the operation completes. - response: Indicates whether the operation succeeded or not. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func logout(completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __logout(currySuccess(completion), failure: curryFailure(completion)) } /** Deactivate the user's account, removing all ability for the user to login again. This API endpoint uses the User-Interactive Authentication API. An access token should be submitted to this endpoint if the client has an active session. The homeserver may change the flows available depending on whether a valid access token is provided. - parameters: - authParameters The additional authentication information for the user-interactive authentication API. - eraseAccount Indicating whether the account should be erased. - completion: A block object called when the operation completes. - response: indicates whether the request succeeded or not. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func deactivateAccount(withAuthParameters authParameters: [String: Any], eraseAccount: Bool, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __deactivateAccount(withAuthParameters: authParameters, eraseAccount: eraseAccount, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Account data /** Set some account_data for the client. - parameters: - data: the new data to set for this event type. - type: The event type of the account_data to set. Custom types should be namespaced to avoid clashes. - completion: A block object called when the operation completes - response: indicates whether the request succeeded or not - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setAccountData(_ data: [String: Any], for type: MXAccountDataType, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setAccountData(data, forType: type.rawValue, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Push Notifications /** Update the pusher for this device on the Home Server. - parameters: - pushkey: The pushkey for this pusher. This should be the APNS token formatted as required for your push gateway (base64 is the recommended formatting). - kind: The kind of pusher your push gateway requires. Generally `.http`. Specify `.none` to disable the pusher. - appId: The app ID of this application as required by your push gateway. - appDisplayName: A human readable display name for this app. - deviceDisplayName: A human readable display name for this device. - profileTag: The profile tag for this device. Identifies this device in push rules. - lang: The user's preferred language for push, eg. 'en' or 'en-US' - data: Dictionary of data as required by your push gateway (generally the notification URI and aps-environment for APNS). - append: If `true`, the homeserver should add another pusher with the given pushkey and App ID in addition to any others with different user IDs. - enabled: Whether the pusher should actively create push notifications - completion: A block object called when the operation succeeds. - response: indicates whether the request succeeded or not. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setPusher(pushKey: String, kind: MXPusherKind, appId: String, appDisplayName: String, deviceDisplayName: String, profileTag: String, lang: String, data: [String: Any], append: Bool, enabled: Bool = true, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setPusherWithPushkey(pushKey, kind: kind.objectValue, appId: appId, appDisplayName: appDisplayName, deviceDisplayName: deviceDisplayName, profileTag: profileTag, lang: lang, data: data, append: append, enabled: enabled, success: currySuccess(completion), failure: curryFailure(completion)) } // TODO: setPusherWithPushKey - futher refinement /* This method is very long. Some of the parameters seem related, specifically: appId, appDisplayName, deviceDisplayName, and profileTag. Perhaps these parameters can be lifted out into a sparate struct? Something like "MXPusherDescriptor"? */ /** Gets all currently active pushers for the authenticated user. - parameters: - response: indicates whether the request succeeded or not. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func pushers(completion: @escaping (_ response: MXResponse<[MXPusher]>) -> Void) -> MXHTTPOperation { return __pushers(currySuccess(completion), failure: curryFailure(completion)) } /** Get all push notifications rules. - parameters: - completion: A block object called when the operation completes. - response: Provides the push rules on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func pushRules(completion: @escaping (_ response: MXResponse<MXPushRulesResponse>) -> Void) -> MXHTTPOperation { return __pushRules(currySuccess(completion), failure: curryFailure(completion)) } /* TODO: Consider refactoring. The following three methods all contain (ruleId:, scope:, kind:). Option 1: Encapsulate those parameters as a tuple or struct called `MXPushRuleDescriptor` This would be appropriate if these three parameters typically get passed around as a set, or if the rule is uniquely identified by this combination of parameters. (eg. one `ruleId` can have different settings for varying scopes and kinds). Option 2: Refactor all of these to a single function that takes a "MXPushRuleAction" as the fourth paramerer. This approach might look like this: enum MXPushRuleAction { case enable case disable case add(actions: [Any], pattern: String, conditions: [[String: Any]]) case remove } func pushRule(ruleId: String, scope: MXPushRuleScope, kind: MXPushRuleKind, action: MXPushRuleAction, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation ? { switch action { case .enable: // ... Call the `enablePushRule` method case .disable: // ... Call the `enablePushRule` method case let .add(actions, pattern, conditions): // ... Call the `addPushRule` method case let .remove: // ... Call the `removePushRule` method } } Option 3: Leave these APIs as-is. */ /** Enable/Disable a push notification rule. - parameters: - ruleId: The identifier for the rule. - scope: Either 'global' or 'device/<profile_tag>' to specify global rules or device rules for the given profile_tag. - kind: The kind of rule, ie. 'override', 'underride', 'sender', 'room', 'content' (see MXPushRuleKind). - enabled: YES to enable - completion: A block object called when the operation completes - response: Indiciates whether the operation was successful - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setPushRuleEnabled(ruleId: String, scope: MXPushRuleScope, kind: MXPushRuleKind, enabled: Bool, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __enablePushRule(ruleId, scope: scope.identifier, kind: kind.identifier, enable: enabled, success: currySuccess(completion), failure: curryFailure(completion)) } /** Remove a push notification rule. - parameters: - ruleId: The identifier for the rule. - scope: Either `.global` or `.device(profileTag:)` to specify global rules or device rules for the given profile_tag. - kind: The kind of rule, ie. `.override`, `.underride`, `.sender`, `.room`, `.content`. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func removePushRule(ruleId: String, scope: MXPushRuleScope, kind: MXPushRuleKind, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __removePushRule(ruleId, scope: scope.identifier, kind: kind.identifier, success: currySuccess(completion), failure: curryFailure(completion)) } /** Create a new push rule. - parameters: - ruleId: The identifier for the rule (it depends on rule kind: user id for sender rule, room id for room rule...). - scope: Either `.global` or `.device(profileTag:)` to specify global rules or device rules for the given profile_tag. - kind: The kind of rule, ie. `.override`, `.underride`, `.sender`, `.room`, `.content`. - actions: The rule actions: notify, don't notify, set tweak... - pattern: The pattern relevant for content rule. - conditions: The conditions relevant for override and underride rule. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func addPushRule(ruleId: String, scope: MXPushRuleScope, kind: MXPushRuleKind, actions: [Any], pattern: String, conditions: [[String: Any]], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __addPushRule(ruleId, scope: scope.identifier, kind: kind.identifier, actions: actions, pattern: pattern, conditions: conditions, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Room operations /** Send a generic non state event to a room. - parameters: - roomId: the id of the room. - threadId: the id of the thread to send the message. nil by default. - eventType: the type of the event. - content: the content that will be sent to the server as a JSON object. - txnId: the transaction id to use. If nil, one will be generated - completion: A block object called when the operation completes. - response: Provides the event id of the event generated on the home server on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func sendEvent(toRoom roomId: String, threadId: String? = nil, eventType: MXEventType, content: [String: Any], txnId: String?, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation { return __sendEvent(toRoom: roomId, threadId: threadId, eventType: eventType.identifier, content: content, txnId: txnId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Send a generic state event to a room. - paramters: - roomId: the id of the room. - eventType: the type of the event. - content: the content that will be sent to the server as a JSON object. - stateKey: the optional state key. - completion: A block object called when the operation completes. - response: Provides the event id of the event generated on the home server on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func sendStateEvent(toRoom roomId: String, eventType: MXEventType, content: [String: Any], stateKey: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation { return __sendStateEvent(toRoom: roomId, eventType: eventType.identifier, content: content, stateKey: stateKey, success: currySuccess(completion), failure: curryFailure(completion)) } /** Send a message to a room - parameters: - roomId: the id of the room. - threadId: the id of the thread to send the message. nil by default. - messageType: the type of the message. - content: the message content that will be sent to the server as a JSON object. - completion: A block object called when the operation completes. - response: Provides the event id of the event generated on the home server on success. -returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func sendMessage(toRoom roomId: String, threadId: String? = nil, messageType: MXMessageType, content: [String: Any], completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation { return __sendMessage(toRoom: roomId, threadId: threadId, msgType: messageType.identifier, content: content, success: currySuccess(completion), failure: curryFailure(completion)) } /** Send a text message to a room - parameters: - roomId: the id of the room. - threadId: the id of the thread to send the message. nil by default. - text: the text to send. - completion: A block object called when the operation completes. - response: Provides the event id of the event generated on the home server on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func sendTextMessage(toRoom roomId: String, threadId: String? = nil, text: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation { return __sendTextMessage(toRoom: roomId, threadId: threadId, text: text, success: currySuccess(completion), failure: curryFailure(completion)) } /** Set the topic of a room. - parameters: - roomId: the id of the room. - topic: the topic to set. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setTopic(ofRoom roomId: String, topic: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setRoomTopic(roomId, topic: topic, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the topic of a room. - parameters: - roomId: the id of the room. - completion: A block object called when the operation completes. - response: Provides the topic of the room on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func topic(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation { return __topic(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Set the avatar of a room. - parameters: - roomId: the id of the room. - avatar: the avatar url to set. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setAvatar(ofRoom roomId: String, avatarUrl: URL, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setRoomAvatar(roomId, avatar: avatarUrl.absoluteString, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the avatar of a room. - parameters: - roomId: the id of the room. - completion: A block object called when the operation completes. - response: Provides the room avatar url on success. - returns: a MXHTTPOperation instance. */ @nonobjc @discardableResult func avatar(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<URL>) -> Void) -> MXHTTPOperation { return __avatar(ofRoom: roomId, success: currySuccess(transform: {return URL(string: $0 ?? "")}, completion), failure: curryFailure(completion)) } /** Set the name of a room. - parameters: - roomId: the id of the room. - name: the name to set. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setName(ofRoom roomId: String, name: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setRoomName(roomId, name: name, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the name of a room. - parameters: - roomId: the id of the room. - completion: A block object called when the operation completes. - response: Provides the room name on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func name(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation { return __name(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Set the history visibility of a room. - parameters: - roomId: the id of the room - historyVisibility: the visibily to set. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setHistoryVisibility(ofRoom roomId: String, historyVisibility: MXRoomHistoryVisibility, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setRoomHistoryVisibility(roomId, historyVisibility: historyVisibility.identifier, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the history visibility of a room. - parameters: - roomId: the id of the room. - completion: A block object called when the operation completes. - response: Provides the room history visibility on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func historyVisibility(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<MXRoomHistoryVisibility>) -> Void) -> MXHTTPOperation { return __historyVisibility(ofRoom: roomId, success: currySuccess(transform: MXRoomHistoryVisibility.init, completion), failure: curryFailure(completion)) } /** Set the join rule of a room. - parameters: - joinRule: the rule to set. - roomId: the id of the room. - allowedParentIds: Optional: list of allowedParentIds (required only for `restricted` join rule as per [MSC3083](https://github.com/matrix-org/matrix-doc/pull/3083) ) - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setRoomJoinRule(_ joinRule: MXRoomJoinRule, forRoomWithId roomId: String, allowedParentIds: [String]?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setRoomJoinRule(joinRule.identifier, forRoomWithId: roomId, allowedParentIds: allowedParentIds, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the enhanced join rule of a room. - parameters: - roomId: the id of the room. - completion: A block object called when the operation completes. It provides the room enhanced join rule as per [MSC3083](https://github.com/matrix-org/matrix-doc/pull/3083. - response: Provides the room join rule on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func joinRule(ofRoomWithId roomId: String, completion: @escaping (_ response: MXResponse<MXRoomJoinRuleResponse>) -> Void) -> MXHTTPOperation { return __joinRuleOfRoom(withId: roomId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Set the guest access of a room. - parameters: - roomId: the id of the room. - guestAccess: the guest access to set. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setGuestAccess(forRoom roomId: String, guestAccess: MXRoomGuestAccess, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setRoomGuestAccess(roomId, guestAccess: guestAccess.identifier, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the guest access of a room. - parameters: - roomId the id of the room. - completion: A block object called when the operation completes. - response: Provides the room guest access on success. - return: a MXHTTPOperation instance. */ @nonobjc @discardableResult func guestAccess(forRoom roomId: String, completion: @escaping (_ response: MXResponse<MXRoomGuestAccess>) -> Void) -> MXHTTPOperation { return __guestAccess(ofRoom: roomId, success: currySuccess(transform: MXRoomGuestAccess.init, completion), failure: curryFailure(completion)) } /** Set the directory visibility of a room on the current homeserver. - parameters: - roomId: the id of the room. - directoryVisibility: the directory visibility to set. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a MXHTTPOperation instance. */ @nonobjc @discardableResult func setDirectoryVisibility(ofRoom roomId: String, directoryVisibility: MXRoomDirectoryVisibility, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setRoomDirectoryVisibility(roomId, directoryVisibility: directoryVisibility.identifier, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the visibility of a room in the current HS's room directory. - parameters: - roomId: the id of the room. - completion: A block object called when the operation completes. - response: Provides the room directory visibility on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func directoryVisibility(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<MXRoomDirectoryVisibility>) -> Void) -> MXHTTPOperation { return __directoryVisibility(ofRoom: roomId, success: currySuccess(transform: MXRoomDirectoryVisibility.init, completion), failure: curryFailure(completion)) } /** Create a new mapping from room alias to room ID. - parameters: - roomId: the id of the room. - roomAlias: the alias to add. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func addAlias(forRoom roomId: String, alias: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __addRoomAlias(roomId, alias: alias, success: currySuccess(completion), failure: curryFailure(completion)) } /** Remove a mapping of room alias to room ID. - parameters: - roomAlias: the alias to remove. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func removeRoomAlias(_ roomAlias: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __removeRoomAlias(roomAlias, success: currySuccess(completion), failure: curryFailure(completion)) } /** Set the canonical alias of the room. - parameters: - roomId: the id of the room. - canonicalAlias: the canonical alias to set. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setCanonicalAlias(forRoom roomId: String, canonicalAlias: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setRoomCanonicalAlias(roomId, canonicalAlias: canonicalAlias, success: currySuccess(completion), failure: curryFailure(completion)); } /** Get the canonical alias. - parameters: - roomId: the id of the room. - completion: A block object called when the operation completes. - response: Provides the canonical alias on success - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func canonicalAlias(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation { return __canonicalAlias(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Join a room, optionally where the user has been invited by a 3PID invitation. - parameters: - roomIdOrAlias: The id or an alias of the room to join. - viaServers The server names to try and join through in addition to those that are automatically chosen. - thirdPartySigned: The signed data obtained by the validation of the 3PID invitation, if 3PID validation is used. The validation is made by `self.signUrl()`. - completion: A block object called when the operation completes. - response: Provides the room id on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func joinRoom(_ roomIdOrAlias: String, viaServers: [String]? = nil, withThirdPartySigned dictionary: [String: Any]? = nil, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation { return __joinRoom(roomIdOrAlias, viaServers: viaServers, withThirdPartySigned: dictionary, success: currySuccess(completion), failure: curryFailure(completion)) } /** Leave a room. - parameters: - roomId: the id of the room to leave. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func leaveRoom(_ roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __leaveRoom(roomId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Invite a user to a room. A user can be invited one of three ways: 1. By their user ID 2. By their email address 3. By a third party The `invitation` parameter specifies how this user should be reached. - parameters: - invitation: the way to reach the user. - roomId: the id of the room. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func invite(_ invitation: MXRoomInvitee, toRoom roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { switch invitation { case .userId(let userId): return __inviteUser(userId, toRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion)) case .email(let emailAddress): return __inviteUser(byEmail: emailAddress, toRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion)) case .thirdPartyId(let descriptor): return __invite(byThreePid: descriptor.medium.identifier, address: descriptor.address, toRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion)) } } /** Kick a user from a room. - parameters: - userId: the user id. - roomId: the id of the room. - reason: the reason for being kicked - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func kickUser(_ userId: String, fromRoom roomId: String, reason: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __kickUser(userId, fromRoom: roomId, reason: reason, success: currySuccess(completion), failure: curryFailure(completion)) } /** Ban a user in a room. - parameters: - userId: the user id. - roomId: the id of the room. - reason: the reason for being banned - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func banUser(_ userId: String, fromRoom roomId: String, reason: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __banUser(userId, inRoom: roomId, reason: reason, success: currySuccess(completion), failure: curryFailure(completion)) } /** Unban a user in a room. - parameters: - userId: the user id. - roomId: the id of the room. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func unbanUser(_ userId: String, fromRoom roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __unbanUser(userId, inRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Create a room. - parameters: - parameters: The parameters for room creation. - completion: A block object called when the operation completes. - response: Provides a MXCreateRoomResponse object on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func createRoom(parameters: MXRoomCreationParameters, completion: @escaping (_ response: MXResponse<MXCreateRoomResponse>) -> Void) -> MXHTTPOperation { return __createRoom(with: parameters, success: currySuccess(completion), failure: curryFailure(completion)) } /** Create a room. - parameters: - parameters: The parameters. Refer to the matrix specification for details. - completion: A block object called when the operation completes. - response: Provides a MXCreateRoomResponse object on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func createRoom(parameters: [String: Any], completion: @escaping (_ response: MXResponse<MXCreateRoomResponse>) -> Void) -> MXHTTPOperation { return __createRoom(parameters, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get a list of messages for this room. - parameters: - roomId: the id of the room. - from: the token to start getting results from. - direction: `MXTimelineDirectionForwards` or `MXTimelineDirectionBackwards` - limit: (optional, use -1 to not defined this value) the maximum nuber of messages to return. - filter: to filter returned events with. - completion: A block object called when the operation completes. - response: Provides a `MXPaginationResponse` object on success. - returns: a MXHTTPOperation instance. */ @nonobjc @discardableResult func messages(forRoom roomId: String, from: String, direction: MXTimelineDirection, limit: UInt?, filter: MXRoomEventFilter, completion: @escaping (_ response: MXResponse<MXPaginationResponse>) -> Void) -> MXHTTPOperation { // The `limit` variable should be set to -1 if it's not provided. let _limit: Int if let limit = limit { _limit = Int(limit) } else { _limit = -1; } return __messages(forRoom: roomId, from: from, direction: direction, limit: _limit, filter: filter, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get a list of members for this room. - parameters: - roomId: the id of the room. - completion: A block object called when the operation completes. - response: Provides an array of `MXEvent` objects that are the type `m.room.member` on success. - returns: a MXHTTPOperation instance. */ @nonobjc @discardableResult func members(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<[MXEvent]>) -> Void) -> MXHTTPOperation { return __members(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get a list of all the current state events for this room. This is equivalent to the events returned under the 'state' key for this room in initialSyncOfRoom. See [the matrix documentation on state events](http://matrix.org/docs/api/client-server/#!/-rooms/get_state_events) for more detail. - parameters: - roomId: the id of the room. - completion: A block object called when the operation completes. - response: Provides the raw home server JSON response on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func state(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<[String: Any]>) -> Void) -> MXHTTPOperation { return __state(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Inform the home server that the user is typing (or not) in this room. - parameters: - roomId: the id of the room. - typing: Use `true` if the user is currently typing. - timeout: the length of time until the user should be treated as no longer typing. Can be set to `nil` if they are no longer typing. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func sendTypingNotification(inRoom roomId: String, typing: Bool, timeout: TimeInterval?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { // The `timeout` variable should be set to -1 if it's not provided. let _timeout: Int if let timeout = timeout { // The `TimeInterval` type is a double value specified in seconds. Multiply by 1000 to get milliseconds. _timeout = Int(timeout * 1000 /* milliseconds */) } else { _timeout = -1; } return __sendTypingNotification(inRoom: roomId, typing: typing, timeout: UInt(_timeout), success: currySuccess(completion), failure: curryFailure(completion)) } /** Redact an event in a room. - parameters: - eventId: the id of the redacted event. - roomId: the id of the room. - reason: the redaction reason. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func redactEvent(_ eventId: String, inRoom roomId: String, reason: String?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __redactEvent(eventId, inRoom: roomId, reason: reason, success: currySuccess(completion), failure: curryFailure(completion)) } /** Report an event. - parameters: - eventId: the id of the event event. - roomId: the id of the room. - score: the metric to let the user rate the severity of the abuse. It ranges from -100 “most offensive” to 0 “inoffensive”. - reason: the redaction reason. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func reportEvent(_ eventId: String, inRoom roomId: String, score: Int, reason: String?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __reportEvent(eventId, inRoom: roomId, score: score, reason: reason, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get all the current information for this room, including messages and state events. See [the matrix documentation](http://matrix.org/docs/api/client-server/#!/-rooms/get_room_sync_data) for more detail. - parameters: - roomId: the id of the room. - limit: the maximum number of messages to return. - completion: A block object called when the operation completes. - response: Provides the model created from the homeserver JSON response on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func intialSync(ofRoom roomId: String, limit: UInt, completion: @escaping (_ response: MXResponse<MXRoomInitialSync>) -> Void) -> MXHTTPOperation { return __initialSync(ofRoom: roomId, withLimit: Int(limit), success: currySuccess(completion), failure: curryFailure(completion)) } /** Retrieve an event from its event id. - parameters: - eventId: the id of the event to get context around. - completion: A block object called when the operation completes. - response: Provides the model created from the homeserver JSON response on success. */ @nonobjc @discardableResult func event(withEventId eventId: String, completion: @escaping (_ response: MXResponse<MXEvent>) -> Void) -> MXHTTPOperation { return __event(withEventId: eventId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Retrieve an event from its room id and event id. - parameters: - eventId: the id of the event to get context around. - roomId: the id of the room to get events from. - completion: A block object called when the operation completes. - response: Provides the model created from the homeserver JSON response on success. */ @nonobjc @discardableResult func event(withEventId eventId: String, inRoom roomId: String, completion: @escaping (_ response: MXResponse<MXEvent>) -> Void) -> MXHTTPOperation { return __event(withEventId: eventId, inRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the context surrounding an event. This API returns a number of events that happened just before and after the specified event. - parameters: - eventId: the id of the event to get context around. - roomId: the id of the room to get events from. - limit: the maximum number of messages to return. - filter the filter to pass in the request. Can be nil. - completion: A block object called when the operation completes. - response: Provides the model created from the homeserver JSON response on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func context(ofEvent eventId: String, inRoom roomId: String, limit: UInt, filter: MXRoomEventFilter? = nil, completion: @escaping (_ response: MXResponse<MXEventContext>) -> Void) -> MXHTTPOperation { return __context(ofEvent: eventId, inRoom: roomId, limit: limit, filter:filter, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the summary of a room - parameters: - roomIdOrAlias: the id of the room or its alias - via: servers, that should be tried to request a summary from, if it can't be generated locally. These can be from a matrix URI, matrix.to link or a `m.space.child` event for example. - completion: A block object called when the operation completes. - response: Provides the model created from the homeserver JSON response on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func roomSummary(with roomIdOrAlias: String, via: [String], completion: @escaping (_ response: MXResponse<MXPublicRoom>) -> Void) -> MXHTTPOperation { return __roomSummary(with: roomIdOrAlias, via: via, success: currySuccess(completion), failure: curryFailure(completion)) } /** Upgrade a room to a new version - parameters: - roomId: the id of the room. - roomVersion: the new room version - completion: A block object called when the operation completes. - response: Provides the ID of the replacement room on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func upgradeRoom(withId roomId: String, to roomVersion: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation { return __upgradeRoom(withId: roomId, to: roomVersion, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Room tags operations /** List the tags of a room. - parameters: - roomId: the id of the room. - completion: A block object called when the operation completes. - response: Provides an array of `MXRoomTag` objects on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func tags(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<[MXRoomTag]>) -> Void) -> MXHTTPOperation { return __tags(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Add a tag to a room. Use this method to update the order of an existing tag. - parameters: - tag: the new tag to add to the room. - order: the order. @see MXRoomTag.order. - roomId: the id of the room. - completion: A block object called when the operation completes. - response: Provides an array of `MXRoomTag` objects on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func addTag(_ tag: String, withOrder order: String, toRoom roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __addTag(tag, withOrder: order, toRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Remove a tag from a room. - parameters: - tag: the tag to remove. - roomId: the id of the room. - completion: A block object called when the operation completes. - response: Provides an array of `MXRoomTag` objects on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func removeTag(_ tag: String, fromRoom roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __removeTag(tag, fromRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Room account data operations /** Update the tagged events - parameters: - roomId: the id of the room. - content: the new tagged events content. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func updateTaggedEvents(_ roomId: String, withContent content: MXTaggedEvents, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __updateTaggedEvents(roomId, withContent: content, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the tagged events of a room - parameters: - roomId: the id of the room. - completion: A block object called when the operation completes. - response: Provides a `MXTaggedEvents` object on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func getTaggedEvents(_ roomId: String, completion: @escaping (_ response: MXResponse<MXTaggedEvents>) -> Void) -> MXHTTPOperation { return __getTaggedEvents(roomId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Set a dedicated room account data field - parameters: - roomId: the id of the room. - eventTypeString: the type of the event. @see MXEventType. - content: the event content. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setRoomAccountData(_ roomId: String, eventType eventTypeString: String, withParameters content: [String: Any], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setRoomAccountData(roomId, eventType: eventTypeString, withParameters: content, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the room account data field - parameters: - roomId: the id of the room. - eventTypeString: the type of the event. @see MXEventType. - completion: A block object called when the operation completes. - response: Provides the raw JSON response from the server. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func getRoomAccountData(_ roomId: String, eventType eventTypeString: String, completion: @escaping (_ response: MXResponse<[String: Any]>) -> Void) -> MXHTTPOperation { return __getRoomAccountData(roomId, eventType: eventTypeString, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Profile operations /** Set the logged-in user display name. - parameters: - displayname: the new display name. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setDisplayName(_ displayName: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setDisplayName(displayName, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the display name of a user. - parameters: - userId: the user id to look up. - completion: A block object called when the operation completes. - response: Provides the display name on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func displayName(forUser userId: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation { return __displayName(forUser: userId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Set the logged-in user avatar url. - parameters: - urlString: The new avatar url. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setAvatarUrl(_ url: URL, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setAvatarUrl(url.absoluteString, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get the avatar url of a user. - parameters: - userId: the user id to look up. - completion: A block object called when the operation completes. - response: Provides the avatar url on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func avatarUrl(forUser userId: String, completion: @escaping (_ response: MXResponse<URL>) -> Void) -> MXHTTPOperation { return __avatarUrl(forUser: userId, success: currySuccess(transform: { return URL(string: $0 ?? "") }, completion), failure: curryFailure(completion)) } /** Get the profile information of a user. - parameters: - userId: the user id to look up. - completion: A block object called when the operation completes. - response: Provides the display name and avatar url if they are defined on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func profile(forUser userId: String, completion: @escaping (_ response: MXResponse<(String?, String?)>) -> Void) -> MXHTTPOperation { return __profile(forUser: userId, success: { (displayName, avatarUrl) -> Void in let profileInformation = (displayName, avatarUrl) completion(MXResponse.success(profileInformation)) }, failure: curryFailure(completion)) } /** Link an authenticated 3rd party id to the Matrix user. This API is deprecated, and you should instead use `addThirdPartyIdentifierOnly` for homeservers that support it. - parameters: - sid: the id provided during the 3PID validation session (MXRestClient.requestEmailValidation). - clientSecret: the same secret key used in the validation session. - bind: whether the homeserver should also bind this third party identifier to the account's Matrix ID with the identity server. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func addThirdPartyIdentifier(_ sid: String, clientSecret: String, bind: Bool, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __add3PID(sid, clientSecret: clientSecret, bind: bind, success: currySuccess(completion), failure: curryFailure(completion)) } /** Add a 3PID to your homeserver account. This API does not use an identity server, as the homeserver is expected to handle 3PID ownership validation. You can check whether a homeserver supports this API via `doesServerSupportSeparateAddAndBind`. - parameters: - sid: the session id provided during the 3PID validation session. - clientSecret: the same secret key used in the validation session. - authParameters: The additional authentication information for the user-interactive authentication API. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func addThirdPartyIdentifierOnly(withSessionId sid: String, clientSecret: String, authParameters: [String: Any]?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __add3PIDOnly(withSessionId: sid, clientSecret: clientSecret, authParams: authParameters, success: currySuccess(completion), failure: curryFailure(completion)) } /** Remove a 3rd party id from the Matrix user information. - parameters: - address: the 3rd party id. - medium: medium the type of the 3rd party id. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func remove3PID(address: String, medium: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __remove3PID(address, medium: medium, success: currySuccess(completion), failure: curryFailure(completion)) } /** List all 3PIDs linked to the Matrix user account. - parameters: - completion: A block object called when the operation completes. - response: Provides the third-party identifiers on success - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func thirdPartyIdentifiers(_ completion: @escaping (_ response: MXResponse<[MXThirdPartyIdentifier]?>) -> Void) -> MXHTTPOperation { return __threePIDs(currySuccess(completion), failure: curryFailure(completion)) } /** Bind a 3PID for discovery onto an identity server via the homeserver. The identity server handles 3PID ownership validation and the homeserver records the new binding to track where all 3PIDs for the account are bound. You can check whether a homeserver supports this API via `doesServerSupportSeparateAddAndBind`. - parameters: - sid: the session id provided during the 3PID validation session. - clientSecret: the same secret key used in the validation session. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func bind3Pid(withSessionId sid: String, clientSecret: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __bind3Pid(withSessionId: sid, clientSecret: clientSecret, success: currySuccess(completion), failure: curryFailure(completion)) } /** Unbind a 3PID for discovery on an identity server via the homeserver. - parameters: - address: the 3rd party id. - medium: medium the type of the 3rd party id. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func unbind3Pid(withAddress address: String, medium: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __unbind3Pid(withAddress: address, medium: medium, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Presence operations // TODO: MXPresence could be refined to a Swift enum. presence+message could be combined in a struct, since they're closely related. /** Set the current user presence status. - parameters: - presence: the new presence status. - statusMessage: the new message status. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setPresence(_ presence: MXPresence, statusMessage: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setPresence(presence, andStatusMessage: statusMessage, success: currySuccess(completion), failure: curryFailure(completion)) } // TODO: MXPresenceResponse smells like a tuple (_ presence: MXPresence, timeActiveAgo: NSTimeInterval). Consider refining further. /** Get the presence status of a user. - parameters: - userId: the user id to look up. - completion: A block object called when the operation completes. - response: Provides the `MXPresenceResponse` on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func presence(forUser userId: String, completion: @escaping (_ response: MXResponse<MXPresenceResponse>) -> Void) -> MXHTTPOperation { return __presence(userId, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Sync /* TODO: This API could be further refined. `token` is an optional string, with nil meaning "initial sync". This could be expressed better as an enum: .initial or .fromToken(String) `presence` appears to support only two possible values: nil or "offline". This could be expressed better as an enum: .online, or .offline (are there any other valid values for this field? why would it be typed as a string?) */ /** Synchronise the client's state and receive new messages. Synchronise the client's state with the latest state on the server. Client's use this API when they first log in to get an initial snapshot of the state on the server, and then continue to call this API to get incremental deltas to the state, and to receive new messages. - parameters: - token: the token to stream from (nil in case of initial sync). - serverTimeout: the maximum time in ms to wait for an event. - clientTimeout: the maximum time in ms the SDK must wait for the server response. - presence: the optional parameter which controls whether the client is automatically marked as online by polling this API. If this parameter is omitted then the client is automatically marked as online when it uses this API. Otherwise if the parameter is set to "offline" then the client is not marked as being online when it uses this API. - filterId: the ID of a filter created using the filter API (optinal). - completion: A block object called when the operation completes. - response: Provides the `MXSyncResponse` on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func sync(fromToken token: String?, serverTimeout: UInt, clientTimeout: UInt, setPresence presence: String?, filterId: String? = nil, completion: @escaping (_ response: MXResponse<MXSyncResponse>) -> Void) -> MXHTTPOperation { return __sync(fromToken: token, serverTimeout: serverTimeout, clientTimeout: clientTimeout, setPresence: presence, filter: filterId, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Directory operations /** Get the list of public rooms hosted by the home server. Pagination parameters (`limit` and `since`) should be used in order to limit homeserver resources usage. - parameters: - server: (optional) the remote server to query for the room list. If nil, get the user homeserver's public room list. - limit: (optional, use -1 to not defined this value) the maximum number of entries to return. - since: (optional) token to paginate from. - filter: (optional) the string to search for. - thirdPartyInstanceId: (optional) returns rooms published to specific lists on a third party instance (like an IRC bridge). - includeAllNetworks: if YES, returns all rooms that have been published to any list. NO to return rooms on the main, default list. - completion: A block object called when the operation is complete. - response: Provides an publicRoomsResponse instance on `success` - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func publicRooms(onServer server: String?, limit: UInt?, since: String? = nil, filter: String? = nil, thirdPartyInstanceId: String? = nil, includeAllNetworks: Bool = false, completion: @escaping (_ response: MXResponse<MXPublicRoomsResponse>) -> Void) -> MXHTTPOperation { // The `limit` variable should be set to -1 if it's not provided. let _limit: Int if let limit = limit { _limit = Int(limit) } else { _limit = -1; } return __publicRooms(onServer: server, limit: _limit, since: since, filter: filter, thirdPartyInstanceId: thirdPartyInstanceId, includeAllNetworks: includeAllNetworks, success: currySuccess(completion), failure: curryFailure(completion)) } /** Resolve given room alias to a room identifier and a list of servers aware of this identifier - parameters: - roomAlias: the alias of the room to look for. - completion: A block object called when the operation completes. - response: Provides a resolution object containing the room ID and a list of servers - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func resolveRoomAlias(_ roomAlias: String, completion: @escaping (_ response: MXResponse<MXRoomAliasResolution>) -> Void) -> MXHTTPOperation { return __resolveRoomAlias(roomAlias, success: currySuccess(completion), failure: curryFailure(completion)) } // Mark: - Media Repository API /** Upload content to HomeServer - parameters: - data: the content to upload. - filename: optional filename - mimetype: the content type (image/jpeg, audio/aac...) - timeout: the maximum time the SDK must wait for the server response. - uploadProgress: A block object called multiple times as the upload progresses. It's also called once the upload is complete - progress: Provides the progress of the upload until it completes. This will provide the URL of the resource on successful completion, or an error message on unsuccessful completion. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func uploadContent(_ data: Data, filename: String? = nil, mimeType: String, timeout: TimeInterval, uploadProgress: @escaping (_ progress: MXProgress<URL>) -> Void) -> MXHTTPOperation { return __uploadContent(data, filename: filename, mimeType: mimeType, timeout: timeout, success: { (urlString) in if let urlString = urlString, let url = URL(string: urlString) { uploadProgress(.success(url)) } else { uploadProgress(.failure(_MXUnknownError())) } }, failure: { (error) in uploadProgress(.failure(error ?? _MXUnknownError())) }, uploadProgress: { (progress) in uploadProgress(.progress(progress!)) }) } // MARK: - VoIP API /** Get the TURN server configuration advised by the homeserver. - parameters: - completion: A block object called when the operation completes. - response: Provides a `MXTurnServerResponse` object (or nil if the HS has TURN config) on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func turnServer(_ completion: @escaping (_ response: MXResponse<MXTurnServerResponse?>) -> Void) -> MXHTTPOperation { return __turnServer(currySuccess(completion), failure: curryFailure(completion)) } // MARK: - read receipt /** Send a read receipt. - parameters: - roomId: the id of the room. - eventId: the id of the event. - threadId: the id of the thread (`nil` for unthreaded RR) - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func sendReadReceipt(toRoom roomId: String, forEvent eventId: String, threadId: String?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __sendReadReceipt(roomId, eventId: eventId, threadId: threadId, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Search /** Search a text in room messages. - parameters: - textPattern: the text to search for in message body. - roomEventFilter: a nullable dictionary which defines the room event filtering during the search request. - beforeLimit: the number of events to get before the matching results. - afterLimit: the number of events to get after the matching results. - nextBatch: the token to pass for doing pagination from a previous response. - completion: A block object called when the operation completes. - response: Provides the search results on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func searchMessages(withPattern textPattern: String, roomEventFilter: MXRoomEventFilter? = nil, beforeLimit: UInt = 0, afterLimit: UInt = 0, nextBatch: String, completion: @escaping (_ response: MXResponse<MXSearchRoomEventResults>) -> Void) -> MXHTTPOperation { return __searchMessages(withText: textPattern, roomEventFilter: roomEventFilter, beforeLimit: beforeLimit, afterLimit: afterLimit, nextBatch: nextBatch, success: currySuccess(completion), failure: curryFailure(completion)) } /** Make a search. - parameters: - parameters: the search parameters as defined by the Matrix search spec (http://matrix.org/docs/api/client-server/#!/Search/post_search ). - nextBatch: the token to pass for doing pagination from a previous response. - completion: A block object called when the operation completes. - response: Provides the search results on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func search(withParameters parameters: [String: Any], nextBatch: String, completion: @escaping (_ response: MXResponse<MXSearchRoomEventResults>) -> Void) -> MXHTTPOperation { return __search(parameters, nextBatch: nextBatch, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Crypto /** Upload device and/or one-time keys. - parameters: - deviceKeys: the device keys to send. - oneTimeKeys: the one-time keys to send. - fallbackKeys: the fallback keys to send - completion: A block object called when the operation completes. - response: Provides information about the keys on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func uploadKeys(_ deviceKeys: [String: Any]?, oneTimeKeys: [String: Any]?, fallbackKeys: [String: Any]?, forDevice deviceId: String? = nil, completion: @escaping (_ response: MXResponse<MXKeysUploadResponse>) -> Void) -> MXHTTPOperation { return __uploadKeys(deviceKeys, oneTimeKeys: oneTimeKeys, fallbackKeys: fallbackKeys, success: currySuccess(completion), failure: curryFailure(completion)) } /** Download device keys. - parameters: - userIds: list of users to get keys for. - token: sync token to pass in the query request, to help the HS give the most recent results. It can be nil. - completion: A block object called when the operation completes. - response: Provides information about the keys on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func downloadKeys(forUsers userIds: [String], token: String? = nil, completion: @escaping (_ response: MXResponse<MXKeysQueryResponse>) -> Void) -> MXHTTPOperation { return __downloadKeys(forUsers: userIds, token: token, success: currySuccess(completion), failure: curryFailure(completion)) } /** Claim one-time keys. - parameters: - usersDevices: a list of users, devices and key types to retrieve keys for. - completion: A block object called when the operation completes. - response: Provides information about the keys on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func claimOneTimeKeys(for usersDevices: MXUsersDevicesMap<NSString>, completion: @escaping (_ response: MXResponse<MXKeysClaimResponse>) -> Void) -> MXHTTPOperation { return __claimOneTimeKeys(forUsersDevices: usersDevices, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Direct-to-device messaging /** Send an event to a specific list of devices - paramaeters: - eventType: the type of event to send - contentMap: content to send. Map from user_id to device_id to content dictionary. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func sendDirectToDevice(eventType: String, contentMap: MXUsersDevicesMap<NSDictionary>, txnId: String?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __send(toDevice: eventType, contentMap: contentMap, txnId: txnId, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Device Management /** Get information about all devices for the current user. - parameters: - completion: A block object called when the operation completes. - response: Provides a list of devices on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func devices(completion: @escaping (_ response: MXResponse<[MXDevice]>) -> Void) -> MXHTTPOperation { return __devices(currySuccess(completion), failure: curryFailure(completion)) } /** Get information on a single device, by device id. - parameters: - deviceId: The device identifier. - completion: A block object called when the operation completes. - response: Provides the requested device on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func device(withId deviceId: String, completion: @escaping (_ response: MXResponse<MXDevice>) -> Void) -> MXHTTPOperation { return __device(byDeviceId: deviceId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Update the display name of a given device. - parameters: - deviceName: The new device name. If not given, the display name is unchanged. - deviceId: The device identifier. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func setDeviceName(_ deviceName: String, forDevice deviceId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __setDeviceName(deviceName, forDeviceId: deviceId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Get an authentication session to delete a device. - parameters: - deviceId: The device identifier. - completion: A block object called when the operation completes. - response: Provides the server response. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func getSession(toDeleteDevice deviceId: String, completion: @escaping (_ response: MXResponse<MXAuthenticationSession>) -> Void) -> MXHTTPOperation { return __getSessionToDeleteDevice(byDeviceId: deviceId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Delete the given device, and invalidates any access token associated with it. This API endpoint uses the User-Interactive Authentication API. - parameters: - deviceId: The device identifier. - authParameters: The additional authentication information for the user-interactive authentication API. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func deleteDevice(_ deviceId: String, authParameters: [String: Any], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __deleteDevice(byDeviceId: deviceId, authParams: authParameters, success: currySuccess(completion), failure: curryFailure(completion)) } /** Deletes the given devices, and invalidates any access token associated with them. @discussion This API endpoint uses the User-Interactive Authentication API. @param deviceIds The identifiers for devices. @param authParameters The additional authentication information for the user-interactive authentication API. @param success A block object called when the operation succeeds. @param failure A block object called when the operation fails. @return a MXHTTPOperation instance. */ @nonobjc @discardableResult func deleteDevices(_ deviceIds: [String], authParameters: [String: Any], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __deleteDevices(byDeviceIds: deviceIds, authParams: authParameters, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Spaces /// Get the space children of a given space. /// - Parameters: /// - spaceId: The room id of the queried space. /// - suggestedOnly: If `true`, return only child events and rooms where the `m.space.child` event has `suggested: true`. /// - limit: Optional. A limit to the maximum number of children to return per space. `-1` for no limit /// - maxDepth: Optional. The maximum depth in the tree (from the root room) to return. `-1` for no limit /// - paginationToken: Optional. Pagination token given to retrieve the next set of rooms. /// - parameters: Space children request parameters. /// - completion: A closure called when the operation completes. /// - Returns: a `MXHTTPOperation` instance. @nonobjc @discardableResult func getSpaceChildrenForSpace(withId spaceId: String, suggestedOnly: Bool, limit: Int?, maxDepth: Int?, paginationToken: String?, completion: @escaping (_ response: MXResponse<MXSpaceChildrenResponse>) -> Void) -> MXHTTPOperation { return __getSpaceChildrenForSpace(withId: spaceId, suggestedOnly: suggestedOnly, limit: limit ?? -1, maxDepth: maxDepth ?? -1, paginationToken: paginationToken, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Home server capabilities /// Get the capabilities of the homeserver /// - Parameters: /// - completion: A closure called when the operation completes. /// - Returns: a `MXHTTPOperation` instance. @nonobjc @discardableResult func homeServerCapabilities(completion: @escaping (_ response: MXResponse<MXHomeserverCapabilities>) -> Void) -> MXHTTPOperation { return __homeServerCapabilities(success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Aggregations /// Get relations for a given event. /// - Parameters: /// - eventId: the id of the event /// - roomId: the id of the room /// - relationType: Optional. The type of relation /// - eventType: Optional. Event type to filter by /// - from: Optional. The token to start getting results from /// - direction: direction from the token /// - limit: Optional. The maximum number of messages to return /// - completion: A closure called when the operation completes. /// - Returns: a `MXHTTPOperation` instance. @nonobjc @discardableResult func relations(forEvent eventId: String, inRoom roomId: String, relationType: String?, eventType: String?, from: String?, direction: MXTimelineDirection, limit: UInt?, completion: @escaping (_ response: MXResponse<MXAggregationPaginatedResponse>) -> Void) -> MXHTTPOperation { let _limit: Int if let limit = limit { _limit = Int(limit) } else { _limit = -1 } return __relations(forEvent: eventId, inRoom: roomId, relationType: relationType, eventType: eventType, from: from, direction: direction, limit: _limit, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Versions /// Get the supported versions of the homeserver /// - Parameters: /// - completion: A closure called when the operation completes. /// - Returns: a `MXHTTPOperation` instance. @nonobjc @discardableResult func supportedMatrixVersions(completion: @escaping (_ response: MXResponse<MXMatrixVersions>) -> Void) -> MXHTTPOperation { return __supportedMatrixVersions(currySuccess(completion), failure: curryFailure(completion)) } }
bb341ea35c81c93a8a2780bdb9e0e285
45.430424
350
0.674208
false
false
false
false
joerocca/GitHawk
refs/heads/master
Classes/Issues/Commit/IssueCommitSectionController.swift
mit
1
// // IssueCommitSectionController.swift // Freetime // // Created by Ryan Nystrom on 7/26/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import IGListKit final class IssueCommitSectionController: ListGenericSectionController<IssueCommitModel>, IssueCommitCellDelegate { private let issueModel: IssueDetailsModel init(issueModel: IssueDetailsModel) { self.issueModel = issueModel super.init() } override func sizeForItem(at index: Int) -> CGSize { guard let width = collectionContext?.containerSize.width else { fatalError("Collection context must be set") } return CGSize(width: width, height: Styles.Sizes.labelEventHeight) } override func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: IssueCommitCell.self, for: self, at: index) as? IssueCommitCell, let object = self.object else { fatalError("Missing collection context, cell incorrect type, or object missing") } cell.configure(object) cell.delegate = self return cell } override func didSelectItem(at index: Int) { guard let hash = object?.hash else { return } viewController?.presentCommit(owner: issueModel.owner, repo: issueModel.repo, hash: hash) } // MARK: IssueCommitCellDelegate func didTapAvatar(cell: IssueCommitCell) { guard let login = object?.login else { return } viewController?.presentProfile(login: login) } }
27c68ae51b2f87e8b559dc7da8cb89ea
32.170213
132
0.695318
false
false
false
false
mrgerych/Cuckoo
refs/heads/master
Generator/Source/CuckooGeneratorFramework/Tokens/FileRepresentation.swift
mit
2
// // FileRepresentation.swift // CuckooGenerator // // Created by Filip Dolnik on 30.05.16. // Copyright © 2016 Brightify. All rights reserved. // import SourceKittenFramework public struct FileRepresentation { public let sourceFile: File public let declarations: [Token] public init(sourceFile: File, declarations: [Token]) { self.sourceFile = sourceFile self.declarations = declarations } } public extension FileRepresentation { public func mergeInheritance(with files: [FileRepresentation]) -> FileRepresentation { let tokens = self.declarations.reduce([Token]()) { list, token in let mergeToken = token.mergeInheritance(with: files) return list + [mergeToken] } return FileRepresentation(sourceFile: self.sourceFile, declarations: tokens) } } internal extension Token { internal func mergeInheritance(with files: [FileRepresentation]) -> Token { guard let typeToken = self as? ContainerToken else { return self } let inheritedRepresentations: [Token] = typeToken.inheritedTypes .flatMap { Self.findToken(forClassOrProtocol: $0.name, in: files) } .flatMap { $0.mergeInheritance(with: files) } // Merge super declarations let mergedTokens = inheritedRepresentations.filter { $0.isClassOrProtocolDefinition } .map { $0 as! ContainerToken } .flatMap { $0.children } .reduce(typeToken.children) { tokens, inheritedToken in if (tokens.contains { $0 == inheritedToken }) { return tokens } return tokens + [inheritedToken] } switch typeToken { case let classToken as ClassDeclaration: return classToken.replace(children: mergedTokens) case let protocolToken as ProtocolDeclaration: return protocolToken.replace(children: mergedTokens) default: return typeToken } } internal static func findToken(forClassOrProtocol name: String, in files: [FileRepresentation]) -> Token? { return files.flatMap { $0.declarations } .filter { $0.isClassOrProtocolDefinition } .map { $0 as! ContainerToken } .first { $0.name == name } } }
caf60591195a1a6fa9c6ccd2d7bc0b2a
34.820896
111
0.619425
false
false
false
false
AboutObjectsTraining/swift-comp-reston-2017-02
refs/heads/master
labs/SwiftProgramming/SwiftBasics.playground/Contents.swift
mit
1
// Copyright (C) 2015 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this example's licensing information. print("Have a nice day.") let message = "Have a nice day" print(message) let temperature = 72 print("It's currently \(temperature) degrees") var width: Int // defines variable 'width' of type Int // width++ // Illegal because width uninitialized var x, y, z: Int var i = 0, j = 0 let pi = 3.14159 // pi += 2.0 // illegal because pi is a constant
2dae2d3fbc9f7d4a95bc1105080b71a9
23.3
62
0.68107
false
false
false
false
exchangegroup/paged-scroll-view-with-images
refs/heads/master
paged-scroll-view-with-images/TegPagedImagesCellView.swift
mit
2
// // PagesImagesCell.swift // paged-scroll-view-with-images // import UIKit class TegPagedImagesCellView: UIView { var url: String? weak var delegate: TegPagedImagesCellViewDelegate? private let imageView = UIImageView() private var downloadManager: TegSingleImageDownloadManager? private let settings: TegPagedImagesSettings init(frame: CGRect, settings: TegPagedImagesSettings) { self.settings = settings super.init(frame: frame) TegPagedImagesCellView.setupImageView(imageView, size: frame.size, contentMode: settings.contentMode) addSubview(imageView) clipsToBounds = true setupTap() } private func setupTap() { let tapGesture = UITapGestureRecognizer(target: self, action: "respondToTap:") addGestureRecognizer(tapGesture) } func respondToTap(gesture: UITapGestureRecognizer) { if downloadManager != nil { return } // downloading if let image = imageView.image { delegate?.tegPagedImagesCellViewDelegate_onImageTapped(image, gesture: gesture) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func showImage(image: UIImage) { imageView.alpha = 1 imageView.image = image } private class func setupImageView(imageView: UIImageView, size: CGSize, contentMode: UIViewContentMode) { imageView.frame = CGRect(origin: CGPoint(), size: size) imageView.contentMode = contentMode } // Called each time the cell is visible on screen when scrolling. // Note: called frequently on each scroll event. func cellIsVisible() { downloadImage() } // Called when cell is not visible on screen. Opposite of cellIsVisible method func cellIsInvisible() { cancelImageDownload() } func cancelImageDownload() { downloadManager = nil } private func downloadImage() { if downloadManager != nil { return } // already downloading if let url = url { downloadManager = settings.singleImageDownloadImageFactory.create() downloadManager?.download(fromUrl: url) { [weak self] image in self?.imagedDownloadComplete(image) } } } private func imagedDownloadComplete(image: UIImage) { url = nil downloadManager = nil fadeInImage(image) } func fadeInImage(image: UIImage, showOnlyIfNoImageShown: Bool = false) { let tempImageView = UIImageView(image: image) addSubview(tempImageView) TegPagedImagesCellView.setupImageView(tempImageView, size: frame.size, contentMode: settings.contentMode) tempImageView.alpha = 0 UIView.animateWithDuration(settings.fadeInAnimationDuration, animations: { [weak self] in tempImageView.alpha = 1 self?.imageView.alpha = 0 }, completion: { [weak self] finished in if !showOnlyIfNoImageShown || self?.imageView.image == nil { self?.showImage(image) } tempImageView.removeFromSuperview() } ) } }
fb2d1a841460fe5801b2ac59b6bb980a
26.423423
105
0.687911
false
false
false
false
Paludis/Swifter
refs/heads/master
Swifter/Swifter.swift
mit
1
// // Swifter.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import Accounts public class Swifter { // MARK: - Types public typealias JSONSuccessHandler = (json: JSON, response: NSHTTPURLResponse) -> Void public typealias FailureHandler = (error: NSError) -> Void internal struct CallbackNotification { static let notificationName = "SwifterCallbackNotificationName" static let optionsURLKey = "SwifterCallbackNotificationOptionsURLKey" } internal struct SwifterError { static let domain = "SwifterErrorDomain" static let appOnlyAuthenticationErrorCode = 1 } internal struct DataParameters { static let dataKey = "SwifterDataParameterKey" static let fileNameKey = "SwifterDataParameterFilename" } // MARK: - Properties internal(set) var apiURL: NSURL internal(set) var uploadURL: NSURL internal(set) var streamURL: NSURL internal(set) var userStreamURL: NSURL internal(set) var siteStreamURL: NSURL public var client: SwifterClientProtocol // MARK: - Initializers public convenience init(consumerKey: String, consumerSecret: String) { self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, appOnly: false) } public init(consumerKey: String, consumerSecret: String, appOnly: Bool) { if appOnly { self.client = SwifterAppOnlyClient(consumerKey: consumerKey, consumerSecret: consumerSecret) } else { self.client = SwifterOAuthClient(consumerKey: consumerKey, consumerSecret: consumerSecret) } self.apiURL = NSURL(string: "https://api.twitter.com/1.1/")! self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/")! self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/")! self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/")! self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/")! } public init(consumerKey: String, consumerSecret: String, oauthToken: String, oauthTokenSecret: String) { self.client = SwifterOAuthClient(consumerKey: consumerKey, consumerSecret: consumerSecret , accessToken: oauthToken, accessTokenSecret: oauthTokenSecret) self.apiURL = NSURL(string: "https://api.twitter.com/1.1/")! self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/")! self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/")! self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/")! self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/")! } public init(account: ACAccount) { self.client = SwifterAccountsClient(account: account) self.apiURL = NSURL(string: "https://api.twitter.com/1.1/")! self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/")! self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/")! self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/")! self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/")! } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - JSON Requests internal func jsonRequestWithPath(path: String, baseURL: NSURL, method: String, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler? = nil, downloadProgress: JSONSuccessHandler? = nil, success: JSONSuccessHandler? = nil, failure: SwifterHTTPRequest.FailureHandler? = nil) -> SwifterHTTPRequest { let jsonDownloadProgressHandler: SwifterHTTPRequest.DownloadProgressHandler = { data, _, _, response in if downloadProgress == nil { return } var error: NSError? do { let jsonResult = try JSON.parseJSONData(data) downloadProgress?(json: jsonResult, response: response) } catch var error2 as NSError { error = error2 let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding) let jsonChunks = jsonString!.componentsSeparatedByString("\r\n") for chunk in jsonChunks { if chunk.utf16.count == 0 { continue } let chunkData = chunk.dataUsingEncoding(NSUTF8StringEncoding) do { let jsonResult = try JSON.parseJSONData(data) if let downloadProgress = downloadProgress { downloadProgress(json: jsonResult, response: response) } } catch var error1 as NSError { error = error1 } catch { fatalError() } } } catch { fatalError() } } let jsonSuccessHandler: SwifterHTTPRequest.SuccessHandler = { data, response in dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)) { var error: NSError? do { let jsonResult = try JSON.parseJSONData(data) dispatch_async(dispatch_get_main_queue()) { if let success = success { success(json: jsonResult, response: response) } } } catch var error1 as NSError { error = error1 dispatch_async(dispatch_get_main_queue()) { if let failure = failure { failure(error: error!) } } } catch { fatalError() } } } if method == "GET" { return self.client.get(path, baseURL: baseURL, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: jsonDownloadProgressHandler, success: jsonSuccessHandler, failure: failure) } else { return self.client.post(path, baseURL: baseURL, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: jsonDownloadProgressHandler, success: jsonSuccessHandler, failure: failure) } } internal func getJSONWithPath(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: JSONSuccessHandler?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest { return self.jsonRequestWithPath(path, baseURL: baseURL, method: "GET", parameters: parameters, uploadProgress: uploadProgress, downloadProgress: downloadProgress, success: success, failure: failure) } internal func postJSONWithPath(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: JSONSuccessHandler?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest { return self.jsonRequestWithPath(path, baseURL: baseURL, method: "POST", parameters: parameters, uploadProgress: uploadProgress, downloadProgress: downloadProgress, success: success, failure: failure) } }
f016f165c16dc72bbc0e999b757781b9
44.539683
341
0.643895
false
false
false
false
muneikh/xmpp-messenger-ios
refs/heads/master
Example/xmpp-messenger-ios/ChatViewController.swift
mit
1
// // ChatViewController.swift // OneChat // // Created by Paul on 20/02/2015. // Copyright (c) 2015 ProcessOne. All rights reserved. // import UIKit //import xmpp_messenger_ios import JSQMessagesViewController import XMPPFramework class ChatViewController: JSQMessagesViewController, OneMessageDelegate, ContactPickerDelegate { let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate var messages = NSMutableArray() var recipient: XMPPUserCoreDataStorageObject? var firstTime = true var userDetails = UIView?() // Mark: Life Cycle override func viewDidLoad() { super.viewDidLoad() OneMessage.sharedInstance.delegate = self if OneChat.sharedInstance.isConnected() { self.senderId = OneChat.sharedInstance.xmppStream?.myJID.bare() self.senderDisplayName = OneChat.sharedInstance.xmppStream?.myJID.bare() } self.collectionView!.collectionViewLayout.springinessEnabled = false self.inputToolbar!.contentView!.leftBarButtonItem!.hidden = true } override func viewWillAppear(animated: Bool) { if let recipient = recipient { self.navigationItem.rightBarButtonItems = [] navigationItem.title = recipient.displayName /* Mark: Adding LastActivity functionality to NavigationBar OneLastActivity.sendLastActivityQueryToJID((recipient.jidStr), sender: OneChat.sharedInstance.xmppLastActivity) { (response, forJID, error) -> Void in let lastActivityResponse = OneLastActivity.sharedInstance.getLastActivityFrom((response?.lastActivitySeconds())!) self.userDetails = OneLastActivity.sharedInstance.addLastActivityLabelToNavigationBar(lastActivityResponse, displayName: recipient.displayName) self.navigationController!.view.addSubview(self.userDetails!) if (self.userDetails != nil) { self.navigationItem.title = "" } } */ dispatch_async(dispatch_get_main_queue(), { () -> Void in // self.messages = OneMessage.sharedInstance.loadArchivedMessagesFrom(jid: recipient.jidStr) self.messages = OneMessage.sharedInstance.loadArchivedMessagesFrom(jid: recipient.jidStr,thread: "") self.finishReceivingMessageAnimated(true) }) } else { if userDetails == nil { navigationItem.title = "New message" } self.inputToolbar!.contentView!.rightBarButtonItem!.enabled = false self.navigationItem.setRightBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(ChatViewController.addRecipient)), animated: true) if firstTime { firstTime = false addRecipient() } } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.scrollToBottomAnimated(true) } override func viewWillDisappear(animated: Bool) { userDetails?.removeFromSuperview() } // Mark: Private methods func addRecipient() { let navController = self.storyboard?.instantiateViewControllerWithIdentifier("contactListNav") as? UINavigationController let contactController: ContactListTableViewController? = navController?.viewControllers[0] as? ContactListTableViewController contactController?.delegate = self self.presentViewController(navController!, animated: true, completion: nil) } func didSelectContact(recipient: XMPPUserCoreDataStorageObject) { self.recipient = recipient if userDetails == nil { navigationItem.title = recipient.displayName } if !OneChats.knownUserForJid(jidStr: recipient.jidStr) { OneChats.addUserToChatList(jidStr: recipient.jidStr) } else { // messages = OneMessage.sharedInstance.loadArchivedMessagesFrom(jid: recipient.jidStr) messages = OneMessage.sharedInstance.loadArchivedMessagesFrom(jid: recipient.jidStr,thread: "") finishReceivingMessageAnimated(true) } } // Mark: JSQMessagesViewController method overrides var isComposing = false var timer: NSTimer? override func textViewDidChange(textView: UITextView) { super.textViewDidChange(textView) if textView.text.characters.count == 0 { if isComposing { hideTypingIndicator() } } else { timer?.invalidate() if !isComposing { self.isComposing = true // OneMessage.sendIsComposingMessage((recipient?.jidStr)!, completionHandler: { (stream, message) -> Void in OneMessage.sendIsComposingMessage((recipient?.jidStr)!,thread:"" , completionHandler: { (stream, message) -> Void in self.timer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: #selector(ChatViewController.hideTypingIndicator), userInfo: nil, repeats: false) }) } else { self.timer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: #selector(ChatViewController.hideTypingIndicator), userInfo: nil, repeats: false) } } } func hideTypingIndicator() { if let recipient = recipient { self.isComposing = false // OneMessage.sendIsComposingMessage((recipient.jidStr)!, completionHandler: { (stream, message) -> Void in OneMessage.sendIsComposingMessage((recipient.jidStr)!,thread: "", completionHandler: { (stream, message) -> Void in }) } } override func didPressSendButton(button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: NSDate!) { let fullMessage = JSQMessage(senderId: OneChat.sharedInstance.xmppStream?.myJID.bare(), senderDisplayName: OneChat.sharedInstance.xmppStream?.myJID.bare(), date: NSDate(), text: text) messages.addObject(fullMessage) if let recipient = recipient { // OneMessage.sendMessage(text, to: recipient.jidStr, completionHandler: { (stream, message) -> Void in OneMessage.sendMessage(text, thread: "", to: recipient.jidStr, completionHandler: { (stream, message) -> Void in JSQSystemSoundPlayer.jsq_playMessageSentSound() self.finishSendingMessageAnimated(true) }) } } // Mark: JSQMessages CollectionView DataSource override func collectionView(collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! { let message: JSQMessage = self.messages[indexPath.item] as! JSQMessage return message } override func collectionView(collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource! { let message: JSQMessage = self.messages[indexPath.item] as! JSQMessage let bubbleFactory = JSQMessagesBubbleImageFactory() let outgoingBubbleImageData = bubbleFactory.outgoingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleLightGrayColor()) let incomingBubbleImageData = bubbleFactory.incomingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleGreenColor()) if message.senderId == self.senderId { return outgoingBubbleImageData } return incomingBubbleImageData } override func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! { let message: JSQMessage = self.messages[indexPath.item] as! JSQMessage if message.senderId == self.senderId { if let photoData = OneChat.sharedInstance.xmppvCardAvatarModule?.photoDataForJID(OneChat.sharedInstance.xmppStream?.myJID) { let senderAvatar = JSQMessagesAvatarImageFactory.avatarImageWithImage(UIImage(data: photoData), diameter: 30) return senderAvatar } else { let senderAvatar = JSQMessagesAvatarImageFactory.avatarImageWithUserInitials("SR", backgroundColor: UIColor(white: 0.85, alpha: 1.0), textColor: UIColor(white: 0.60, alpha: 1.0), font: UIFont(name: "Helvetica Neue", size: 14.0), diameter: 30) return senderAvatar } } else { if let photoData = OneChat.sharedInstance.xmppvCardAvatarModule?.photoDataForJID(recipient!.jid!) { let recipientAvatar = JSQMessagesAvatarImageFactory.avatarImageWithImage(UIImage(data: photoData), diameter: 30) return recipientAvatar } else { let recipientAvatar = JSQMessagesAvatarImageFactory.avatarImageWithUserInitials("SR", backgroundColor: UIColor(white: 0.85, alpha: 1.0), textColor: UIColor(white: 0.60, alpha: 1.0), font: UIFont(name: "Helvetica Neue", size: 14.0)!, diameter: 30) return recipientAvatar } } } override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! { if indexPath.item % 3 == 0 { let message: JSQMessage = self.messages[indexPath.item] as! JSQMessage return JSQMessagesTimestampFormatter.sharedFormatter().attributedTimestampForDate(message.date) } return nil; } override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! { let message: JSQMessage = self.messages[indexPath.item] as! JSQMessage if message.senderId == self.senderId { return nil } if indexPath.item - 1 > 0 { let previousMessage: JSQMessage = self.messages[indexPath.item - 1] as! JSQMessage if previousMessage.senderId == message.senderId { return nil } } return nil } override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! { return nil } // Mark: UICollectionView DataSource override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.messages.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell: JSQMessagesCollectionViewCell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell let msg: JSQMessage = self.messages[indexPath.item] as! JSQMessage if !msg.isMediaMessage { if msg.senderId == self.senderId { cell.textView!.textColor = UIColor.blackColor() cell.textView!.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.blackColor(), NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue] } else { cell.textView!.textColor = UIColor.whiteColor() cell.textView!.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor(), NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue] } } return cell } // Mark: JSQMessages collection view flow layout delegate override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat { if indexPath.item % 3 == 0 { return kJSQMessagesCollectionViewCellLabelHeightDefault } return 0.0 } override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat { let currentMessage: JSQMessage = self.messages[indexPath.item] as! JSQMessage if currentMessage.senderId == self.senderId { return 0.0 } if indexPath.item - 1 > 0 { let previousMessage: JSQMessage = self.messages[indexPath.item - 1] as! JSQMessage if previousMessage.senderId == currentMessage.senderId { return 0.0 } } return kJSQMessagesCollectionViewCellLabelHeightDefault } override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat { return 0.0 } // Mark: Chat message Delegates func oneStream(sender: XMPPStream, didReceiveMessage message: XMPPMessage, from user: XMPPUserCoreDataStorageObject) { if message.isChatMessageWithBody() { //let displayName = user.displayName JSQSystemSoundPlayer.jsq_playMessageReceivedSound() // if let msg: String = message.elementForName("body")?.stringValue() { if let msg: String = message.elementForName("body")?.stringValue! { // if let from: String = message.attributeForName("from")?.stringValue() { if let from: String = message.attributeForName("from")?.stringValue { let message = JSQMessage(senderId: from, senderDisplayName: from, date: NSDate(), text: msg) messages.addObject(message) self.finishReceivingMessageAnimated(true) } } } } func oneStream(sender: XMPPStream, userIsComposing user: XMPPUserCoreDataStorageObject) { self.showTypingIndicator = !self.showTypingIndicator self.scrollToBottomAnimated(true) } // Mark: Memory Management override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
7339e80e31fbce85af553be9f3952a92
40.626168
250
0.734621
false
false
false
false
NeoTeo/SwiftIpfsApi
refs/heads/master
SwiftIpfsApi/Multipart.swift
mit
2
// // Multipart.swift // SwiftIpfsApi // // Created by Matteo Sartori on 20/10/15. // Copyright © 2015 Teo Sartori. All rights reserved. // // Licensed under MIT See LICENCE file in the root of this project for details. import Foundation public enum MultipartError : Error { case failedURLCreation case invalidEncoding } public struct Multipart { static let lineFeed:String = "\r\n" let boundary: String let encoding: String.Encoding let charset: String var body = NSMutableData() let request: NSMutableURLRequest init(targetUrl: String, encoding: String.Encoding) throws { // Eg. UTF8 self.encoding = encoding guard let charset = Multipart.charsetString(from: encoding) else { throw MultipartError.invalidEncoding } self.charset = charset boundary = Multipart.createBoundary() guard let url = URL(string: targetUrl) else { throw MultipartError.failedURLCreation } request = NSMutableURLRequest(url: url) request.httpMethod = "POST" request.setValue("multipart/form-data; boundary="+boundary, forHTTPHeaderField: "content-type") request.setValue("Swift IPFS Client", forHTTPHeaderField: "user-agent") } } extension Multipart { static func charsetString(from encoding: String.Encoding) -> String? { switch encoding { case String.Encoding.utf8: return "UTF8" case String.Encoding.ascii: return "ASCII" default: return nil } } /// Generate a string of 32 random alphanumeric characters. static func createBoundary() -> String { let allowed = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" let maxCount = allowed.count let count = 32 var output = "" for _ in 0 ..< count { let r = Int(arc4random_uniform(UInt32(maxCount))) let randomIndex = allowed.index(allowed.startIndex, offsetBy: r) output += String(allowed[randomIndex]) } return output } static func addFormField(oldMultipart: Multipart, name: String, value: String) throws -> Multipart { let encoding = oldMultipart.encoding var outString = "--" + oldMultipart.boundary + lineFeed oldMultipart.body.append(outString.data(using: encoding)!) outString = "content-disposition: form-data; name=\"" + name + "\"" + lineFeed oldMultipart.body.append(outString.data(using: encoding)!) outString = "content-type: text/plain; charset=\"" + oldMultipart.charset + "\"" + lineFeed oldMultipart.body.append(outString.data(using: encoding)!) oldMultipart.body.append(lineFeed.data(using: encoding)!) oldMultipart.body.append(value.data(using: encoding)!) oldMultipart.body.append(lineFeed.data(using: encoding)!) return oldMultipart } static func addDirectoryPart(oldMultipart: Multipart, path: String) throws -> Multipart { let encoding = oldMultipart.encoding var outString = "--" + oldMultipart.boundary + lineFeed oldMultipart.body.append(outString.data(using: encoding)!) outString = "content-disposition: file; filename=\"\(path)\"" + lineFeed oldMultipart.body.append(outString.data(using: encoding)!) outString = "content-type: application/x-directory" + lineFeed oldMultipart.body.append(outString.data(using: encoding)!) outString = "content-transfer-encoding: binary" + lineFeed oldMultipart.body.append(outString.data(using: encoding)!) oldMultipart.body.append(lineFeed.data(using: encoding)!) oldMultipart.body.append(lineFeed.data(using: encoding)!) return oldMultipart } public static func addFilePart(_ oldMultipart: Multipart, fileName: String?, fileData: Data) throws -> Multipart { var outString = "--" + oldMultipart.boundary + lineFeed oldMultipart.body.append(outString.data(using: String.Encoding.utf8)!) if fileName != nil { outString = "content-disposition: file; filename=\"\(fileName!)\";" + lineFeed } else { outString = "content-disposition: file; name=\"file\";" + lineFeed } oldMultipart.body.append(outString.data(using: String.Encoding.utf8)!) outString = "content-type: application/octet-stream" + lineFeed oldMultipart.body.append(outString.data(using: String.Encoding.utf8)!) outString = "content-transfer-encoding: binary" + lineFeed + lineFeed oldMultipart.body.append(outString.data(using: String.Encoding.utf8)!) /// Add the actual data for this file. oldMultipart.body.append(fileData) oldMultipart.body.append(lineFeed.data(using: String.Encoding.utf8)!) return oldMultipart } public static func finishMultipart(_ multipart: Multipart, completionHandler: @escaping (Data) -> Void) { let outString = "--" + multipart.boundary + "--" + lineFeed multipart.body.append(outString.data(using: String.Encoding.utf8)!) multipart.request.setValue(String(multipart.body.length), forHTTPHeaderField: "content-length") multipart.request.httpBody = multipart.body as Data /// Send off the request let task = URLSession.shared.dataTask(with: (multipart.request as URLRequest)) { (data: Data?, response: URLResponse?, error: Error?) -> Void in // FIXME: use Swift 5 Result type rather than passing nil data. if error != nil || data == nil { print("Error in dataTaskWithRequest: \(String(describing: error))") let emptyData = Data() completionHandler(emptyData) return } completionHandler(data!) } task.resume() } }
7e87901db67be48748021ebeb89e45b9
35.128655
118
0.623665
false
false
false
false
zisko/swift
refs/heads/master
stdlib/public/core/Equatable.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Equatable //===----------------------------------------------------------------------===// /// A type that can be compared for value equality. /// /// Types that conform to the `Equatable` protocol can be compared for equality /// using the equal-to operator (`==`) or inequality using the not-equal-to /// operator (`!=`). Most basic types in the Swift standard library conform to /// `Equatable`. /// /// Some sequence and collection operations can be used more simply when the /// elements conform to `Equatable`. For example, to check whether an array /// contains a particular value, you can pass the value itself to the /// `contains(_:)` method when the array's element conforms to `Equatable` /// instead of providing a closure that determines equivalence. The following /// example shows how the `contains(_:)` method can be used with an array of /// strings. /// /// let students = ["Nora", "Fern", "Ryan", "Rainer"] /// /// let nameToCheck = "Ryan" /// if students.contains(nameToCheck) { /// print("\(nameToCheck) is signed up!") /// } else { /// print("No record of \(nameToCheck).") /// } /// // Prints "Ryan is signed up!" /// /// Conforming to the Equatable Protocol /// ==================================== /// /// Adding `Equatable` conformance to your custom types means that you can use /// more convenient APIs when searching for particular instances in a /// collection. `Equatable` is also the base protocol for the `Hashable` and /// `Comparable` protocols, which allow more uses of your custom type, such as /// constructing sets or sorting the elements of a collection. /// /// You can rely on automatic synthesis of the `Equatable` protocol's /// requirements for a custom type when you declare `Equatable` conformance in /// the type's original declaration and your type meets these criteria: /// /// - For a `struct`, all its stored properties must conform to `Equatable`. /// - For an `enum`, all its associated values must conform to `Equatable`. (An /// `enum` without associated values has `Equatable` conformance even /// without the declaration.) /// /// To customize your type's `Equatable` conformance, to adopt `Equatable` in a /// type that doesn't meet the criteria listed above, or to extend an existing /// type to conform to `Equatable`, implement the equal-to operator (`==`) as /// a static method of your type. The standard library provides an /// implementation for the not-equal-to operator (`!=`) for any `Equatable` /// type, which calls the custom `==` function and negates its result. /// /// As an example, consider a `StreetAddress` class that holds the parts of a /// street address: a house or building number, the street name, and an /// optional unit number. Here's the initial declaration of the /// `StreetAddress` type: /// /// class StreetAddress { /// let number: String /// let street: String /// let unit: String? /// /// init(_ number: String, _ street: String, unit: String? = nil) { /// self.number = number /// self.street = street /// self.unit = unit /// } /// } /// /// Now suppose you have an array of addresses that you need to check for a /// particular address. To use the `contains(_:)` method without including a /// closure in each call, extend the `StreetAddress` type to conform to /// `Equatable`. /// /// extension StreetAddress: Equatable { /// static func == (lhs: StreetAddress, rhs: StreetAddress) -> Bool { /// return /// lhs.number == rhs.number && /// lhs.street == rhs.street && /// lhs.unit == rhs.unit /// } /// } /// /// The `StreetAddress` type now conforms to `Equatable`. You can use `==` to /// check for equality between any two instances or call the /// `Equatable`-constrained `contains(_:)` method. /// /// let addresses = [StreetAddress("1490", "Grove Street"), /// StreetAddress("2119", "Maple Avenue"), /// StreetAddress("1400", "16th Street")] /// let home = StreetAddress("1400", "16th Street") /// /// print(addresses[0] == home) /// // Prints "false" /// print(addresses.contains(home)) /// // Prints "true" /// /// Equality implies substitutability---any two instances that compare equally /// can be used interchangeably in any code that depends on their values. To /// maintain substitutability, the `==` operator should take into account all /// visible aspects of an `Equatable` type. Exposing nonvalue aspects of /// `Equatable` types other than class identity is discouraged, and any that /// *are* exposed should be explicitly pointed out in documentation. /// /// Since equality between instances of `Equatable` types is an equivalence /// relation, any of your custom types that conform to `Equatable` must /// satisfy three conditions, for any values `a`, `b`, and `c`: /// /// - `a == a` is always `true` (Reflexivity) /// - `a == b` implies `b == a` (Symmetry) /// - `a == b` and `b == c` implies `a == c` (Transitivity) /// /// Moreover, inequality is the inverse of equality, so any custom /// implementation of the `!=` operator must guarantee that `a != b` implies /// `!(a == b)`. The default implementation of the `!=` operator function /// satisfies this requirement. /// /// Equality is Separate From Identity /// ---------------------------------- /// /// The identity of a class instance is not part of an instance's value. /// Consider a class called `IntegerRef` that wraps an integer value. Here's /// the definition for `IntegerRef` and the `==` function that makes it /// conform to `Equatable`: /// /// class IntegerRef: Equatable { /// let value: Int /// init(_ value: Int) { /// self.value = value /// } /// /// static func == (lhs: IntegerRef, rhs: IntegerRef) -> Bool { /// return lhs.value == rhs.value /// } /// } /// /// The implementation of the `==` function returns the same value whether its /// two arguments are the same instance or are two different instances with /// the same integer stored in their `value` properties. For example: /// /// let a = IntegerRef(100) /// let b = IntegerRef(100) /// /// print(a == a, a == b, separator: ", ") /// // Prints "true, true" /// /// Class instance identity, on the other hand, is compared using the /// triple-equals identical-to operator (`===`). For example: /// /// let c = a /// print(c === a, c === b, separator: ", ") /// // Prints "true, false" public protocol Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. static func == (lhs: Self, rhs: Self) -> Bool } extension Equatable { /// Returns a Boolean value indicating whether two values are not equal. /// /// Inequality is the inverse of equality. For any values `a` and `b`, `a != b` /// implies that `a == b` is `false`. /// /// This is the default implementation of the not-equal-to operator (`!=`) /// for any type that conforms to `Equatable`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. @_inlineable // FIXME(sil-serialize-all) @_transparent public static func != (lhs: Self, rhs: Self) -> Bool { return !(lhs == rhs) } } //===----------------------------------------------------------------------===// // Reference comparison //===----------------------------------------------------------------------===// /// Returns a Boolean value indicating whether two references point to the same /// object instance. /// /// This operator tests whether two instances have the same identity, not the /// same value. For value equality, see the equal-to operator (`==`) and the /// `Equatable` protocol. /// /// The following example defines an `IntegerRef` type, an integer type with /// reference semantics. /// /// class IntegerRef: Equatable { /// let value: Int /// init(_ value: Int) { /// self.value = value /// } /// } /// /// func ==(lhs: IntegerRef, rhs: IntegerRef) -> Bool { /// return lhs.value == rhs.value /// } /// /// Because `IntegerRef` is a class, its instances can be compared using the /// identical-to operator (`===`). In addition, because `IntegerRef` conforms /// to the `Equatable` protocol, instances can also be compared using the /// equal-to operator (`==`). /// /// let a = IntegerRef(10) /// let b = a /// print(a == b) /// // Prints "true" /// print(a === b) /// // Prints "true" /// /// The identical-to operator (`===`) returns `false` when comparing two /// references to different object instances, even if the two instances have /// the same value. /// /// let c = IntegerRef(10) /// print(a == c) /// // Prints "true" /// print(a === c) /// // Prints "false" /// /// - Parameters: /// - lhs: A reference to compare. /// - rhs: Another reference to compare. @_inlineable // FIXME(sil-serialize-all) public func === (lhs: AnyObject?, rhs: AnyObject?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return ObjectIdentifier(l) == ObjectIdentifier(r) case (nil, nil): return true default: return false } } /// Returns a Boolean value indicating whether two references point to /// different object instances. /// /// This operator tests whether two instances have different identities, not /// different values. For value inequality, see the not-equal-to operator /// (`!=`) and the `Equatable` protocol. /// /// - Parameters: /// - lhs: A reference to compare. /// - rhs: Another reference to compare. @_inlineable // FIXME(sil-serialize-all) public func !== (lhs: AnyObject?, rhs: AnyObject?) -> Bool { return !(lhs === rhs) }
32dce7487c81a70f73f1ad09ffff104f
37.88
81
0.600917
false
false
false
false
appsquickly/Typhoon-Swift-Example
refs/heads/master
PocketForecast/Client/WeatherClientBasicImpl.swift
apache-2.0
1
//////////////////////////////////////////////////////////////////////////////// // // TYPHOON FRAMEWORK // Copyright 2013, Typhoon Framework Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// import Foundation public class WeatherClientBasicImpl: NSObject, WeatherClient { var weatherReportDao: WeatherReportDao? var serviceUrl: NSURL? var daysToRetrieve: NSNumber? var apiKey: String? { willSet(newValue) { assert(newValue != "$$YOUR_API_KEY_HERE$$", "Please get an API key (v2) from: http://free.worldweatheronline.com, and then " + "edit 'Configuration.plist'") } } public func loadWeatherReportFor(city: String!, onSuccess successBlock: @escaping ((WeatherReport) -> Void), onError errorBlock: @escaping ((String) -> Void)) { DispatchQueue.global(priority: .high).async() { let url = self.queryURL(city: city) let data : Data! = try! Data(contentsOf: url) let dictionary = (try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSDictionary if let error = dictionary.parseError() { DispatchQueue.main.async() { errorBlock(error.rootCause()) return } } else { let weatherReport: WeatherReport = dictionary.toWeatherReport() self.weatherReportDao!.saveReport(weatherReport: weatherReport) DispatchQueue.main.async() { successBlock(weatherReport) return } } } } private func queryURL(city: String) -> URL { let serviceUrl: NSURL = self.serviceUrl! return serviceUrl.uq_URL(byAppendingQueryDictionary: [ "q": city, "format": "json", "num_of_days": daysToRetrieve!.stringValue, "key": apiKey! ]) } }
7a3a995890f6bd63d060f796da8eece6
33.323077
164
0.550874
false
false
false
false
dvor/Antidote
refs/heads/master
Antidote/iPadFriendsButton.swift
mit
1
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import UIKit import SnapKit private struct Constants { static let BadgeHorizontalOffset = 5.0 static let BadgeMinimumWidth = 22.0 static let BadgeHeight: CGFloat = 18.0 static let BadgeRightOffset = -10.0 } class iPadFriendsButton: UIView { var didTapHandler: ((Void) -> Void)? var badgeText: String? { didSet { badgeLabel.text = badgeText badgeContainer.isHidden = (badgeText == nil) } } fileprivate var badgeContainer: UIView! fileprivate var badgeLabel: UILabel! fileprivate var button: UIButton! init(theme: Theme) { super.init(frame: CGRect.zero) createViews(theme) installConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension iPadFriendsButton { func buttonPressed() { didTapHandler?() } } private extension iPadFriendsButton { func createViews(_ theme: Theme) { badgeContainer = UIView() badgeContainer.backgroundColor = theme.colorForType(.TabBadgeBackground) badgeContainer.layer.masksToBounds = true badgeContainer.layer.cornerRadius = Constants.BadgeHeight / 2 addSubview(badgeContainer) badgeLabel = UILabel() badgeLabel.textColor = theme.colorForType(.TabBadgeText) badgeLabel.textAlignment = .center badgeLabel.backgroundColor = .clear badgeLabel.font = UIFont.antidoteFontWithSize(14.0, weight: .light) badgeContainer.addSubview(badgeLabel) button = UIButton(type: .system) button.contentHorizontalAlignment = .left button.contentEdgeInsets.left = 20.0 button.titleEdgeInsets.left = 20.0 button.titleLabel?.font = UIFont.systemFont(ofSize: 18.0) button.setTitle(String(localized: "contacts_title"), for: UIControlState()) button.setImage(UIImage(named: "tab-bar-friends"), for: UIControlState()) button.addTarget(self, action: #selector(iPadFriendsButton.buttonPressed), for: .touchUpInside) addSubview(button) } func installConstraints() { badgeContainer.snp.makeConstraints { $0.trailing.equalTo(self).offset(Constants.BadgeRightOffset) $0.centerY.equalTo(self) $0.width.greaterThanOrEqualTo(Constants.BadgeMinimumWidth) $0.height.equalTo(Constants.BadgeHeight) } badgeLabel.snp.makeConstraints { $0.leading.equalTo(badgeContainer).offset(Constants.BadgeHorizontalOffset) $0.trailing.equalTo(badgeContainer).offset(-Constants.BadgeHorizontalOffset) $0.centerY.equalTo(badgeContainer) } button.snp.makeConstraints { $0.edges.equalTo(self) } } }
2792ab474043d0ac198cbc4bb5279628
32.098901
103
0.668659
false
false
false
false
eonil/toolbox.swift
refs/heads/master
EonilToolbox/DisplayLinkUtility-iOS.swift
mit
1
// // DisplayLinkUtility-iOS.swift // EonilToolbox // // Created by Hoon H. on 2016/06/05. // Copyright © 2016 Eonil. All rights reserved. // #if os(iOS) import Foundation import UIKit import CoreGraphics import CoreVideo public enum DisplayLinkError: Error { case cannotCreateLink } public struct DisplayLinkUtility { fileprivate typealias Error = DisplayLinkError fileprivate static var link: CADisplayLink? fileprivate static let proxy = TargetProxy() fileprivate static var handlers = Dictionary<ObjectIdentifier, ()->()>() public static func installMainScreenHandler(_ id: ObjectIdentifier, f: @escaping ()->()) throws { assertMainThread() assert(handlers[id] == nil) if handlers.count == 0 { // `CADisplayLink` retains `target`. // So we need a proxy to break retain cycle. link = CADisplayLink(target: proxy, selector: #selector(TargetProxy.TOOLBOX_onTick(_:))) guard let link = link else { throw Error.cannotCreateLink } link.add(to: RunLoop.main, forMode: RunLoopMode.commonModes) link.add(to: RunLoop.main, forMode: RunLoopMode.UITrackingRunLoopMode) } handlers[id] = f } public static func deinstallMainScreenHandler(_ id: ObjectIdentifier) { assertMainThread() assert(handlers[id] != nil) handlers[id] = nil if handlers.count == 0 { assert(link != nil) var moved: CADisplayLink? swap(&moved, &link) guard let link = moved else { fatalError("Display-link is missing...") } link.remove(from: RunLoop.main, forMode: RunLoopMode.UITrackingRunLoopMode) link.remove(from: RunLoop.main, forMode: RunLoopMode.commonModes) } } fileprivate static func callback() { for (_, h) in handlers { h() } } } @objc private final class TargetProxy: NSObject { @objc func TOOLBOX_onTick(_: AnyObject?) { DisplayLinkUtility.callback() } } #endif
a347e467f7603d2de4a74bdc9b24c58a
31.464789
105
0.569631
false
false
false
false
dmorrow/UTSwiftUtils
refs/heads/master
Classes/Base/NSObject+UT.swift
mit
1
// // NSObject+UT.swift // // Created by Daniel Morrow on 10/25/16. // Copyright © 2016 unitytheory. All rights reserved. // import Foundation extension NSObject { public typealias cancellable_closure = (() -> ())? @discardableResult public func delay(_ delay:TimeInterval, closure:@escaping ()->()) -> cancellable_closure{ var cancelled = false let cancel_closure: cancellable_closure = { cancelled = true } DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + delay, execute: { if !cancelled { closure() } } ) return cancel_closure } public func cancel_delay(_ cancel_closure: cancellable_closure?) { if let closure = cancel_closure { closure?() } } }
27f9198c185b56d855e80485df8d6789
22.736842
93
0.532151
false
false
false
false
alvarozizou/Noticias-Leganes-iOS
refs/heads/develop
NoticiasLeganes/Position/PositionAPIService.swift
mit
1
// // PositionAPIService.swift // NoticiasLeganes // // Created by Alvaro Blazquez Montero on 17/9/17. // Copyright © 2017 Alvaro Blazquez Montero. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class PositionAPIService: DataManager { func getData(completionHandler: @escaping completion) { let headers: HTTPHeaders = [ "X-Auth-Token": K.Key ] Alamofire.request(K.PositionURL, method: .get, headers: headers).validate().responseJSON { response in switch response.result { case .success(let value): let json = JSON(value) let positions = self.getList(json: json) completionHandler(positions, nil) case .failure(let error): completionHandler(nil, error) } } } private func getList(json: JSON) -> [Position] { guard let standings = json[PositionKey.standing.rawValue] .arrayValue .first(where: { $0[PositionKey.type.rawValue].stringValue == PositionKey.total.rawValue } ) else { return [Position]() } return standings[PositionKey.table.rawValue].arrayValue.map { Position(json: $0) } } }
e04257129b6e691107852a64ba8b7dc2
31.97619
111
0.553791
false
false
false
false
dzenbot/XCSwiftr
refs/heads/master
XCSwiftr/Classes/ViewControllers/XCSConverterWindowController.swift
mit
1
// // XCSConverterWindowController.swift // XCSwiftr // // Created by Ignacio Romero on 4/3/16. // Copyright © 2016 DZN Labs. All rights reserved. // import Cocoa private let XCSwifterDomain = "com.dzn.XCSwiftr" extension Bool { init<T: Integer>(_ integer: T) { self.init(integer != 0) } } class XCSConverterWindowController: NSWindowController, NSTextViewDelegate { let commandController = XCSCommandController() let snippetManager = XCSSnippetManager(domain: XCSwifterDomain) var initialText: String? var inPlugin: Bool = false var autoConvert: Bool = false #if PLUGIN @IBOutlet var primaryTextView: DVTSourceTextView! @IBOutlet var secondaryTextView: DVTSourceTextView! #else @IBOutlet var primaryTextView: NSTextView! @IBOutlet var secondaryTextView: NSTextView! #endif @IBOutlet var autoCheckBox: NSButton! @IBOutlet var cancelButton: NSButton! @IBOutlet var acceptButton: NSButton! @IBOutlet var progressIndicator: NSProgressIndicator! var loading: Bool = false { didSet { if loading { self.progressIndicator.startAnimation(self) self.acceptButton.title = "" } else { self.progressIndicator.stopAnimation(self) self.acceptButton.title = "Convert" } } } // MARK: View lifecycle override func windowDidLoad() { super.windowDidLoad() primaryTextView.delegate = self primaryTextView.string = "" secondaryTextView.string = "" if let string = initialText { primaryTextView.string = string convertToSwift(objcString: string) updateAcceptButton() } if inPlugin == true { cancelButton.isHidden = false } } // MARK: Actions func convertToSwift(objcString: String?) { guard let objcString = objcString else { return } loading = true snippetManager.cacheTemporary(snippet: objcString) { (filePath) in if let path = filePath { self.commandController.objc2Swift(path) { (result) in self.loading = false self.secondaryTextView.string = result } } } } func updateAcceptButton() { acceptButton.isEnabled = ((primaryTextView.string?.characters.count)! > 0) } // MARK: IBActions @IBAction func convertAction(sender: AnyObject) { convertToSwift(objcString: primaryTextView.string) } @IBAction func dismissAction(sender: AnyObject) { guard let window = window, let sheetParent = window.sheetParent else { return } sheetParent.endSheet(window, returnCode: NSModalResponseCancel) } @IBAction func autoConvert(sender: AnyObject) { autoConvert = Bool(autoCheckBox.state) } // MARK: NSTextViewDelegate func textDidChange(_ notification: Notification) { updateAcceptButton() } }
127f00a04b843f79f91ec79b25975fc9
23.496
87
0.629001
false
false
false
false
AkshayNG/iSwift
refs/heads/master
iSwift/UI Components/UIView/UICounterControl.swift
mit
1
// // UICounterController.swift // iSwift // // Created by Akshay Gajarlawar on 09/05/17. // Copyright © 2017 yantrana. All rights reserved. // import UIKit class UICounterControl: UIView { var minValue:NSInteger = 0 var maxValue:NSInteger = 0 var controlColor:UIColor = UIColor.gray var controlTextColor:UIColor = UIColor.white var counterColor:UIColor = UIColor.lightGray var counterTextColor:UIColor = UIColor.black var minusImage:UIImage? var plusImage:UIImage? override init(frame: CGRect) { super.init(frame: frame) if(frame.size.height < frame.size.width/3) { fatalError("init(frame:) INVALID : Frame width (\(frame.size.width)) must be at least thrice the frame height(\(frame.size.height)) . e.g frame must have width >= (height * 3)") } self.clipsToBounds = true self.backgroundColor = UIColor.yellow self.layer.cornerRadius = 5.0 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { /*** Left Contol ***/ let minusBtn = UIButton.init(type: .custom) minusBtn.backgroundColor = controlColor minusBtn.frame = CGRect(x:1, y:1, width:rect.size.height - 2, height:rect.size.height - 2) if(minusImage != nil) { minusBtn .setImage(minusImage, for: .normal) } else { minusBtn.setTitle("-", for: .normal) minusBtn.setTitleColor(controlTextColor, for: .normal) minusBtn.titleLabel?.font = UIFont.systemFont(ofSize: minusBtn.frame.size.height/2) } /*** Right Contol ***/ let plusBtn = UIButton.init(type: .custom) plusBtn.backgroundColor = controlColor let plusX = rect.size.width - (minusBtn.frame.size.width + 1) plusBtn.frame = CGRect(x:plusX, y:minusBtn.frame.origin.y, width:minusBtn.frame.size.width, height:minusBtn.frame.size.height) if(plusImage != nil) { plusBtn .setImage(plusImage, for: .normal) } else { plusBtn.setTitle("+", for: .normal) plusBtn.setTitleColor(controlTextColor, for: .normal) plusBtn.titleLabel?.font = UIFont.systemFont(ofSize: plusBtn.frame.size.height/2) } /*** COUNTER ***/ let counterLbl = UILabel.init() let counterX = minusBtn.frame.size.width + 2 let counterWidth = rect.size.width - ( minusBtn.frame.size.width*2 + 4) counterLbl.frame = CGRect(x:counterX, y:minusBtn.frame.origin.y, width:counterWidth, height:minusBtn.frame.size.height) counterLbl.backgroundColor = counterColor counterLbl.textColor = counterTextColor /*** Add ***/ self.addSubview(minusBtn) self.addSubview(plusBtn) self.addSubview(counterLbl) } }
a41515827b6daa77517489efcc3da977
32.19
189
0.554083
false
false
false
false
shohei/firefox-ios
refs/heads/master
Client/Frontend/UIConstants.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation public struct UIConstants { static let AboutHomeURL = NSURL(string: "\(WebServer.sharedInstance.base)/about/home/#panel=0")! static let AppBackgroundColor = UIColor.blackColor() static let ToolbarHeight: CGFloat = 44 static let DefaultRowHeight: CGFloat = 58 static let DefaultPadding: CGFloat = 10 static let DefaultMediumFontSize: CGFloat = 14 static let DefaultMediumFont = UIFont.systemFontOfSize(DefaultMediumFontSize, weight: UIFontWeightRegular) static let DefaultMediumBoldFont = UIFont.boldSystemFontOfSize(DefaultMediumFontSize) static let DefaultSmallFontSize: CGFloat = 11 static let DefaultSmallFont = UIFont.systemFontOfSize(DefaultSmallFontSize, weight: UIFontWeightRegular) static let DefaultSmallFontBold = UIFont.systemFontOfSize(DefaultSmallFontSize, weight: UIFontWeightBold) static let DefaultStandardFontSize: CGFloat = 17 static let DefaultStandardFontBold = UIFont.boldSystemFontOfSize(DefaultStandardFontSize) // These highlight colors are currently only used on Snackbar buttons when they're pressed static let HighlightColor = UIColor(red: 205/255, green: 223/255, blue: 243/255, alpha: 0.9) static let HighlightText = UIColor(red: 42/255, green: 121/255, blue: 213/255, alpha: 1.0) static let PanelBackgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.6) static let SeparatorColor = UIColor(rgb: 0xcccccc) static let HighlightBlue = UIColor(red:0.3, green:0.62, blue:1, alpha:1) static let BorderColor = UIColor.blackColor().colorWithAlphaComponent(0.25) static let BackgroundColor = UIColor(red: 0.21, green: 0.23, blue: 0.25, alpha: 1) // settings static let TableViewHeaderBackgroundColor = UIColor(red: 242/255, green: 245/255, blue: 245/255, alpha: 1.0) static let TableViewHeaderTextColor = UIColor(red: 130/255, green: 135/255, blue: 153/255, alpha: 1.0) static let TableViewRowTextColor = UIColor(red: 53.55/255, green: 53.55/255, blue: 53.55/255, alpha: 1.0) // Firefox Orange static let ControlTintColor = UIColor(red: 240.0 / 255, green: 105.0 / 255, blue: 31.0 / 255, alpha: 1) }
8114a7b107bf19462b924feff5aa5ea0
55.452381
112
0.748523
false
false
false
false
stripe/stripe-ios
refs/heads/master
StripePaymentSheet/StripePaymentSheet/Helpers/STPStringUtils.swift
mit
1
// // STPStringUtils.swift // StripePaymentSheet // // Created by Brian Dorfman on 9/7/16. // Copyright © 2016 Stripe, Inc. All rights reserved. // import Foundation @_spi(STP) import StripePaymentsUI typealias STPTaggedSubstringCompletionBlock = (String?, NSRange) -> Void typealias STPTaggedSubstringsCompletionBlock = (String, [String: NSValue]) -> Void extension STPStringUtils { /// Takes a string with the named html-style tags, removes the tags, /// and then calls the completion block with the modified string and the range /// in it that the tag would have enclosed. /// E.g. Passing in @"Test <b>string</b>" with tag @"b" would call completion /// with @"Test string" and NSMakeRange(5,6). /// Completion is always called, location of range is NSNotFound with the unmodified /// string if a match could not be found. /// - Parameters: /// - string: The string with tagged substrings. /// - tag: The tag to search for. /// - completion: The string with the named tag removed and the range of the /// substring it covered. @objc(parseRangeFromString:withTag:completion:) class func parseRange( from string: String, withTag tag: String, completion: STPTaggedSubstringCompletionBlock ) { let startingTag = "<\(tag)>" let startingTagRange = (string as NSString?)?.range(of: startingTag) if startingTagRange?.location == NSNotFound { completion(string, startingTagRange!) return } var finalString: String? if let startingTagRange = startingTagRange { finalString = (string as NSString?)?.replacingCharacters(in: startingTagRange, with: "") } let endingTag = "</\(tag)>" let endingTagRange = (finalString as NSString?)?.range(of: endingTag) if endingTagRange?.location == NSNotFound { completion(string, endingTagRange!) return } if let endingTagRange = endingTagRange { finalString = (finalString as NSString?)?.replacingCharacters( in: endingTagRange, with: "") } let finalTagRange = NSRange( location: startingTagRange?.location ?? 0, length: (endingTagRange?.location ?? 0) - (startingTagRange?.location ?? 0)) completion(finalString, finalTagRange) } /// Like `parseRangeFromString:withTag:completion:` but you can pass in a set /// of unique tags to get the ranges for and it will return you the mapping. /// E.g. Passing @"<a>Test</a> <b>string</b>" with the tag set [a, b] /// will get you a completion block dictionary that looks like /// @{ @"a" : NSMakeRange(0,4), /// @"b" : NSMakeRange(5,6) } /// - Parameters: /// - string: The string with tagged substrings. /// - tags: The tags to search for. /// - completion: The string with the named tags removed and the ranges of the /// substrings they covered (wrapped in NSValue) /// @warning Doesn't currently support overlapping tag ranges because that's /// complicated and we don't need it at the moment. @objc(parseRangesFromString:withTags:completion:) class func parseRanges( from string: String, withTags tags: Set<String>, completion: STPTaggedSubstringsCompletionBlock ) { var interiorRangesToTags: [NSValue: String] = [:] var tagsToRange: [String: NSValue] = [:] for tag in tags { self.parseRange( from: string, withTag: tag ) { _, tagRange in if tagRange.location == NSNotFound { tagsToRange[tag] = NSValue(range: tagRange) } else { let interiorRange = NSRange( location: tagRange.location + tag.count + 2, length: tagRange.length) interiorRangesToTags[NSValue(range: interiorRange)] = tag } } } let sortedRanges = interiorRangesToTags.keys.sorted { (obj1, obj2) -> Bool in let range1 = obj1.rangeValue let range2 = obj2.rangeValue return range1.location < range2.location } var modifiedString = string var deletedCharacters = 0 for rangeValue in sortedRanges { let tag = interiorRangesToTags[rangeValue] var interiorTagRange = rangeValue.rangeValue if interiorTagRange.location != NSNotFound { interiorTagRange.location -= deletedCharacters let beginningTagLength = (tag?.count ?? 0) + 2 let beginningTagRange = NSRange( location: interiorTagRange.location - beginningTagLength, length: beginningTagLength) if let subRange = Range<String.Index>(beginningTagRange, in: modifiedString) { modifiedString.removeSubrange(subRange) } interiorTagRange.location -= beginningTagLength deletedCharacters += beginningTagLength let endingTagLength = beginningTagLength + 1 let endingTagRange = NSRange( location: interiorTagRange.location + interiorTagRange.length, length: endingTagLength) if let subRange = Range<String.Index>(endingTagRange, in: modifiedString) { modifiedString.removeSubrange(subRange) } deletedCharacters += endingTagLength tagsToRange[tag!] = NSValue(range: interiorTagRange) } } completion(modifiedString, tagsToRange) } }
716e8b5e700791050bae5d5443599151
40.640288
100
0.605045
false
false
false
false
silence0201/Swift-Study
refs/heads/master
AdvancedSwift/可选值/A Tour of Optional Techniques - switch-case Matching for Optionals:.playgroundpage/Contents.swift
mit
1
/*: ### `switch`-`case` Matching for Optionals: Another consequence of optionals not being `Equatable` is that you can't check them in a `case` statement. `case` matching is controlled in Swift by the `~=` operator, and the relevant definition looks a lot like the one that wasn't working for arrays: ``` swift-example func ~=<T: Equatable>(a: T, b: T) -> Bool ``` But it's simple to produce a matching version for optionals that just calls `==`: */ //#-editable-code func ~=<T: Equatable>(pattern: T?, value: T?) -> Bool { return pattern == value } //#-end-editable-code /*: It's also nice to implement a range match at the same time: */ //#-editable-code func ~=<Bound>(pattern: Range<Bound>, value: Bound?) -> Bool { return value.map { pattern.contains($0) } ?? false } //#-end-editable-code /*: Here, we use `map` to check if a non-`nil` value is inside the interval. Because we want `nil` not to match any interval, we return `false` in case of `nil`. Given this, we can now match optional values with `switch`: */ //#-editable-code for i in ["2", "foo", "42", "100"] { switch Int(i) { case 42: print("The meaning of life") case 0..<10: print("A single digit") case nil: print("Not a number") default: print("A mystery number") } } //#-end-editable-code
5270dfa161f5918fcedb7eb37b32d809
22.839286
80
0.641948
false
false
false
false
Joachimdj/JobResume
refs/heads/master
Apps/Kort sagt/KortSagt-master/Pods/Kingfisher/Kingfisher/UIButton+Kingfisher.swift
apache-2.0
12
// // UIButton+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/13. // // Copyright (c) 2015 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit /** * Set image to use from web for a specified state. */ public extension UIButton { /** Set an image to use for a specified state with a resource. It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state. The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource, forState state: UIControlState) -> RetrieveImageTask { return kf_setImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image to use for a specified state with a URL. It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state. The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use. If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState) -> RetrieveImageTask { return kf_setImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image to use for a specified state with a resource and a placeholder image. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?) -> RetrieveImageTask { return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image to use for a specified state with a URL and a placeholder image. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?) -> RetrieveImageTask { return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image to use for a specified state with a resource, a placeholder image and options. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set an image to use for a specified state with a URL, a placeholder image and options. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set an image to use for a specified state with a resource, a placeholder image, options and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set an image to use for a specified state with a URL, a placeholder image, options and completion handler. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { setImage(placeholderImage, forState: state) kf_setWebURL(resource.downloadURL, forState: state) let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo, progressBlock: { receivedSize, totalSize in if let progressBlock = progressBlock { dispatch_async(dispatch_get_main_queue(), { () -> Void in progressBlock(receivedSize: receivedSize, totalSize: totalSize) }) } }, completionHandler: {[weak self] image, error, cacheType, imageURL in dispatch_async_safely_main_queue { if let sSelf = self { if imageURL == sSelf.kf_webURLForState(state) && image != nil { sSelf.setImage(image, forState: state) } completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL) } } } ) return task } /** Set an image to use for a specified state with a URL, a placeholder image, options, progress handler and completion handler. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithResource(Resource(downloadURL: URL), forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler) } } private var lastURLKey: Void? public extension UIButton { /** Get the image URL binded to this button for a specified state. - parameter state: The state that uses the specified image. - returns: Current URL for image. */ public func kf_webURLForState(state: UIControlState) -> NSURL? { return kf_webURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL } private func kf_setWebURL(URL: NSURL, forState state: UIControlState) { kf_webURLs[NSNumber(unsignedLong:state.rawValue)] = URL } private var kf_webURLs: NSMutableDictionary { var dictionary = objc_getAssociatedObject(self, &lastURLKey) as? NSMutableDictionary if dictionary == nil { dictionary = NSMutableDictionary() kf_setWebURLs(dictionary!) } return dictionary! } private func kf_setWebURLs(URLs: NSMutableDictionary) { objc_setAssociatedObject(self, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /** * Set background image to use from web for a specified state. */ public extension UIButton { /** Set the background image to use for a specified state with a resource. It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state. The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithResource(resource: Resource, forState state: UIControlState) -> RetrieveImageTask { return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set the background image to use for a specified state with a URL. It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state. The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use. If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState) -> RetrieveImageTask { return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set the background image to use for a specified state with a resource and a placeholder image. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?) -> RetrieveImageTask { return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set the background image to use for a specified state with a URL and a placeholder image. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?) -> RetrieveImageTask { return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set the background image to use for a specified state with a resource, a placeholder image and options. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set the background image to use for a specified state with a URL, a placeholder image and options. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set the background image to use for a specified state with a resource, a placeholder image, options and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set the background image to use for a specified state with a URL, a placeholder image, options and completion handler. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set the background image to use for a specified state with a resource, a placeholder image, options progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithResource(resource: Resource, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { setBackgroundImage(placeholderImage, forState: state) kf_setBackgroundWebURL(resource.downloadURL, forState: state) let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo, progressBlock: { receivedSize, totalSize in if let progressBlock = progressBlock { dispatch_async(dispatch_get_main_queue(), { () -> Void in progressBlock(receivedSize: receivedSize, totalSize: totalSize) }) } }, completionHandler: { [weak self] image, error, cacheType, imageURL in dispatch_async_safely_main_queue { if let sSelf = self { if imageURL == sSelf.kf_backgroundWebURLForState(state) && image != nil { sSelf.setBackgroundImage(image, forState: state) } completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL) } } } ) return task } /** Set the background image to use for a specified state with a URL, a placeholder image, options progress handler and completion handler. - parameter URL: The URL of image for specified state. - parameter state: The state that uses the specified image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. */ public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setBackgroundImageWithResource(Resource(downloadURL: URL), forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler) } } private var lastBackgroundURLKey: Void? public extension UIButton { /** Get the background image URL binded to this button for a specified state. - parameter state: The state that uses the specified background image. - returns: Current URL for background image. */ public func kf_backgroundWebURLForState(state: UIControlState) -> NSURL? { return kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL } private func kf_setBackgroundWebURL(URL: NSURL, forState state: UIControlState) { kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] = URL } private var kf_backgroundWebURLs: NSMutableDictionary { var dictionary = objc_getAssociatedObject(self, &lastBackgroundURLKey) as? NSMutableDictionary if dictionary == nil { dictionary = NSMutableDictionary() kf_setBackgroundWebURLs(dictionary!) } return dictionary! } private func kf_setBackgroundWebURLs(URLs: NSMutableDictionary) { objc_setAssociatedObject(self, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Deprecated public extension UIButton { @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo: instead.") public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, options: KingfisherOptions) -> RetrieveImageTask { return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: nil) } @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo:completionHandler: instead.") public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, options: KingfisherOptions, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: completionHandler) } @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.") public func kf_setImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, options: KingfisherOptions, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: progressBlock, completionHandler: completionHandler) } @available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo: instead.") public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, options: KingfisherOptions) -> RetrieveImageTask { return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: nil) } @available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo:completionHandler: instead.") public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, options: KingfisherOptions, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: completionHandler) } @available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.") public func kf_setBackgroundImageWithURL(URL: NSURL, forState state: UIControlState, placeholderImage: UIImage?, options: KingfisherOptions, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: progressBlock, completionHandler: completionHandler) } }
6419359a4b979ae46272c71bf47d6ca4
52.564189
242
0.649511
false
false
false
false
qrpc/orbits
refs/heads/master
orbits/GameScene.swift
gpl-3.0
1
// // GameScene.swift // orbits // // Created by Robert Altenburg on 5/13/15. // Copyright (c) 2015 Robert Altenburg. All rights reserved. // import SpriteKit enum BodyType:UInt32 { case star = 1 case ship = 2 case weapon = 4 } class GameScene: SKScene, SKPhysicsContactDelegate { let star = SKSpriteNode(imageNamed:"Sun") let ship = [Ship(imageNamed: "Spaceship", name: "Player One", controlLeft: 123, controlRight: 124, controlThrust: 126, controlFire: 125), Ship(imageNamed: "Ship2", name: "Player Two", controlLeft: 0, controlRight: 2, controlThrust: 13, controlFire: 1)] var missle = [Missle]() override func didMove(to view: SKView) { //set up physics physicsWorld.contactDelegate = self let gravField = SKFieldNode.radialGravityField(); // Create grav field gravField.position = CGPoint(x: size.width/2.0, y: size.height/2) addChild(gravField); // Add to world // setting graphics self.backgroundColor = NSColor.black // set up star field with stars of different sizes for _ in 1...100 { let c = SKShapeNode(circleOfRadius: (CGFloat(arc4random_uniform(10)) / 70.0)) c.strokeColor = SKColor.white c.position = CGPoint(x: CGFloat(arc4random_uniform(UInt32(self.size.width))), y: CGFloat(arc4random_uniform(UInt32(self.size.height)))) self.addChild(c) } // set up star in center star.position = gravField.position star.setScale(0.08) star.name = "Star" star.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "Sun"), size: star.size) if let physics = star.physicsBody { physics.isDynamic = false physics.categoryBitMask = BodyType.star.rawValue } self.addChild(star) // place the ships ship[0].position = CGPoint(x: size.width * 0.25, y:size.height * 0.5) ship[0].physicsBody?.velocity = CGVector(dx: 0, dy: 100) self.addChild(ship[0]) ship[1].position = CGPoint(x: size.width * 0.75, y:size.height * 0.5) ship[1].physicsBody?.velocity = CGVector(dx: 0, dy: -100) self.addChild(ship[1]) } func endGame() { self.run(SKAction.wait(forDuration: 4), completion: { let scene = EndScene(size: self.size) self.view?.presentScene(scene, transition: SKTransition.crossFade(withDuration: 2)) }) } func didBegin(_ contact: SKPhysicsContact) { let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask var actionBody:SKPhysicsBody var otherBody:SKPhysicsBody switch(contactMask) { // contactMask 3 = ship hit the star case BodyType.ship.rawValue | BodyType.star.rawValue: // make sure action takes place on the ship if contact.bodyA.node!.name == "Star" { actionBody = contact.bodyB } else { actionBody = contact.bodyA } explosion(actionBody.node!.position) actionBody.node!.removeFromParent() endGame() // contactMask = 5: weapon hit star case BodyType.weapon.rawValue | BodyType.star.rawValue: // make sure action takes place on the ship if contact.bodyA.node!.name == "Star" { actionBody = contact.bodyB } else { actionBody = contact.bodyA } actionBody.node!.removeFromParent() // contactMask = 5: weapon hit ship case BodyType.weapon.rawValue | BodyType.ship.rawValue: // make sure action takes place on the ship if contact.bodyA.node!.name == "Missle" { actionBody = contact.bodyB otherBody = contact.bodyA } else { actionBody = contact.bodyA otherBody = contact.bodyB } explosion(actionBody.node!.position) actionBody.node!.removeFromParent() otherBody.node!.removeFromParent() endGame() default: print("Uncaught contact made: \(contactMask)") return } } func explosion(_ pos: CGPoint) { let emitterNode = SKEmitterNode(fileNamed: "explosion.sks") emitterNode!.particlePosition = pos self.addChild(emitterNode!) // Don't forget to remove the emitter node after the explosion self.run(SKAction.wait(forDuration: 2), completion: { emitterNode!.removeFromParent() }) } override func keyDown(with theEvent: NSEvent) { //println(theEvent.keyCode) // respond to ship events for s in ship { if theEvent.keyCode == s.controlThrust { s.thrust() } else if theEvent.keyCode == s.controlLeft { s.left() } else if theEvent.keyCode == s.controlRight { s.right() } else if theEvent.keyCode == s.controlFire { s.fire(self, missle: &missle) } /*else { println("Key: \(theEvent.keyCode)") }*/ } print("Key: \(theEvent.keyCode)") } func screenWrap(_ node:SKSpriteNode)->Void { // wrap if object exits screen if node.position.x < 0 { node.position.x = size.width } else if node.position.x > size.width { node.position.x = 0 } if node.position.y < 0 { node.position.y = size.height } else if node.position.y > size.height { node.position.y = 0 } } override func update(_ currentTime: TimeInterval) { /* Called before each frame is rendered */ for s in ship { screenWrap(s) } for m in missle { //Turn the missles into the direction of travel m.zRotation = CGFloat(M_2_PI - M_PI/4) - atan2(m.physicsBody!.velocity.dx , m.physicsBody!.velocity.dy) //Don't wrap missles unless they have a lifespan screenWrap(m) //TODO: remove missle from the array when they leave screen } } }
b0856605cd98a28b5b1204dfe3d06c1e
30.764423
141
0.548963
false
false
false
false
manavgabhawala/CocoaMultipeer
refs/heads/master
MultipeerCocoaiOS/MGBrowserTableViewController.swift
apache-2.0
1
// // MGBrowserViewController.swift // CocoaMultipeer // // Created by Manav Gabhawala on 05/07/15. // // import UIKit protocol MGBrowserTableViewControllerDelegate : NSObjectProtocol { var minimumPeers: Int { get } var maximumPeers: Int { get } } @objc internal class MGBrowserTableViewController: UITableViewController { /// The browser passed to the initializer for which this class is presenting a UI for. (read-only) internal let browser: MGNearbyServiceBrowser /// The session passed to the initializer for which this class is presenting a UI for. (read-only) internal let session: MGSession internal weak var delegate: MGBrowserTableViewControllerDelegate! private var availablePeers = [MGPeerID]() /// Initializes a browser view controller with the provided browser and session. /// - Parameter browser: An object that the browser view controller uses for browsing. This is usually an instance of MGNearbyServiceBrowser. However, if your app is using a custom discovery scheme, you can instead pass any custom subclass that calls the methods defined in the MCNearbyServiceBrowserDelegate protocol on its delegate when peers are found and lost. /// - Parameter session: The multipeer session into which the invited peers are connected. /// - Returns: An initialized browser. /// - Warning: If you want the browser view controller to manage the browsing process, the browser object must not be actively browsing, and its delegate must be nil. internal init(browser: MGNearbyServiceBrowser, session: MGSession, delegate: MGBrowserTableViewControllerDelegate) { self.browser = browser self.session = session self.delegate = delegate super.init(style: .Grouped) self.browser.delegate = self } required internal init?(coder aDecoder: NSCoder) { let peer = MGPeerID() self.browser = MGNearbyServiceBrowser(peer: peer, serviceType: "custom-server") self.session = MGSession(peer: peer) super.init(coder: aDecoder) self.browser.delegate = self } internal override func viewDidLoad() { navigationItem.title = "" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "donePressed:") navigationItem.rightBarButtonItem?.enabled = false navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "cancelPressed:") } internal override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) browser.startBrowsingForPeers() NSNotificationCenter.defaultCenter().addObserver(self, selector: "sessionUpdated:", name: MGSession.sessionPeerStateUpdatedNotification, object: session) tableView.reloadData() } internal override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self, name: MGSession.sessionPeerStateUpdatedNotification, object: session) browser.stopBrowsingForPeers() } internal func sessionUpdated(notification: NSNotification) { guard notification.name == MGSession.sessionPeerStateUpdatedNotification else { return } dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadSections(NSIndexSet(indexesInRange: NSRange(location: 0, length: 2)), withRowAnimation: .Automatic) }) if self.session.connectedPeers.count >= self.delegate.minimumPeers { self.navigationItem.rightBarButtonItem?.enabled = true } else { self.navigationItem.rightBarButtonItem?.enabled = false } } // MARK: - Actions internal func donePressed(sender: UIBarButtonItem) { guard session.connectedPeers.count >= delegate.minimumPeers && session.connectedPeers.count <= delegate.maximumPeers else { sender.enabled = false return } dismissViewControllerAnimated(true, completion: nil) } internal func cancelPressed(sender: UIBarButtonItem) { session.disconnect() dismissViewControllerAnimated(true, completion: nil) } } // MARK: - TableViewStuff extension MGBrowserTableViewController { internal override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } internal override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? session.peers.count : availablePeers.count } internal override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell : UITableViewCell if indexPath.section == 0 { cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "connected") cell.textLabel!.text = session.peers[indexPath.row].peer.displayName cell.detailTextLabel!.text = session.peers[indexPath.row].state.description cell.selectionStyle = .None } else { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "available") if availablePeers.count > indexPath.row { cell.textLabel!.text = availablePeers[indexPath.row].displayName } cell.selectionStyle = .Default } return cell } internal override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.cellForRowAtIndexPath(indexPath)!.setHighlighted(false, animated: true) guard indexPath.section == 1 && delegate.maximumPeers > session.peers.count else { return } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { do { try self.browser.invitePeer(self.availablePeers[indexPath.row], toSession: self.session) } catch { MGLog("Couldn't find peer. Refreshing.") MGDebugLog("Attemtpting to connect to an unknown service. Removing the listing and refreshing the view to recover. \(error)") self.availablePeers.removeAtIndex(indexPath.row) // Couldn't find the peer so let's reload the table. dispatch_async(dispatch_get_main_queue(), self.tableView.reloadData) } }) } internal override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 0 ? "Connected Peers" : "Available Peers" } internal override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { return section == 0 ? nil : "This device will appear as \(browser.myPeerID.displayName). You must connect to at least \(delegate.minimumPeers.peerText) and no more than \(delegate.maximumPeers.peerText)." } } // MARK: - Browser stuff extension MGBrowserTableViewController : MGNearbyServiceBrowserDelegate { internal func browserDidStartSuccessfully(browser: MGNearbyServiceBrowser) { tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Automatic) } internal func browser(browser: MGNearbyServiceBrowser, didNotStartBrowsingForPeers error: [String : NSNumber]) { // TODO: Handle the error. } internal func browser(browser: MGNearbyServiceBrowser, foundPeer peerID: MGPeerID, withDiscoveryInfo info: [String : String]?) { assert(browser === self.browser) guard peerID != session.myPeerID && peerID != browser.myPeerID else { return } // This should never happen but its better to check availablePeers.append(peerID) dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Automatic) }) } internal func browser(browser: MGNearbyServiceBrowser, lostPeer peerID: MGPeerID) { assert(browser === self.browser) guard peerID != session.myPeerID && peerID != browser.myPeerID else { // FIXME: Fail silently fatalError("We lost the browser to our own peer. Something went wrong in the browser.") } availablePeers.removeElement(peerID) dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Automatic) }) } internal func browser(browser: MGNearbyServiceBrowser, didReceiveInvitationFromPeer peerID: MGPeerID, invitationHandler: (Bool, MGSession) -> Void) { guard session.connectedPeers.count == 0 else { // We are already connected to some peers so we can't accept any other connections. invitationHandler(false, session) return } let alertController = UIAlertController(title: "\(peerID.displayName) wants to connect?", message: nil, preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "Decline", style: .Destructive, handler: { action in invitationHandler(false, self.session) })) alertController.addAction(UIAlertAction(title: "Accept", style: UIAlertActionStyle.Default, handler: {action in invitationHandler(true, self.session) // Remove self since we accepted the connection. self.dismissViewControllerAnimated(true, completion: nil) })) presentViewController(alertController, animated: true, completion: nil) } internal func browserStoppedSearching(browser: MGNearbyServiceBrowser) { // availablePeers.removeAll() } }
280e23f869ab787974ff06e839f67add
37.465217
365
0.765544
false
false
false
false
rwyland/MMDB
refs/heads/master
MMDB Swift/MovieDBService.swift
apache-2.0
1
// // MovieDBService.swift // MMDB Swift // // Created by Rob W on 12/11/15. // Copyright © 2015 Org Inc. All rights reserved. // import UIKit protocol MovieLookupDelegate { /** A Delegate to receive responses for async network calls. */ func receivedMovies(movies: Array<Movie>, forPage page: Int) /** A movie returned for a specific lookup on id. This will cache movies for quicker responsiveness. */ func receivedMovieDetails(movie: Movie) /** Some sort of failure from the network call. */ func requestFailedWithError(error: NSError) } class MovieDBService { /** A queue to support network calls on a background thread */ let queue: NSOperationQueue = NSOperationQueue() /** * A simple cache by movie id. * All of the contents of a movie are historical, however the user rating and voting can change, so ideally we would support updating the cache. * We could accomplish this by immediately returning the cache value, and then applying an update to the View if the cache was found to be stale. */ var movieCache: Dictionary<Int, Movie> = [:] /** * This is loaded from a local plist called "apiKey.plist" with a single string entry: * { @"kAPI_KEY" : @"Your API key" } */ var apiKey: String? var delegate: protocol<MovieLookupDelegate>? // MARK: - Init init() { // Find out the path of the local api key properties list let path = NSBundle.mainBundle().pathForResource("apiKey", ofType: "plist") if let dict = NSDictionary(contentsOfFile: path!) { self.apiKey = dict["kAPI_KEY"] as? String } } func requestPopularMoviesWithPage(page: Int) { assert(self.apiKey != nil, "An API_KEY is required to use the movie DB. Please register a key as described") if page > 1000 { // The API doesn't support anything over 1000 self.delegate?.requestFailedWithError(NSError(domain: "Invalid page number", code: 400, userInfo: nil)) return } let urlString = "http://api.themoviedb.org/3/movie/popular?api_key=\(self.apiKey!)&page=\(page)" let url = NSURL(string: urlString)! let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in if let error = error where data == nil { self.delegate?.requestFailedWithError(error) return } // Parse the raw JSON into Objects do { let parsed = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! Dictionary<String, AnyObject> let page = parsed["page"]! as! Int // These can be useful for displaying in the View //let totalPages = parsed["total_pages"] as! Int //let totalResults = parsed["total_results"] as! Int var movies: Array<Movie> = [] let results = parsed["results"] as! Array<AnyObject> for value in results { let movie = self.parseMovieFromDictionary(value as! Dictionary<String, AnyObject>) movies.append(movie) } self.delegate?.receivedMovies(movies, forPage: page) } catch { self.delegate?.requestFailedWithError(NSError(domain: "JSON Parse Error", code: 400, userInfo: nil)) return } }) task.resume() } func searchMoviesWithQuery(query: String, andPage page: Int) { assert(self.apiKey != nil, "An API_KEY is required to use the movie DB. Please register a key as described") if page > 1000 { // The API doesn't support anything over 1000 self.delegate?.requestFailedWithError(NSError(domain: "Invalid page number", code: 400, userInfo: nil)) return } let encoded = self.urlEncodeQuery(query) let urlString = "http://api.themoviedb.org/3/search/movie?api_key=\(self.apiKey!)&query=\(encoded)&page=\(page)" let url = NSURL(string: urlString)! let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in if let error = error where data == nil { self.delegate?.requestFailedWithError(error) return } // Parse the raw JSON into Objects do { let parsed = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! Dictionary<String, AnyObject> let page = parsed["page"]! as! Int // These can be useful for displaying in the View //let totalPages = parsed["total_pages"] as! Int //let totalResults = parsed["total_results"] as! Int var movies: Array<Movie> = [] let results = parsed["results"] as! Array<AnyObject> for value in results { let movie = self.parseMovieFromDictionary(value as! Dictionary<String, AnyObject>) movies.append(movie) } self.delegate?.receivedMovies(movies, forPage: page) } catch { self.delegate?.requestFailedWithError(NSError(domain: "JSON Parse Error", code: 400, userInfo: nil)) return } }) task.resume() } func lookupMovieWithId(movieId: Int ) { assert(self.apiKey != nil, "An API_KEY is required to use the movie DB. Please register a key as described") if let movie = self.movieCache[movieId] { // lookup in the cache and return self.delegate?.receivedMovieDetails( movie ) return } let urlString = "http://api.themoviedb.org/3/movie/\(movieId)?api_key=\(self.apiKey!)" let url = NSURL(string: urlString)! let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in if let error = error where data == nil { self.delegate?.requestFailedWithError(error) return } // Parse the raw JSON into Objects do { let parsed = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! Dictionary<String, AnyObject> let movie = self.parseMovieFromDictionary(parsed) // Add the movie to the cache to avoid excessive network requests self.movieCache[movie.id] = movie self.delegate?.receivedMovieDetails(movie) } catch { self.delegate?.requestFailedWithError(NSError(domain: "JSON Parse Error", code: 400, userInfo: nil)) return } }) task.resume() } // MARK: - Private Helpers /** Using Key Value Coding (KVC), iterate the JSON response object and construct a Movie using the applicable values */ private func parseMovieFromDictionary(dict: Dictionary<String, AnyObject>) -> Movie { let movie = Movie() for (key, value) in dict { if value !== NSNull() && movie.respondsToSelector(Selector(key)) { movie.setValue(value, forKey: key) } } return movie } /** Need to make sure we are properly encoding the query for the API */ func urlEncodeQuery(query: String) -> String { return query.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet() )! } }
90c9658f6eb03505b7d18a17eda23974
37.668508
148
0.661189
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/TableOfContentsCell.swift
mit
1
import UIKit // MARK: - Cell class TableOfContentsCell: UITableViewCell { @IBOutlet var titleLabel: UILabel! @IBOutlet var selectedSectionIndicator: UIView! @IBOutlet var indentationConstraint: NSLayoutConstraint! @IBOutlet weak var titleLabelTopConstraint: NSLayoutConstraint! var titleIndentationLevel: Int = 0 { didSet { titleLabelTopConstraint.constant = titleIndentationLevel == 0 ? 19 : 11 indentationConstraint.constant = indentationWidth * CGFloat(1 + titleIndentationLevel) if titleIndentationLevel == 0 { accessibilityTraits = .header } else { accessibilityValue = String.localizedStringWithFormat(WMFLocalizedString("table-of-contents-subheading-label", value:"Subheading %1$d", comment:"VoiceOver label to indicate level of subheading in table of contents. %1$d is replaced by the level of subheading."), titleIndentationLevel) } } } private var titleHTML: String = "" private var titleTextStyle: DynamicTextStyle = .georgiaTitle3 private var isTitleLabelHighlighted: Bool = false func setTitleHTML(_ html: String, with textStyle: DynamicTextStyle, highlighted: Bool, color: UIColor, selectionColor: UIColor) { isTitleLabelHighlighted = highlighted titleHTML = html titleTextStyle = textStyle titleColor = color titleSelectionColor = selectionColor updateTitle() } func updateTitle() { let color = isTitleLabelHighlighted ? titleSelectionColor : titleColor titleLabel.attributedText = titleHTML.byAttributingHTML(with: titleTextStyle, matching: traitCollection, color: color, handlingLinks: false) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateTitle() } private var titleColor: UIColor = Theme.standard.colors.primaryText { didSet { titleLabel.textColor = titleColor } } private var titleSelectionColor: UIColor = Theme.standard.colors.link // MARK: - Init public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) indentationWidth = 10 } // MARK: - UIView override func awakeFromNib() { super.awakeFromNib() selectedSectionIndicator.alpha = 0.0 selectionStyle = .none } // MARK: - Accessors func setSectionSelected(_ selected: Bool, animated: Bool) { if selected { setSelectionIndicatorVisible(titleIndentationLevel == 0) } else { setSelectionIndicatorVisible(false) } } // MARK: - UITableVIewCell class func reuseIdentifier() -> String { return wmf_nibName() } override func prepareForReuse() { super.prepareForReuse() indentationLevel = 1 setSectionSelected(false, animated: false) isTitleLabelHighlighted = false accessibilityTraits = [] accessibilityValue = nil } func setSelectionIndicatorVisible(_ visible: Bool) { if visible { selectedSectionIndicator.backgroundColor = titleSelectionColor selectedSectionIndicator.alpha = 1.0 } else { selectedSectionIndicator.alpha = 0.0 } } }
b58a49b460521ab8205be9cfa81d74f7
32.326923
301
0.655511
false
false
false
false
Constantine-Fry/das-quadrat
refs/heads/develop
Source/Shared/Keychain.swift
bsd-2-clause
1
// // FSKeychain.swift // Quadrat // // Created by Constantine Fry on 26/10/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation import Security /** The error domain for errors returned by `Keychain Service`. The `code` property will contain OSStatus. See SecBase.h for error codes. The `userInfo` is always nil and there is no localized description provided. */ public let QuadratKeychainOSSatusErrorDomain = "QuadratKeychainOSSatusErrorDomain" class Keychain { var logger: Logger? fileprivate let keychainQuery: [String:AnyObject] init(configuration: Configuration) { #if os(iOS) let serviceAttribute = "Foursquare2API-FSKeychain" #else let serviceAttribute = "Foursquare Access Token" #endif var accountAttribute: String if let userTag = configuration.userTag { accountAttribute = configuration.client.identifier + "_" + userTag } else { accountAttribute = configuration.client.identifier } keychainQuery = [ kSecClass as String : kSecClassGenericPassword, kSecAttrAccessible as String : kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, kSecAttrService as String : serviceAttribute as AnyObject, kSecAttrAccount as String : accountAttribute as AnyObject ] } func accessToken() throws -> String? { var query = keychainQuery query[kSecReturnData as String] = kCFBooleanTrue query[kSecMatchLimit as String] = kSecMatchLimitOne /** Fixes the issue with Keychain access in release mode. https://devforums.apple.com/message/1070614#1070614 */ var dataTypeRef: AnyObject? let status = withUnsafeMutablePointer(to: &dataTypeRef) {cfPointer -> OSStatus in SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer(cfPointer)) } var accessToken: String? if status == errSecSuccess { if let retrievedData = dataTypeRef as? Data { if retrievedData.count != 0 { accessToken = NSString(data: retrievedData, encoding: String.Encoding.utf8.rawValue) as String? } } } if status != errSecSuccess && status != errSecItemNotFound { let error = errorWithStatus(status) self.logger?.logError(error, withMessage: "Keychain can't read access token.") throw error } return accessToken } func deleteAccessToken() throws { let query = keychainQuery let status = SecItemDelete(query as CFDictionary) if status != errSecSuccess && status != errSecItemNotFound { let error = errorWithStatus(status) self.logger?.logError(error, withMessage: "Keychain can't delete access token .") throw error } } func saveAccessToken(_ accessToken: String) throws { do { if (try self.accessToken()) != nil { try deleteAccessToken() } } catch { } var query = keychainQuery let accessTokenData = accessToken.data(using: String.Encoding.utf8, allowLossyConversion: false) query[kSecValueData as String] = accessTokenData as AnyObject? let status = SecItemAdd(query as CFDictionary, nil) if status != errSecSuccess { let error = errorWithStatus(status) self.logger?.logError(error, withMessage: "Keychain can't add access token.") throw error } } fileprivate func errorWithStatus(_ status: OSStatus) -> NSError { return NSError(domain: QuadratKeychainOSSatusErrorDomain, code: Int(status), userInfo: nil) } func allAllAccessTokens() -> [String] { return [""] } }
ecd9dfb0f48e525de41d9a5f84416da7
34.918919
115
0.620015
false
false
false
false