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
brocktonpoint/CCCodeExample
refs/heads/master
CCCodeExample/PhotosViewController.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2015 CawBox 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 /* Improvements that could be made: Pre-generate drop shadow Store a queue of off screen cells as to not need to re-create new ones */ class PhotosViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView? var photosNotification: AnyObject? var photos: JSONFetch? var arrangedPhotos = [JSONPhoto]() deinit { if let notification = photosNotification { NSNotificationCenter.defaultCenter().removeObserver (notification) } } } extension PhotosViewController { override func viewWillAppear (animated: Bool) { photosNotification = NSNotificationCenter.defaultCenter().addObserverForName (JSONFetch.PhotosDidChangeNotification, object: nil, queue: NSOperationQueue.mainQueue()) { [weak self] notification in dispatch_async(dispatch_get_main_queue()) { self?.arrangedPhotos.appendContentsOf (self?.photos?.allPhotos ?? []) self?.collectionView?.reloadData () } } photos = JSONFetch () } @IBAction func reArrangePhotos (sender: AnyObject) { arrangedPhotos = recursiveReorder (arrangedPhotos) collectionView?.reloadData () } } extension PhotosViewController: UICollectionViewDataSource { func collectionView ( collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return arrangedPhotos.count } func collectionView ( collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier ("photoCell", forIndexPath: indexPath) as! ShadowCollectionViewCell let photo = arrangedPhotos[indexPath.row] cell.titleLabel?.text = photo.title let photoNeedsUpdate = cell.photoID != photo.id cell.photoID = photo.id if photoNeedsUpdate { if !photo.hasLocalCache { cell.imageView?.image = nil } photo.cachePhoto { result in dispatch_async (dispatch_get_main_queue()) { if case .Photo (let cachedPhoto, let cacheID) = result { // Don't show the image if this cell doesn't match the ID anymore guard cell.photoID == cacheID else { return } cell.imageView?.image = cachedPhoto } } } } return cell } }
c38c833258658cd930105725b12a2a48
34.732143
176
0.622189
false
false
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/Classes/ViewRelated/Stats/Shared Views/GhostViews/StatsGhostTableViewRows.swift
gpl-2.0
1
protocol StatsRowGhostable: ImmuTableRow { } extension StatsRowGhostable { var action: ImmuTableAction? { return nil } func configureCell(_ cell: UITableViewCell) { DispatchQueue.main.async { cell.startGhostAnimation(style: GhostCellStyle.muriel) } } } struct StatsGhostGrowAudienceImmutableRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostGrowAudienceCell.defaultNib, StatsGhostGrowAudienceCell.self) }() } struct StatsGhostTwoColumnImmutableRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostTwoColumnCell.defaultNib, StatsGhostTwoColumnCell.self) }() } struct StatsGhostTopImmutableRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostTopCell.defaultNib, StatsGhostTopCell.self) }() var hideTopBorder = false var hideBottomBorder = false func configureCell(_ cell: UITableViewCell) { DispatchQueue.main.async { cell.startGhostAnimation(style: GhostCellStyle.muriel) } if let detailCell = cell as? StatsGhostTopCell { detailCell.topBorder?.isHidden = hideTopBorder detailCell.bottomBorder?.isHidden = hideBottomBorder } } } struct StatsGhostTopHeaderImmutableRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostTopHeaderCell.defaultNib, StatsGhostTopHeaderCell.self) }() } struct StatsGhostTabbedImmutableRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostTabbedCell.defaultNib, StatsGhostTabbedCell.self) }() } struct StatsGhostPostingActivitiesImmutableRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostPostingActivityCell.defaultNib, StatsGhostPostingActivityCell.self) }() } struct StatsGhostChartImmutableRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostChartCell.defaultNib, StatsGhostChartCell.self) }() } struct StatsGhostDetailRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostSingleRowCell.defaultNib, StatsGhostSingleRowCell.self) }() var hideTopBorder = false var isLastRow = false var enableTopPadding = false func configureCell(_ cell: UITableViewCell) { DispatchQueue.main.async { cell.startGhostAnimation(style: GhostCellStyle.muriel) } if let detailCell = cell as? StatsGhostSingleRowCell { detailCell.topBorder?.isHidden = hideTopBorder detailCell.isLastRow = isLastRow detailCell.enableTopPadding = enableTopPadding } } } struct StatsGhostTitleRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostTitleCell.defaultNib, StatsGhostTitleCell.self) }() } enum GhostCellStyle { static let muriel = GhostStyle(beatStartColor: .placeholderElement, beatEndColor: .placeholderElementFaded) }
787e01715fca6b12bc93447eeb9af93c
31.02
111
0.725796
false
false
false
false
Ataraxiis/MGW-Esport
refs/heads/develop
Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/Deferred.swift
apache-2.0
60
// // Deferred.swift // RxSwift // // Created by Krunoslav Zaher on 4/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class DeferredSink<S: ObservableType, O: ObserverType where S.E == O.E> : Sink<O>, ObserverType { typealias E = O.E private let _observableFactory: () throws -> S init(observableFactory: () throws -> S, observer: O) { _observableFactory = observableFactory super.init(observer: observer) } func run() -> Disposable { do { let result = try _observableFactory() return result.subscribe(self) } catch let e { forwardOn(.Error(e)) dispose() return NopDisposable.instance } } func on(event: Event<E>) { forwardOn(event) switch event { case .Next: break case .Error: dispose() case .Completed: dispose() } } } class Deferred<S: ObservableType> : Producer<S.E> { typealias Factory = () throws -> S private let _observableFactory : Factory init(observableFactory: Factory) { _observableFactory = observableFactory } override func run<O: ObserverType where O.E == S.E>(observer: O) -> Disposable { let sink = DeferredSink(observableFactory: _observableFactory, observer: observer) sink.disposable = sink.run() return sink } }
a8393d22801e012a5cba5d8e88901ca4
23.52459
97
0.573913
false
false
false
false
apple/swift
refs/heads/main
test/Interop/Cxx/operators/member-inline-typechecker.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-experimental-cxx-interop import MemberInline var lhs = LoadableIntWrapper(value: 42) let rhs = LoadableIntWrapper(value: 23) let resultPlus = lhs - rhs lhs += rhs let resultCall0 = lhs() let resultCall1 = lhs(1) let resultCall2 = lhs(1, 2) var boolWrapper = LoadableBoolWrapper(value: true) let notBoolResult = !boolWrapper var addressOnly = AddressOnlyIntWrapper(42) let addressOnlyResultCall0 = addressOnly() let addressOnlyResultCall1 = addressOnly(1) let addressOnlyResultCall2 = addressOnly(1, 2) var readWriteIntArray = ReadWriteIntArray() readWriteIntArray[2] = 321 let readWriteValue = readWriteIntArray[2] var readOnlyIntArray = ReadOnlyIntArray(3) let readOnlyValue = readOnlyIntArray[1] var writeOnlyIntArray = WriteOnlyIntArray() writeOnlyIntArray[2] = 654 let writeOnlyValue = writeOnlyIntArray[2] var readOnlyRvalueParam = ReadOnlyRvalueParam() let readOnlyRvalueVal = readOnlyRvalueParam[1] // expected-error {{value of type 'ReadOnlyRvalueParam' has no subscripts}} var readWriteRvalueParam = ReadWriteRvalueParam() let readWriteRvalueVal = readWriteRvalueParam[1] // expected-error {{value of type 'ReadWriteRvalueParam' has no subscripts}} var readWriteRvalueGetterParam = ReadWriteRvalueGetterParam() let readWriteRvalueGetterVal = readWriteRvalueGetterParam[1] var diffTypesArray = DifferentTypesArray() let diffTypesResultInt: Int32 = diffTypesArray[0] let diffTypesResultDouble: Double = diffTypesArray[0.5] var nonTrivialIntArrayByVal = NonTrivialIntArrayByVal(3) let nonTrivialValueByVal = nonTrivialIntArrayByVal[1] var diffTypesArrayByVal = DifferentTypesArrayByVal() let diffTypesResultIntByVal: Int32 = diffTypesArrayByVal[0] let diffTypesResultDoubleByVal: Double = diffTypesArrayByVal[0.5] let postIncrement = HasPostIncrementOperator() postIncrement.successor() // expected-error {{value of type 'HasPostIncrementOperator' has no member 'successor'}} let anotherReturnType = HasPreIncrementOperatorWithAnotherReturnType() let anotherReturnTypeResult: HasPreIncrementOperatorWithAnotherReturnType = anotherReturnType.successor() let voidReturnType = HasPreIncrementOperatorWithVoidReturnType() let voidReturnTypeResult: HasPreIncrementOperatorWithVoidReturnType = voidReturnType.successor() let immortalIncrement = myCounter.successor() // expected-error {{value of type 'ImmortalCounter' has no member 'successor'}}
d9ca71dcf1c69d788647e9a4795398ea
37.507937
125
0.821517
false
false
false
false
NUKisZ/OCAndSwift
refs/heads/master
OCAndSwift/OCAndSwift/SecondViewController.swift
mit
1
// // SecondViewController.swift // OCAndSwift // // Created by gongrong on 2017/5/11. // Copyright © 2017年 张坤. All rights reserved. // import UIKit class SecondViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() title = "swift" view.backgroundColor = UIColor.red let btn = UIButton(type: .system) btn.frame = CGRect(x: 50, y: 50, width: 50, height: 50) btn.setTitle("OC", for: .normal) btn.addTarget(self, action: #selector(click), for: .touchUpInside) btn.backgroundColor = UIColor.white view.addSubview(btn) // Do any additional setup after loading the view. } func click(){ let vc = ViewController() present(vc, animated: true, completion: nil) } func aa(){ print("aa") let vc = FourViewController() print(vc.nibName as Any); } 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. } */ }
dc6012c433efcfe31304fda002dc3e0b
26.45283
106
0.626804
false
false
false
false
programersun/HiChongSwift
refs/heads/master
HiChongSwift/FindCatelogWhiteCell.swift
apache-2.0
1
// // FindCatelogWhiteCell.swift // HiChongSwift // // Created by eagle on 15/1/27. // Copyright (c) 2015年 多思科技. All rights reserved. // import UIKit class FindCatelogWhiteCell: UITableViewCell { // 头像 @IBOutlet private weak var keeperAvatarImageView: UIImageView! var keeperAvatarPath: String? { didSet { if let path = keeperAvatarPath { keeperAvatarImageView.setImageWithURL(NSURL(string: path), placeholderImage: UIImage(named: "placeholderLogo")) } else { keeperAvatarImageView.image = nil } } } // 性别 @IBOutlet private weak var genderImageView: UIImageView! enum cateGender: String { case Male = "0" case Female = "1" case Unknown = "-1" init(pValue: String) { if pValue == "0" { self = .Male } else if pValue == "1" { self = .Female } else { self = .Unknown } } } var keeperGender: cateGender = .Unknown { didSet { switch keeperGender { case .Male: genderImageView.image = UIImage(named: "sqMale") case .Female: genderImageView.image = UIImage(named: "sqFemale") case .Unknown: genderImageView.image = nil } } } // 昵称 @IBOutlet weak var userNameLabel: UILabel! // 距离 @IBOutlet weak var distanceLabel: UILabel! // 宠物 @IBOutlet private var petImageViews: [UIImageView]! var petImagePaths: [String]? { didSet { if let images = petImagePaths { for i_imageView in petImageViews { if images.count >= i_imageView.tag { i_imageView.setImageWithURL(NSURL(string: images[i_imageView.tag - 1]), placeholderImage: UIImage(named: "placeholderLogo")) } else { i_imageView.image = nil } } } else { for oneImage in petImageViews { oneImage.image = nil } } } } @IBOutlet private weak var sepratorHeight: NSLayoutConstraint! @IBOutlet private weak var sepratorImageView: UIImageView! class var identifier: String { return "FindCatelogWhiteCellIdentifier" } override func awakeFromNib() { super.awakeFromNib() // Initialization code keeperAvatarImageView.roundCorner() sepratorHeight.constant = 1.0 / UIScreen.mainScreen().scale sepratorImageView.image = LCYCommon.sharedInstance.circleSepratorImage } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
aacbfdee765d79915d2cce6cf5fac57f
27.205607
148
0.537442
false
false
false
false
master-nevi/UPnAtom
refs/heads/master
Examples/ControlPointDemo_Swift/ControlPointDemo/Player.swift
mit
1
// // Player.swift // // Copyright (c) 2015 David Robles // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import UPnAtom private let _PlayerSharedInstance = Player() class Player { class var sharedInstance: Player { return _PlayerSharedInstance } var mediaServer: MediaServer1Device? var mediaRenderer: MediaRenderer1Device? { didSet { didSetRenderer(oldRenderer: oldValue, newRenderer: mediaRenderer) } } private(set) var playPauseButton: UIBarButtonItem! // TODO: Should ideally be a constant, see Github issue #10 private(set) var stopButton: UIBarButtonItem! // TODO: Should ideally be a constant, see Github issue #10 private var _position: Int = 0 private var _playlist: [ContentDirectory1Object]? private var _avTransportEventObserver: AnyObject? private var _playerState: PlayerState = PlayerState.Stopped { didSet { playerStateDidChange() } } private var _avTransportInstanceID = "0" enum PlayerState { case Unknown case Stopped case Playing case Paused } init() { playPauseButton = UIBarButtonItem(image: UIImage(named: "play_button"), style: .Plain, target: self, action: #selector(Player.playPauseButtonTapped(_:))) stopButton = UIBarButtonItem(image: UIImage(named: "stop_button"), style: .Plain, target: self, action: #selector(Player.stopButtonTapped(_:))) } func startPlayback(playlist: [ContentDirectory1Object], position: Int) { _playlist = playlist startPlayback(position: position) } func startPlayback(position position: Int) { _position = position if let item = _playlist?[position] as? ContentDirectory1VideoItem { let uri = item.resourceURL.absoluteString let instanceID = _avTransportInstanceID mediaRenderer?.avTransportService?.setAVTransportURI(instanceID: instanceID, currentURI: uri, currentURIMetadata: "", success: { () -> Void in print("URI set succeeded!") self.play({ () -> Void in print("Play command succeeded!") }, failure: { (error) -> Void in print("Play command failed: \(error)") }) }, failure: { (error) -> Void in print("URI set failed: \(error)") }) } } @objc private func playPauseButtonTapped(sender: AnyObject) { print("play/pause button tapped") switch _playerState { case .Playing: pause({ () -> Void in print("Pause command succeeded!") }, failure: { (error) -> Void in print("Pause command failed: \(error)") }) case .Paused, .Stopped: play({ () -> Void in print("Play command succeeded!") }, failure: { (error) -> Void in print("Play command failed: \(error)") }) default: print("Play/pause button cannot be used in this state.") } } @objc private func stopButtonTapped(sender: AnyObject) { print("stop button tapped") switch _playerState { case .Playing, .Paused: stop({ () -> Void in print("Stop command succeeded!") }, failure: { (error) -> Void in print("Stop command failed: \(error)") }) case .Stopped: print("Stop button cannot be used in this state.") default: print("Stop button cannot be used in this state.") } } private func didSetRenderer(oldRenderer oldRenderer: MediaRenderer1Device?, newRenderer: MediaRenderer1Device?) { if let avTransportEventObserver: AnyObject = _avTransportEventObserver { oldRenderer?.avTransportService?.removeEventObserver(avTransportEventObserver) } _avTransportEventObserver = newRenderer?.avTransportService?.addEventObserver(NSOperationQueue.currentQueue(), callBackBlock: { (event: UPnPEvent) -> Void in if let avTransportEvent = event as? AVTransport1Event, transportState = (avTransportEvent.instanceState["TransportState"] as? String)?.lowercaseString { print("\(event.service?.className) Event: \(avTransportEvent.instanceState)") print("transport state: \(transportState)") if transportState.rangeOfString("playing") != nil { self._playerState = .Playing } else if transportState.rangeOfString("paused") != nil { self._playerState = .Paused } else if transportState.rangeOfString("stopped") != nil { self._playerState = .Stopped } else { self._playerState = .Unknown } } }) } private func playerStateDidChange() { switch _playerState { case .Stopped, .Paused, .Unknown: playPauseButton.image = UIImage(named: "play_button") case .Playing: playPauseButton.image = UIImage(named: "pause_button") } } private func play(success: () -> Void, failure:(error: NSError) -> Void) { self.mediaRenderer?.avTransportService?.play(instanceID: _avTransportInstanceID, speed: "1", success: success, failure: failure) } private func pause(success: () -> Void, failure:(error: NSError) -> Void) { self.mediaRenderer?.avTransportService?.pause(instanceID: _avTransportInstanceID, success: success, failure: failure) } private func stop(success: () -> Void, failure:(error: NSError) -> Void) { self.mediaRenderer?.avTransportService?.stop(instanceID: _avTransportInstanceID, success: success, failure: failure) } }
b055035fbf68d042f2dac53da6416de2
40.270115
165
0.605069
false
false
false
false
goRestart/restart-backend-app
refs/heads/develop
Sources/Domain/Model/Game/Game.swift
gpl-3.0
1
import Foundation public struct Game { public let identifier: String public let title: String public let alternativeNames: [String] public let description: String public let images: [Image] public let company: GameCompany? public let platforms: [Platform] public let genres: [GameGenre] public let released: Date public init(identifier: String, title: String, alternativeNames: [String], description: String, images: [Image], company: GameCompany?, platforms: [Platform], genres: [GameGenre], released: Date) { self.identifier = identifier self.title = title self.alternativeNames = alternativeNames self.description = description self.images = images self.company = company self.platforms = platforms self.genres = genres self.released = released } }
a2e5815fa64b1c0333042f3ab3e712e4
27.885714
48
0.586548
false
false
false
false
tutsplus/iOSFromScratch-ShoppingList-2
refs/heads/master
Shopping List/EditItemViewController.swift
bsd-2-clause
1
// // EditItemViewController.swift // Shopping List // // Created by Bart Jacobs on 18/12/15. // Copyright © 2015 Envato Tuts+. All rights reserved. // import UIKit protocol EditItemViewControllerDelegate { func controller(controller: EditItemViewController, didUpdateItem item: Item) } class EditItemViewController: UIViewController { @IBOutlet var nameTextField: UITextField! @IBOutlet var priceTextField: UITextField! var item: Item! var delegate: EditItemViewControllerDelegate? // MARK: - // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() // Create Save Button navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Save, target: self, action: "save:") // Populate Text Fields nameTextField.text = item.name priceTextField.text = "\(item.price)" } // MARK: - // MARK: Actions func save(sender: UIBarButtonItem) { if let name = nameTextField.text, let priceAsString = priceTextField.text, let price = Float(priceAsString) { // Update Item item.name = name item.price = price // Notify Delegate delegate?.controller(self, didUpdateItem: item) // Pop View Controller navigationController?.popViewControllerAnimated(true) } } }
101d75551248c11da641eccebac39b78
26.358491
118
0.626897
false
false
false
false
vanyaland/Tagger
refs/heads/master
Tagger/Sources/Common/Helpers/WebService/Base/HttpApiClient+MultipartFormData.swift
mit
1
/** * Copyright (c) 2016 Ivan Magda * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Foundation // MARK: Typealiases /// - parameter data: Data to uploaded /// - parameter name: The optional field name to be used when uploading files. If you supply paths, you must supply filePathKey, too. /// - parameter fileName: Name of the uploading file typealias MultipartData = (data: Data, name: String, fileName: String) // MARK: - HttpApiClient (multipart/form-data) extension HttpApiClient { /// Creates body of the multipart/form-data request /// /// - parameter parameters: The optional dictionary containing keys and values to be passed to web service /// - parameter files: An optional array containing multipart/form-data parts /// - parameter boundary: The multipart/form-data boundary /// /// - returns: The NSData of the body of the request func createMultipartBody(params parameters: HttpMethodParams?, files: [MultipartData]?, boundary: String) -> Data { let body = NSMutableData() parameters?.forEach { (key, value) in body.appendString("--\(boundary)\r\n") body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") body.appendString("\(value)\r\n") } files?.forEach { body.appendString("--\(boundary)\r\n") body.appendString("Content-Disposition:form-data; name=\"\($0.name)\"; filename=\"\($0.fileName)\"\r\n") body.appendString("Content-Type: \($0.data.mimeType)\r\n\r\n") body.append($0.data) body.appendString("\r\n") } body.appendString("--\(boundary)--\r\n") return body as Data } /// Create boundary string for multipart/form-data request /// /// - returns: The boundary string that consists of "Boundary-" followed by a UUID string. func generateBoundaryString() -> String { return "Boundary-\(UUID().uuidString)" } } // MARK: - NSMutableData+AppendString - extension NSMutableData { /// Append string to NSMutableData /// /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to NSData, and then add that data to the NSMutableData, this wraps it in a nice convenient little extension to NSMutableData. This converts using UTF-8. /// /// - parameter string: The string to be added to the `NSMutableData`. func appendString(_ string: String) { let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true) append(data!) } }
50772ae19d85c2b211f3252785252522
39.956044
243
0.668098
false
false
false
false
shu223/watchOS-2-Sampler
refs/heads/master
watchOS2Sampler WatchKit Extension/PickerStylesInterfaceController.swift
mit
1
// // PickerStylesInterfaceController.swift // watchOS2Sampler // // Created by Shuichi Tsutsumi on 2015/06/12. // Copyright © 2015 Shuichi Tsutsumi. All rights reserved. // import WatchKit import Foundation class PickerStylesInterfaceController: WKInterfaceController { @IBOutlet weak var listPicker: WKInterfacePicker! @IBOutlet weak var stackPicker: WKInterfacePicker! @IBOutlet weak var sequencePicker: WKInterfacePicker! var pickerItems: [WKPickerItem]! = [] override func awake(withContext context: Any?) { super.awake(withContext: context) for i in 1...10 { let pickerItem = WKPickerItem() let imageName = "m\(i)" let image = WKImage(imageName: imageName) // Text to show when the item is being displayed in a picker with the 'List' style. pickerItem.title = imageName // Caption to show for the item when focus style includes a caption callout. pickerItem.caption = imageName // An accessory image to show next to the title in a picker with the 'List' style. // Note that the image will be scaled and centered to fit within an 13×13pt rect. pickerItem.accessoryImage = image // A custom image to show for the item, used instead of the title + accessory // image when more flexibility is needed, or when displaying in the stack or // sequence style. The image will be scaled and centered to fit within the // picker's bounds or item row bounds. pickerItem.contentImage = image pickerItems.append(pickerItem) // print("\(pickerItems)") } } override func willActivate() { super.willActivate() listPicker.setItems(pickerItems) sequencePicker.setItems(pickerItems) stackPicker.setItems(pickerItems) } override func didDeactivate() { super.didDeactivate() } }
584b9bbc1c7825f32daf40927d9af10c
31.936508
95
0.624096
false
false
false
false
zalando/ModularDemo
refs/heads/master
IPLookupUI/IPLookupUI App/MyIPTestService.swift
bsd-2-clause
1
// // MyIPTestService.swift // IPLookupUI App // // Created by Oliver Eikemeier on 26.09.15. // Copyright © 2015 Zalando SE. All rights reserved. // import Foundation import ZContainer import IPLookupUI class MyIPTestService: IPLookupUIService { // MARK: - Shared Instance private static let sharedInstance = MyIPTestService() static func sharedService() -> MyIPTestService { return MyIPTestService.sharedInstance } // MARK: - Result Type enum ResultType { case IPv4, IPv6, Timeout, Immediate, Alternating } var resultType: ResultType private init(resultType: ResultType = .Immediate) { self.resultType = resultType } // MARK: - Lookup Simulation private let completionQueue = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0) private func complete(after delta: NSTimeInterval = 0.0, IP: String? = nil, error: ErrorType? = nil, completionHandler: (IP: String?, error: ErrorType?) -> Void) { let when: dispatch_time_t if delta > 0 { let offset = Int64(delta * Double(NSEC_PER_SEC)) when = dispatch_time(DISPATCH_TIME_NOW, offset) } else { when = DISPATCH_TIME_NOW } dispatch_after(when, completionQueue) { completionHandler(IP: IP, error: error) } } private var timeoutResult = true func lookupIP(completionHandler: (IP: String?, error: ErrorType?) -> Void) { switch resultType { case .IPv4: complete(after: 2.0, IP: "69.89.31.226", completionHandler: completionHandler) case .IPv6: complete(after: 2.0, IP: "2001:0db8:85a3:08d3:1319:8a2e:0370:7344", completionHandler: completionHandler) case .Timeout: complete(after: 5.0, error: NSURLError.TimedOut, completionHandler: completionHandler) case .Immediate: complete(IP: "127.0.0.1", completionHandler: completionHandler) case .Alternating: if timeoutResult { complete(after: 2.0, error: NSURLError.TimedOut, completionHandler: completionHandler) } else { complete(IP: "127.0.0.1", completionHandler: completionHandler) } timeoutResult = !timeoutResult } } }
afa4b35ae1210ff83c9bd60b5d5e443c
30.644737
167
0.602495
false
true
false
false
diwip/inspector-ios
refs/heads/master
Carthage/Checkouts/RxSwift/RxCocoa/Common/CocoaUnits/Driver/Driver+Operators.swift
apache-2.0
7
// // Driver+Operators.swift // Rx // // Created by Krunoslav Zaher on 9/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif // MARK: map extension DriverConvertibleType { /** Projects each element of an observable sequence into a new form. - parameter selector: A transform function to apply to each source element. - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. */ @warn_unused_result(message="http://git.io/rxs.uo") public func map<R>(selector: E -> R) -> Driver<R> { let source = self .asObservable() .map(selector) return Driver<R>(source) } } // MARK: filter extension DriverConvertibleType { /** Filters the elements of an observable sequence based on a predicate. - parameter predicate: A function to test each source element for a condition. - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. */ @warn_unused_result(message="http://git.io/rxs.uo") public func filter(predicate: (E) -> Bool) -> Driver<E> { let source = self .asObservable() .filter(predicate) return Driver(source) } } // MARK: switchLatest extension DriverConvertibleType where E : DriverConvertibleType { /** Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. Each time a new inner observable sequence is received, unsubscribe from the previous inner observable sequence. - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ @warn_unused_result(message="http://git.io/rxs.uo") public func switchLatest() -> Driver<E.E> { let source: Observable<E.E> = self .asObservable() .map { $0.asDriver() } .switchLatest() return Driver<E.E>(source) } } // MARK: flatMapLatest extension DriverConvertibleType { /** Projects each element of an observable sequence into a new sequence of observable sequences and then transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. It is a combination of `map` + `switchLatest` operator - parameter selector: A transform function to apply to each element. - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ @warn_unused_result(message="http://git.io/rxs.uo") public func flatMapLatest<R>(selector: (E) -> Driver<R>) -> Driver<R> { let source: Observable<R> = self .asObservable() .flatMapLatest(selector) return Driver<R>(source) } } // MARK: flatMapFirst extension DriverConvertibleType { /** Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. If element is received while there is some projected observable sequence being merged it will simply be ignored. - parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel. - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated. */ @warn_unused_result(message="http://git.io/rxs.uo") public func flatMapFirst<R>(selector: (E) -> Driver<R>) -> Driver<R> { let source: Observable<R> = self .asObservable() .flatMapFirst(selector) return Driver<R>(source) } } // MARK: doOn extension DriverConvertibleType { /** Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. - parameter eventHandler: Action to invoke for each event in the observable sequence. - returns: The source sequence with the side-effecting behavior applied. */ @warn_unused_result(message="http://git.io/rxs.uo") public func doOn(eventHandler: (Event<E>) -> Void) -> Driver<E> { let source = self.asObservable() .doOn(eventHandler) return Driver(source) } /** Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. This callback will never be invoked since driver can't error out. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - returns: The source sequence with the side-effecting behavior applied. */ @warn_unused_result(message="http://git.io/rxs.uo") public func doOn(onNext onNext: (E -> Void)? = nil, onError: (ErrorType -> Void)? = nil, onCompleted: (() -> Void)? = nil) -> Driver<E> { let source = self.asObservable() .doOn(onNext: onNext, onError: onError, onCompleted: onCompleted) return Driver(source) } /** Invokes an action for each Next event in the observable sequence, and propagates all observer messages through the result sequence. - parameter onNext: Action to invoke for each element in the observable sequence. - returns: The source sequence with the side-effecting behavior applied. */ @warn_unused_result(message="http://git.io/rxs.uo") public func doOnNext(onNext: (E -> Void)) -> Driver<E> { return self.doOn(onNext: onNext) } /** Invokes an action for the Completed event in the observable sequence, and propagates all observer messages through the result sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - returns: The source sequence with the side-effecting behavior applied. */ @warn_unused_result(message="http://git.io/rxs.uo") public func doOnCompleted(onCompleted: (() -> Void)) -> Driver<E> { return self.doOn(onCompleted: onCompleted) } } // MARK: debug extension DriverConvertibleType { /** Prints received events for all observers on standard output. - parameter identifier: Identifier that is printed together with event description to standard output. - returns: An observable sequence whose events are printed to standard output. */ @warn_unused_result(message="http://git.io/rxs.uo") public func debug(identifier: String? = nil, file: String = __FILE__, line: UInt = __LINE__, function: String = __FUNCTION__) -> Driver<E> { let source = self.asObservable() .debug(identifier, file: file, line: line, function: function) return Driver(source) } } // MARK: distinctUntilChanged extension DriverConvertibleType where E: Equatable { /** Returns an observable sequence that contains only distinct contiguous elements according to equality operator. - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func distinctUntilChanged() -> Driver<E> { let source = self.asObservable() .distinctUntilChanged({ $0 }, comparer: { ($0 == $1) }) return Driver(source) } } extension DriverConvertibleType { /** Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. - parameter keySelector: A function to compute the comparison key for each element. - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func distinctUntilChanged<K: Equatable>(keySelector: (E) -> K) -> Driver<E> { let source = self.asObservable() .distinctUntilChanged(keySelector, comparer: { $0 == $1 }) return Driver(source) } /** Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. - parameter comparer: Equality comparer for computed key values. - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func distinctUntilChanged(comparer: (lhs: E, rhs: E) -> Bool) -> Driver<E> { let source = self.asObservable() .distinctUntilChanged({ $0 }, comparer: comparer) return Driver(source) } /** Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. - parameter keySelector: A function to compute the comparison key for each element. - parameter comparer: Equality comparer for computed key values. - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func distinctUntilChanged<K>(keySelector: (E) -> K, comparer: (lhs: K, rhs: K) -> Bool) -> Driver<E> { let source = self.asObservable() .distinctUntilChanged(keySelector, comparer: comparer) return Driver(source) } } // MARK: flatMap extension DriverConvertibleType { /** Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. - parameter selector: A transform function to apply to each element. - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func flatMap<R>(selector: (E) -> Driver<R>) -> Driver<R> { let source = self.asObservable() .flatMap(selector) return Driver<R>(source) } } // MARK: merge extension DriverConvertibleType where E : DriverConvertibleType { /** Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence. - parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently. - returns: The observable sequence that merges the elements of the observable sequences. */ @warn_unused_result(message="http://git.io/rxs.uo") public func merge() -> Driver<E.E> { let source = self.asObservable() .map { $0.asDriver() } .merge() return Driver<E.E>(source) } /** Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences. - returns: The observable sequence that merges the elements of the inner sequences. */ @warn_unused_result(message="http://git.io/rxs.uo") public func merge(maxConcurrent maxConcurrent: Int) -> Driver<E.E> { let source = self.asObservable() .map { $0.asDriver() } .merge(maxConcurrent: maxConcurrent) return Driver<E.E>(source) } } // MARK: throttle extension DriverConvertibleType { /** Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. `throttle` and `debounce` are synonyms. - parameter dueTime: Throttling duration for each element. - returns: The throttled sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func throttle(dueTime: RxTimeInterval) -> Driver<E> { let source = self.asObservable() .throttle(dueTime, scheduler: driverObserveOnScheduler) return Driver(source) } /** Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. `throttle` and `debounce` are synonyms. - parameter dueTime: Throttling duration for each element. - returns: The throttled sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func debounce(dueTime: RxTimeInterval) -> Driver<E> { let source = self.asObservable() .debounce(dueTime, scheduler: driverObserveOnScheduler) return Driver(source) } } // MARK: scan extension DriverConvertibleType { /** Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. For aggregation behavior with no intermediate results, see `reduce`. - parameter seed: The initial accumulator value. - parameter accumulator: An accumulator function to be invoked on each element. - returns: An observable sequence containing the accumulated values. */ @warn_unused_result(message="http://git.io/rxs.uo") public func scan<A>(seed: A, accumulator: (A, E) -> A) -> Driver<A> { let source = self.asObservable() .scan(seed, accumulator: accumulator) return Driver<A>(source) } } // MARK: concat extension SequenceType where Generator.Element : DriverConvertibleType { /** Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ @warn_unused_result(message="http://git.io/rxs.uo") public func concat() -> Driver<Generator.Element.E> { let source = self.lazy.map { $0.asDriver().asObservable() }.concat() return Driver<Generator.Element.E>(source) } } extension CollectionType where Generator.Element : DriverConvertibleType { /** Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. - returns: An observable sequence that contains the elements of each given sequence, in sequential order. */ @warn_unused_result(message="http://git.io/rxs.uo") public func concat() -> Driver<Generator.Element.E> { let source = self.map { $0.asDriver().asObservable() }.concat() return Driver<Generator.Element.E>(source) } } // MARK: zip extension CollectionType where Generator.Element : DriverConvertibleType { /** Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ @warn_unused_result(message="http://git.io/rxs.uo") public func zip<R>(resultSelector: [Generator.Element.E] throws -> R) -> Driver<R> { let source = self.map { $0.asDriver().asObservable() }.zip(resultSelector) return Driver<R>(source) } } // MARK: combineLatest extension CollectionType where Generator.Element : DriverConvertibleType { /** Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. - parameter resultSelector: Function to invoke whenever any of the sources produces an element. - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ @warn_unused_result(message="http://git.io/rxs.uo") public func combineLatest<R>(resultSelector: [Generator.Element.E] throws -> R) -> Driver<R> { let source = self.map { $0.asDriver().asObservable() }.combineLatest(resultSelector) return Driver<R>(source) } } // MARK: withLatestFrom extension DriverConvertibleType { /** Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. - parameter second: Second observable source. - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. */ public func withLatestFrom<SecondO: DriverConvertibleType, ResultType>(second: SecondO, resultSelector: (E, SecondO.E) -> ResultType) -> Driver<ResultType> { let source = self.asObservable() .withLatestFrom(second.asDriver(), resultSelector: resultSelector) return Driver<ResultType>(source) } /** Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emitts an element. - parameter second: Second observable source. - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. */ public func withLatestFrom<SecondO: DriverConvertibleType>(second: SecondO) -> Driver<SecondO.E> { let source = self.asObservable() .withLatestFrom(second.asDriver()) return Driver<SecondO.E>(source) } } // MARK: skip extension DriverConvertibleType { /** Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) - parameter count: The number of elements to skip before returning the remaining elements. - returns: An observable sequence that contains the elements that occur after the specified index in the input sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func skip(count: Int) -> Driver<E> { let source = self.asObservable() .skip(count) return Driver(source) } } // MARK: startWith extension DriverConvertibleType { /** Prepends a value to an observable sequence. - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) - parameter element: Element to prepend to the specified sequence. - returns: The source sequence prepended with the specified values. */ @warn_unused_result(message="http://git.io/rxs.uo") public func startWith(element: E) -> Driver<E> { let source = self.asObservable() .startWith(element) return Driver(source) } }
4c16ec3554ac015e8f9361ce9c53bab1
39.945233
217
0.693039
false
false
false
false
Esri/arcgis-runtime-samples-ios
refs/heads/main
arcgis-ios-sdk-samples/Display information/Display grid/DisplayGridViewController.swift
apache-2.0
1
// // Copyright 2017 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class DisplayGridViewController: UIViewController { @IBOutlet weak var mapView: AGSMapView! override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = [ "DisplayGridViewController", "DisplayGridSettingsViewController", "OptionsTableViewController", "ColorPickerViewController" ] // Assign map to the map view. mapView.map = AGSMap(basemapStyle: .arcGISImageryStandard) // Set viewpoint. let center = AGSPoint(x: -7702852.905619, y: 6217972.345771, spatialReference: .webMercator()) mapView.setViewpoint(AGSViewpoint(center: center, scale: 23227)) // Add lat long grid. mapView.grid = AGSLatitudeLongitudeGrid() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let navController = segue.destination as? UINavigationController, let controller = navController.viewControllers.first as? DisplayGridSettingsViewController { controller.mapView = mapView controller.preferredContentSize = { let height: CGFloat if traitCollection.horizontalSizeClass == .regular, traitCollection.verticalSizeClass == .regular { height = 350 } else { height = 250 } return CGSize(width: 375, height: height) }() navController.presentationController?.delegate = self } } } extension DisplayGridViewController: UIAdaptivePresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } }
26eecc6ce00fed6bb91609bc90ac188d
38.075758
142
0.661497
false
false
false
false
na4lapy/na4lapy-ios
refs/heads/master
Na4Łapy/Model/Photo.swift
apache-2.0
1
// // Photo.swift // Na4Łapy // // Created by Andrzej Butkiewicz on 06.06.2016. // Copyright © 2016 Stowarzyszenie Na4Łapy. All rights reserved. // import Foundation import UIKit class Photo { let id: Int let url: URL var author: String? var image: UIImage? var downloaded: Bool = false var profile: Bool = false init?(dictionary: [String:AnyObject]) { guard let id = dictionary[JsonAttr.id] as? Int, let fileName = dictionary[JsonAttr.fileName] as? String, let url = URL(string: baseUrl + EndPoint.files + fileName) else { log.error(Err.noIdOrName.desc()) return nil } self.id = id self.url = url self.image = UIImage(named: "Placeholder") if let author = dictionary[JsonAttr.author] as? String { self.author = author } if let isProfile = dictionary[JsonAttr.profile] as? Bool { self.profile = isProfile } } /** Asynchroniczne pobieranie obrazka */ func download(_ success: (() -> Void)? = nil) { if self.downloaded { log.debug("Zdjęcie zostało już wcześniej pobrane.") success?() return } log.debug("Pobieram zdjęcie... \(self.url.absoluteString)") Request.getImageData(self.url, success: { (image) in self.image = image self.downloaded = true success?() }, failure: { (error) in log.error("Błąd: \(error.localizedDescription) dla urla: \(self.url.absoluteString)") } ) } }
1757cb8d2e3db3d9087b2a6e73609fae
25.4
101
0.537296
false
false
false
false
wuhduhren/Mr-Ride-iOS
refs/heads/master
Mr-Ride-iOS/Model/MapData/MapDataRouter.swift
mit
1
// // MapDataRouter.swift // Mr-Ride-iOS // // Created by Eph on 2016/6/13. // Copyright © 2016年 AppWorks School WuDuhRen. All rights reserved. // Reference: YBRouter.swift Created by 許郁棋 on 2016/4/27. // import Alamofire import JWT enum MapDataRouter { case GetPublicToilets case GetRiverSideToilets case GetYoubike } // MARK: - URLRequestConvertible extension MapDataRouter: URLRequestConvertible { var method: Alamofire.Method { switch self { case .GetRiverSideToilets: return .GET case .GetYoubike: return .GET case .GetPublicToilets: return .GET } } var url: NSURL { switch self { case .GetRiverSideToilets: return NSURL(string: "http://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=fe49c753-9358-49dd-8235-1fcadf5bfd3f")! case .GetYoubike: return NSURL(string: "http://data.taipei/youbike")! case .GetPublicToilets: return NSURL(string: "http://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=008ed7cf-2340-4bc4-89b0-e258a5573be2")! } } var URLRequest: NSMutableURLRequest { let URLRequest = NSMutableURLRequest(URL: url) URLRequest.HTTPMethod = method.rawValue return URLRequest } }
a2b6c580a3f95818f0b9ae4436cd998a
24.327273
172
0.634602
false
false
false
false
uasys/swift
refs/heads/master
stdlib/public/core/String.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 // //===----------------------------------------------------------------------===// import SwiftShims /// A type that can represent a string as a collection of characters. /// /// Do not declare new conformances to `StringProtocol`. Only the `String` and /// `Substring` types in the standard library are valid conforming types. public protocol StringProtocol : BidirectionalCollection, TextOutputStream, TextOutputStreamable, LosslessStringConvertible, ExpressibleByStringLiteral, Hashable, Comparable where Iterator.Element == Character { associatedtype UTF8View : /*Bidirectional*/Collection where UTF8View.Element == UInt8 // Unicode.UTF8.CodeUnit associatedtype UTF16View : BidirectionalCollection where UTF16View.Element == UInt16 // Unicode.UTF16.CodeUnit associatedtype UnicodeScalarView : BidirectionalCollection where UnicodeScalarView.Element == Unicode.Scalar var utf8: UTF8View { get } var utf16: UTF16View { get } var unicodeScalars: UnicodeScalarView { get } #if _runtime(_ObjC) func hasPrefix(_ prefix: String) -> Bool func hasSuffix(_ prefix: String) -> Bool #endif func lowercased() -> String func uppercased() -> String /// Creates a string from the given Unicode code units in the specified /// encoding. /// /// - Parameters: /// - codeUnits: A collection of code units encoded in the ecoding /// specified in `sourceEncoding`. /// - sourceEncoding: The encoding in which `codeUnits` should be /// interpreted. init<C: Collection, Encoding: Unicode.Encoding>( decoding codeUnits: C, as sourceEncoding: Encoding.Type ) where C.Iterator.Element == Encoding.CodeUnit /// Creates a string from the null-terminated, UTF-8 encoded sequence of /// bytes at the given pointer. /// /// - Parameter nullTerminatedUTF8: A pointer to a sequence of contiguous, /// UTF-8 encoded bytes ending just before the first zero byte. init(cString nullTerminatedUTF8: UnsafePointer<CChar>) /// Creates a string from the null-terminated sequence of bytes at the given /// pointer. /// /// - Parameters: /// - nullTerminatedCodeUnits: A pointer to a sequence of contiguous code /// units in the encoding specified in `sourceEncoding`, ending just /// before the first zero code unit. /// - sourceEncoding: The encoding in which the code units should be /// interpreted. init<Encoding: Unicode.Encoding>( decodingCString nullTerminatedCodeUnits: UnsafePointer<Encoding.CodeUnit>, as sourceEncoding: Encoding.Type) /// Calls the given closure with a pointer to the contents of the string, /// represented as a null-terminated sequence of UTF-8 code units. /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withCString(_:)`. Do not store or return the pointer for /// later use. /// /// - Parameter body: A closure with a pointer parameter that points to a /// null-terminated sequence of UTF-8 code units. If `body` has a return /// value, that value is also used as the return value for the /// `withCString(_:)` method. The pointer argument is valid only for the /// duration of the method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. func withCString<Result>( _ body: (UnsafePointer<CChar>) throws -> Result) rethrows -> Result /// Calls the given closure with a pointer to the contents of the string, /// represented as a null-terminated sequence of code units. /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withCString(encodedAs:_:)`. Do not store or return the /// pointer for later use. /// /// - Parameters: /// - body: A closure with a pointer parameter that points to a /// null-terminated sequence of code units. If `body` has a return /// value, that value is also used as the return value for the /// `withCString(encodedAs:_:)` method. The pointer argument is valid /// only for the duration of the method's execution. /// - targetEncoding: The encoding in which the code units should be /// interpreted. /// - Returns: The return value, if any, of the `body` closure parameter. func withCString<Result, Encoding: Unicode.Encoding>( encodedAs targetEncoding: Encoding.Type, _ body: (UnsafePointer<Encoding.CodeUnit>) throws -> Result ) rethrows -> Result } extension StringProtocol { //@available(swift, deprecated: 3.2, obsoleted: 4.0, message: "Please use the StringProtocol itself") //public var characters: Self { return self } @available(swift, deprecated: 3.2, obsoleted: 4.0, renamed: "UTF8View.Index") public typealias UTF8Index = UTF8View.Index @available(swift, deprecated: 3.2, obsoleted: 4.0, renamed: "UTF16View.Index") public typealias UTF16Index = UTF16View.Index @available(swift, deprecated: 3.2, obsoleted: 4.0, renamed: "UnicodeScalarView.Index") public typealias UnicodeScalarIndex = UnicodeScalarView.Index } /// A protocol that provides fast access to a known representation of String. /// /// Can be used to specialize generic functions that would otherwise end up /// doing grapheme breaking to vend individual characters. internal protocol _SwiftStringView { /// A `String`, having the same contents as `self`, that may be unsuitable for /// long-term storage. var _ephemeralContent : String { get } /// A `String`, having the same contents as `self`, that is suitable for /// long-term storage. var _persistentContent : String { get } } extension _SwiftStringView { var _ephemeralContent : String { return _persistentContent } } extension StringProtocol { public // Used in the Foundation overlay var _ephemeralString : String { if _fastPath(self is _SwiftStringView) { return (self as! _SwiftStringView)._ephemeralContent } return String(String.CharacterView(self)) } } extension String : _SwiftStringView { var _persistentContent : String { return characters._persistentContent } } /// Call body with a pointer to zero-terminated sequence of /// `TargetEncoding.CodeUnit` representing the same string as `source`, when /// `source` is interpreted as being encoded with `SourceEncoding`. internal func _withCString< Source : Collection, SourceEncoding : Unicode.Encoding, TargetEncoding : Unicode.Encoding, Result >( encodedAs targetEncoding: TargetEncoding.Type, from source: Source, encodedAs sourceEncoding: SourceEncoding.Type, execute body : (UnsafePointer<TargetEncoding.CodeUnit>) throws -> Result ) rethrows -> Result where Source.Iterator.Element == SourceEncoding.CodeUnit { return try _withCStringAndLength( encodedAs: targetEncoding, from: source, encodedAs: sourceEncoding) { p, _ in try body(p) } } @_semantics("optimize.sil.specialize.generic.partial.never") internal func _withCStringAndLength< Source : Collection, SourceEncoding : Unicode.Encoding, TargetEncoding : Unicode.Encoding, Result >( encodedAs targetEncoding: TargetEncoding.Type, from source: Source, encodedAs sourceEncoding: SourceEncoding.Type, execute body : (UnsafePointer<TargetEncoding.CodeUnit>, Int) throws -> Result ) rethrows -> Result where Source.Iterator.Element == SourceEncoding.CodeUnit { var targetLength = 0 // nul terminator var i = source.makeIterator() SourceEncoding.ForwardParser._parse(&i) { targetLength += numericCast( targetEncoding._transcode($0, from: SourceEncoding.self).count) } var a: [TargetEncoding.CodeUnit] = [] a.reserveCapacity(targetLength + 1) i = source.makeIterator() SourceEncoding.ForwardParser._parse(&i) { a.append( contentsOf: targetEncoding._transcode($0, from: SourceEncoding.self)) } a.append(0) return try body(a, targetLength) } extension _StringCore { /// Invokes `body` on a null-terminated sequence of code units in the given /// encoding corresponding to the substring in `bounds`. internal func _withCSubstring<Result, TargetEncoding: Unicode.Encoding>( in bounds: Range<Index>, encoding targetEncoding: TargetEncoding.Type, _ body: (UnsafePointer<TargetEncoding.CodeUnit>) throws -> Result ) rethrows -> Result { return try _withCSubstringAndLength(in: bounds, encoding: targetEncoding) { p,_ in try body(p) } } @_semantics("optimize.sil.specialize.generic.partial.never") internal func _withCSubstringAndLength< Result, TargetEncoding: Unicode.Encoding >( in bounds: Range<Index>, encoding targetEncoding: TargetEncoding.Type, _ body: (UnsafePointer<TargetEncoding.CodeUnit>, Int) throws -> Result ) rethrows -> Result { if _fastPath(hasContiguousStorage) { defer { _fixLifetime(self) } if isASCII { return try Swift._withCStringAndLength( encodedAs: targetEncoding, from: UnsafeBufferPointer(start: startASCII, count: count)[bounds], encodedAs: Unicode.ASCII.self, execute: body ) } else { return try Swift._withCStringAndLength( encodedAs: targetEncoding, from: UnsafeBufferPointer(start: startUTF16, count: count)[bounds], encodedAs: Unicode.UTF16.self, execute: body ) } } return try Swift._withCStringAndLength( encodedAs: targetEncoding, from: self[bounds], encodedAs: Unicode.UTF16.self, execute: body ) } } extension String { /// Creates a string from the given Unicode code units in the specified /// encoding. /// /// - Parameters: /// - codeUnits: A collection of code units encoded in the ecoding /// specified in `sourceEncoding`. /// - sourceEncoding: The encoding in which `codeUnits` should be /// interpreted. public init<C: Collection, Encoding: Unicode.Encoding>( decoding codeUnits: C, as sourceEncoding: Encoding.Type ) where C.Iterator.Element == Encoding.CodeUnit { let (b,_) = _StringBuffer.fromCodeUnits( codeUnits, encoding: sourceEncoding, repairIllFormedSequences: true) self = String(_StringCore(b!)) } /// Creates a string from the null-terminated sequence of bytes at the given /// pointer. /// /// - Parameters: /// - nullTerminatedCodeUnits: A pointer to a sequence of contiguous code /// units in the encoding specified in `sourceEncoding`, ending just /// before the first zero code unit. /// - sourceEncoding: The encoding in which the code units should be /// interpreted. public init<Encoding: Unicode.Encoding>( decodingCString nullTerminatedCodeUnits: UnsafePointer<Encoding.CodeUnit>, as sourceEncoding: Encoding.Type) { let codeUnits = _SentinelCollection( UnsafeBufferPointer(_unboundedStartingAt: nullTerminatedCodeUnits), until: _IsZero() ) self.init(decoding: codeUnits, as: sourceEncoding) } /// Calls the given closure with a pointer to the contents of the string, /// represented as a null-terminated sequence of code units. /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withCString(encodedAs:_:)`. Do not store or return the /// pointer for later use. /// /// - Parameters: /// - body: A closure with a pointer parameter that points to a /// null-terminated sequence of code units. If `body` has a return /// value, that value is also used as the return value for the /// `withCString(encodedAs:_:)` method. The pointer argument is valid /// only for the duration of the method's execution. /// - targetEncoding: The encoding in which the code units should be /// interpreted. /// - Returns: The return value, if any, of the `body` closure parameter. public func withCString<Result, TargetEncoding: Unicode.Encoding>( encodedAs targetEncoding: TargetEncoding.Type, _ body: (UnsafePointer<TargetEncoding.CodeUnit>) throws -> Result ) rethrows -> Result { return try _core._withCSubstring( in: _core.startIndex..<_core.endIndex, encoding: targetEncoding, body) } } // FIXME: complexity documentation for most of methods on String ought to be // qualified with "amortized" at least, as Characters are variable-length. /// A Unicode string value that is a collection of characters. /// /// A string is a series of characters, such as `"Swift"`, that forms a /// collection. Strings in Swift are Unicode correct and locale insensitive, /// and are designed to be efficient. The `String` type bridges with the /// Objective-C class `NSString` and offers interoperability with C functions /// that works with strings. /// /// You can create new strings using string literals or string interpolations. /// A *string literal* is a series of characters enclosed in quotes. /// /// let greeting = "Welcome!" /// /// *String interpolations* are string literals that evaluate any included /// expressions and convert the results to string form. String interpolations /// give you an easy way to build a string from multiple pieces. Wrap each /// expression in a string interpolation in parentheses, prefixed by a /// backslash. /// /// let name = "Rosa" /// let personalizedGreeting = "Welcome, \(name)!" /// // personalizedGreeting == "Welcome, Rosa!" /// /// let price = 2 /// let number = 3 /// let cookiePrice = "\(number) cookies: $\(price * number)." /// // cookiePrice == "3 cookies: $6." /// /// Combine strings using the concatenation operator (`+`). /// /// let longerGreeting = greeting + " We're glad you're here!" /// // longerGreeting == "Welcome! We're glad you're here!" /// /// Multiline string literals are enclosed in three double quotation marks /// (`"""`), with each delimiter on its own line. Indentation is stripped from /// each line of a multiline string literal to match the indentation of the /// closing delimiter. /// /// let banner = """ /// __, /// ( o /) _/_ /// `. , , , , // / /// (___)(_(_/_(_ //_ (__ /// /) /// (/ /// """ /// /// Modifying and Comparing Strings /// =============================== /// /// Strings always have value semantics. Modifying a copy of a string leaves /// the original unaffected. /// /// var otherGreeting = greeting /// otherGreeting += " Have a nice time!" /// // otherGreeting == "Welcome! Have a nice time!" /// /// print(greeting) /// // Prints "Welcome!" /// /// Comparing strings for equality using the equal-to operator (`==`) or a /// relational operator (like `<` or `>=`) is always performed using Unicode /// canonical representation. As a result, different representations of a /// string compare as being equal. /// /// let cafe1 = "Cafe\u{301}" /// let cafe2 = "Café" /// print(cafe1 == cafe2) /// // Prints "true" /// /// The Unicode scalar value `"\u{301}"` modifies the preceding character to /// include an accent, so `"e\u{301}"` has the same canonical representation /// as the single Unicode scalar value `"é"`. /// /// Basic string operations are not sensitive to locale settings, ensuring that /// string comparisons and other operations always have a single, stable /// result, allowing strings to be used as keys in `Dictionary` instances and /// for other purposes. /// /// Accessing String Elements /// ========================= /// /// A string is a collection of *extended grapheme clusters*, which approximate /// human-readable characters. Many individual characters, such as "é", "김", /// and "🇮🇳", can be made up of multiple Unicode scalar values. These scalar /// values are combined by Unicode's boundary algorithms into extended /// grapheme clusters, represented by the Swift `Character` type. Each element /// of a string is represented by a `Character` instance. /// /// For example, to retrieve the first word of a longer string, you can search /// for a space and then create a substring from a prefix of the string up to /// that point: /// /// let name = "Marie Curie" /// let firstSpace = name.index(of: " ") ?? name.endIndex /// let firstName = name[..<firstSpace] /// // firstName == "Marie" /// /// The `firstName` constant is an instance of the `Substring` type---a type /// that represents substrings of a string while sharing the original string's /// storage. Substrings present the same interface as strings. /// /// print("\(name)'s first name has \(firstName.count) letters.") /// // Prints "Marie Curie's first name has 5 letters." /// /// Accessing a String's Unicode Representation /// =========================================== /// /// If you need to access the contents of a string as encoded in different /// Unicode encodings, use one of the string's `unicodeScalars`, `utf16`, or /// `utf8` properties. Each property provides access to a view of the string /// as a series of code units, each encoded in a different Unicode encoding. /// /// To demonstrate the different views available for every string, the /// following examples use this `String` instance: /// /// let cafe = "Cafe\u{301} du 🌍" /// print(cafe) /// // Prints "Café du 🌍" /// /// The `cafe` string is a collection of the nine characters that are visible /// when the string is displayed. /// /// print(cafe.count) /// // Prints "9" /// print(Array(cafe)) /// // Prints "["C", "a", "f", "é", " ", "d", "u", " ", "🌍"]" /// /// Unicode Scalar View /// ------------------- /// /// A string's `unicodeScalars` property is a collection of Unicode scalar /// values, the 21-bit codes that are the basic unit of Unicode. Each scalar /// value is represented by a `Unicode.Scalar` instance and is equivalent to a /// UTF-32 code unit. /// /// print(cafe.unicodeScalars.count) /// // Prints "10" /// print(Array(cafe.unicodeScalars)) /// // Prints "["C", "a", "f", "e", "\u{0301}", " ", "d", "u", " ", "\u{0001F30D}"]" /// print(cafe.unicodeScalars.map { $0.value }) /// // Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 127757]" /// /// The `unicodeScalars` view's elements comprise each Unicode scalar value in /// the `cafe` string. In particular, because `cafe` was declared using the /// decomposed form of the `"é"` character, `unicodeScalars` contains the /// scalar values for both the letter `"e"` (101) and the accent character /// `"´"` (769). /// /// UTF-16 View /// ----------- /// /// A string's `utf16` property is a collection of UTF-16 code units, the /// 16-bit encoding form of the string's Unicode scalar values. Each code unit /// is stored as a `UInt16` instance. /// /// print(cafe.utf16.count) /// // Prints "11" /// print(Array(cafe.utf16)) /// // Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 55356, 57101]" /// /// The elements of the `utf16` view are the code units for the string when /// encoded in UTF-16. These elements match those accessed through indexed /// `NSString` APIs. /// /// let nscafe = cafe as NSString /// print(nscafe.length) /// // Prints "11" /// print(nscafe.character(at: 3)) /// // Prints "101" /// /// UTF-8 View /// ---------- /// /// A string's `utf8` property is a collection of UTF-8 code units, the 8-bit /// encoding form of the string's Unicode scalar values. Each code unit is /// stored as a `UInt8` instance. /// /// print(cafe.utf8.count) /// // Prints "14" /// print(Array(cafe.utf8)) /// // Prints "[67, 97, 102, 101, 204, 129, 32, 100, 117, 32, 240, 159, 140, 141]" /// /// The elements of the `utf8` view are the code units for the string when /// encoded in UTF-8. This representation matches the one used when `String` /// instances are passed to C APIs. /// /// let cLength = strlen(cafe) /// print(cLength) /// // Prints "14" /// /// Measuring the Length of a String /// ================================ /// /// When you need to know the length of a string, you must first consider what /// you'll use the length for. Are you measuring the number of characters that /// will be displayed on the screen, or are you measuring the amount of /// storage needed for the string in a particular encoding? A single string /// can have greatly differing lengths when measured by its different views. /// /// For example, an ASCII character like the capital letter *A* is represented /// by a single element in each of its four views. The Unicode scalar value of /// *A* is `65`, which is small enough to fit in a single code unit in both /// UTF-16 and UTF-8. /// /// let capitalA = "A" /// print(capitalA.count) /// // Prints "1" /// print(capitalA.unicodeScalars.count) /// // Prints "1" /// print(capitalA.utf16.count) /// // Prints "1" /// print(capitalA.utf8.count) /// // Prints "1" /// /// On the other hand, an emoji flag character is constructed from a pair of /// Unicode scalar values, like `"\u{1F1F5}"` and `"\u{1F1F7}"`. Each of these /// scalar values, in turn, is too large to fit into a single UTF-16 or UTF-8 /// code unit. As a result, each view of the string `"🇵🇷"` reports a different /// length. /// /// let flag = "🇵🇷" /// print(flag.count) /// // Prints "1" /// print(flag.unicodeScalars.count) /// // Prints "2" /// print(flag.utf16.count) /// // Prints "4" /// print(flag.utf8.count) /// // Prints "8" /// /// To check whether a string is empty, use its `isEmpty` property instead of /// comparing the length of one of the views to `0`. Unlike with `isEmpty`, /// calculating a view's `count` property requires iterating through the /// elements of the string. /// /// Accessing String View Elements /// ============================== /// /// To find individual elements of a string, use the appropriate view for your /// task. For example, to retrieve the first word of a longer string, you can /// search the string for a space and then create a new string from a prefix /// of the string up to that point. /// /// let name = "Marie Curie" /// let firstSpace = name.index(of: " ") ?? name.endIndex /// let firstName = name[..<firstSpace] /// print(firstName) /// // Prints "Marie" /// /// Strings and their views share indices, so you can access the UTF-8 view of /// the `name` string using the same `firstSpace` index. /// /// print(Array(name.utf8[..<firstSpace])) /// // Prints "[77, 97, 114, 105, 101]" /// /// Note that an index into one view may not have an exact corresponding /// position in another view. For example, the `flag` string declared above /// comprises a single character, but is composed of eight code units when /// encoded as UTF-8. The following code creates constants for the first and /// second positions in the `flag.utf8` view. Accessing the `utf8` view with /// these indices yields the first and second code UTF-8 units. /// /// let firstCodeUnit = flag.startIndex /// let secondCodeUnit = flag.utf8.index(after: firstCodeUnit) /// // flag.utf8[firstCodeUnit] == 240 /// // flag.utf8[secondCodeUnit] == 159 /// /// When used to access the elements of the `flag` string itself, however, the /// `secondCodeUnit` index does not correspond to the position of a specific /// character. Instead of only accessing the specific UTF-8 code unit, that /// index is treated as the position of the character at the index's encoded /// offset. In the case of `secondCodeUnit`, that character is still the flag /// itself. /// /// // flag[firstCodeUnit] == "🇵🇷" /// // flag[secondCodeUnit] == "🇵🇷" /// /// If you need to validate that an index from one string's view corresponds /// with an exact position in another view, use the index's /// `samePosition(in:)` method or the `init(_:within:)` initializer. /// /// if let exactIndex = secondCodeUnit.samePosition(in: flag) { /// print(flag[exactIndex]) /// } else { /// print("No exact match for this position.") /// } /// // Prints "No exact match for this position." /// /// Performance Optimizations /// ========================= /// /// Although strings in Swift have value semantics, strings use a copy-on-write /// strategy to store their data in a buffer. This buffer can then be shared /// by different copies of a string. A string's data is only copied lazily, /// upon mutation, when more than one string instance is using the same /// buffer. Therefore, the first in any sequence of mutating operations may /// cost O(*n*) time and space. /// /// When a string's contiguous storage fills up, a new buffer must be allocated /// and data must be moved to the new storage. String buffers use an /// exponential growth strategy that makes appending to a string a constant /// time operation when averaged over many append operations. /// /// Bridging Between String and NSString /// ==================================== /// /// Any `String` instance can be bridged to `NSString` using the type-cast /// operator (`as`), and any `String` instance that originates in Objective-C /// may use an `NSString` instance as its storage. Because any arbitrary /// subclass of `NSString` can become a `String` instance, there are no /// guarantees about representation or efficiency when a `String` instance is /// backed by `NSString` storage. Because `NSString` is immutable, it is just /// as though the storage was shared by a copy. The first in any sequence of /// mutating operations causes elements to be copied into unique, contiguous /// storage which may cost O(*n*) time and space, where *n* is the length of /// the string's encoded representation (or more, if the underlying `NSString` /// has unusual performance characteristics). /// /// For more information about the Unicode terms used in this discussion, see /// the [Unicode.org glossary][glossary]. In particular, this discussion /// mentions [extended grapheme clusters][clusters], [Unicode scalar /// values][scalars], and [canonical equivalence][equivalence]. /// /// [glossary]: http://www.unicode.org/glossary/ /// [clusters]: http://www.unicode.org/glossary/#extended_grapheme_cluster /// [scalars]: http://www.unicode.org/glossary/#unicode_scalar_value /// [equivalence]: http://www.unicode.org/glossary/#canonical_equivalent @_fixed_layout public struct String { /// Creates an empty string. public init() { _core = _StringCore() } public // @testable init(_ _core: _StringCore) { self._core = _core } public // @testable var _core: _StringCore } extension String { public // @testable static func _fromWellFormedCodeUnitSequence< Encoding : Unicode.Encoding, Input : Collection >( _ encoding: Encoding.Type, input: Input ) -> String where Input.Element == Encoding.CodeUnit { return String._fromCodeUnitSequence(encoding, input: input)! } public // @testable static func _fromCodeUnitSequence< Encoding : Unicode.Encoding, Input : Collection >( _ encoding: Encoding.Type, input: Input ) -> String? where Input.Element == Encoding.CodeUnit { let (stringBufferOptional, _) = _StringBuffer.fromCodeUnits(input, encoding: encoding, repairIllFormedSequences: false) return stringBufferOptional.map { String(_storage: $0) } } public // @testable static func _fromCodeUnitSequenceWithRepair< Encoding : Unicode.Encoding, Input : Collection >( _ encoding: Encoding.Type, input: Input ) -> (String, hadError: Bool) where Input.Element == Encoding.CodeUnit { let (stringBuffer, hadError) = _StringBuffer.fromCodeUnits(input, encoding: encoding, repairIllFormedSequences: true) return (String(_storage: stringBuffer!), hadError) } } extension String : _ExpressibleByBuiltinUnicodeScalarLiteral { @effects(readonly) public // @testable init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self = String._fromWellFormedCodeUnitSequence( UTF32.self, input: CollectionOfOne(UInt32(value))) } } extension String : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral { @_inlineable @effects(readonly) @_semantics("string.makeUTF8") public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) { self = String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer( start: UnsafeMutablePointer<UTF8.CodeUnit>(start), count: Int(utf8CodeUnitCount))) } } extension String : _ExpressibleByBuiltinUTF16StringLiteral { @_inlineable @effects(readonly) @_semantics("string.makeUTF16") public init( _builtinUTF16StringLiteral start: Builtin.RawPointer, utf16CodeUnitCount: Builtin.Word ) { self = String( _StringCore( baseAddress: UnsafeMutableRawPointer(start), count: Int(utf16CodeUnitCount), elementShift: 1, hasCocoaBuffer: false, owner: nil)) } } extension String : _ExpressibleByBuiltinStringLiteral { @_inlineable @effects(readonly) @_semantics("string.makeUTF8") public init( _builtinStringLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) { if Bool(isASCII) { self = String( _StringCore( baseAddress: UnsafeMutableRawPointer(start), count: Int(utf8CodeUnitCount), elementShift: 0, hasCocoaBuffer: false, owner: nil)) } else { self = String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer( start: UnsafeMutablePointer<UTF8.CodeUnit>(start), count: Int(utf8CodeUnitCount))) } } } extension String : ExpressibleByStringLiteral { /// Creates an instance initialized to the given string value. /// /// Do not call this initializer directly. It is used by the compiler when you /// initialize a string using a string literal. For example: /// /// let nextStop = "Clark & Lake" /// /// This assignment to the `nextStop` constant calls this string literal /// initializer behind the scenes. public init(stringLiteral value: String) { self = value } } extension String : CustomDebugStringConvertible { /// A representation of the string that is suitable for debugging. public var debugDescription: String { var result = "\"" for us in self.unicodeScalars { result += us.escaped(asASCII: false) } result += "\"" return result } } extension String { /// Returns the number of code units occupied by this string /// in the given encoding. func _encodedLength< Encoding: Unicode.Encoding >(_ encoding: Encoding.Type) -> Int { var codeUnitCount = 0 self._encode(encoding, into: { _ in codeUnitCount += 1 }) return codeUnitCount } // FIXME: this function may not handle the case when a wrapped NSString // contains unpaired surrogates. Fix this before exposing this function as a // public API. But it is unclear if it is valid to have such an NSString in // the first place. If it is not, we should not be crashing in an obscure // way -- add a test for that. // Related: <rdar://problem/17340917> Please document how NSString interacts // with unpaired surrogates func _encode<Encoding: Unicode.Encoding>( _ encoding: Encoding.Type, into processCodeUnit: (Encoding.CodeUnit) -> Void ) { return _core.encode(encoding, into: processCodeUnit) } } // Support for copy-on-write extension String { /// Appends the given string to this string. /// /// The following example builds a customized greeting by using the /// `append(_:)` method: /// /// var greeting = "Hello, " /// if let name = getUserName() { /// greeting.append(name) /// } else { /// greeting.append("friend") /// } /// print(greeting) /// // Prints "Hello, friend" /// /// - Parameter other: Another string. public mutating func append(_ other: String) { _core.append(other._core) } /// Appends the given Unicode scalar to the string. /// /// - Parameter x: A Unicode scalar value. /// /// - Complexity: Appending a Unicode scalar to a string averages to O(1) /// over many additions. @available(*, unavailable, message: "Replaced by append(_: String)") public mutating func append(_ x: Unicode.Scalar) { Builtin.unreachable() } public // SPI(Foundation) init(_storage: _StringBuffer) { _core = _StringCore(_storage) } } extension String { @effects(readonly) @_semantics("string.concat") public static func + (lhs: String, rhs: String) -> String { if lhs.isEmpty { return rhs } var lhs = lhs lhs._core.append(rhs._core) return lhs } // String append public static func += (lhs: inout String, rhs: String) { if lhs.isEmpty { lhs = rhs } else { lhs._core.append(rhs._core) } } /// Constructs a `String` in `resultStorage` containing the given UTF-8. /// /// Low-level construction interface used by introspection /// implementation in the runtime library. @_inlineable @_silgen_name("swift_stringFromUTF8InRawMemory") public // COMPILER_INTRINSIC static func _fromUTF8InRawMemory( _ resultStorage: UnsafeMutablePointer<String>, start: UnsafeMutablePointer<UTF8.CodeUnit>, utf8CodeUnitCount: Int ) { resultStorage.initialize(to: String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer(start: start, count: utf8CodeUnitCount))) } } extension Sequence where Element: StringProtocol { /// Returns a new string by concatenating the elements of the sequence, /// adding the given separator between each element. /// /// The following example shows how an array of strings can be joined to a /// single, comma-separated string: /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let list = cast.joined(separator: ", ") /// print(list) /// // Prints "Vivien, Marlon, Kim, Karl" /// /// - Parameter separator: A string to insert between each of the elements /// in this sequence. The default separator is an empty string. /// - Returns: A single, concatenated string. public func joined(separator: String = "") -> String { return _joined(separator: separator) } @inline(__always) internal func _joined(separator: String = "") -> String { var result = "" // FIXME(performance): this code assumes UTF-16 in-memory representation. // It should be switched to low-level APIs. let separatorSize = separator.utf16.count let reservation = self._preprocessingPass { () -> Int in var r = 0 for chunk in self { // FIXME(performance): this code assumes UTF-16 in-memory representation. // It should be switched to low-level APIs. r += separatorSize + chunk._ephemeralString.utf16.count } return r - separatorSize } if let n = reservation { result.reserveCapacity(n) } if separatorSize == 0 { for x in self { result.append(x._ephemeralString) } return result } var iter = makeIterator() if let first = iter.next() { result.append(first._ephemeralString) while let next = iter.next() { result.append(separator) result.append(next._ephemeralString) } } return result } } // This overload is necessary because String now conforms to // BidirectionalCollection, and there are other `joined` overloads that are // considered more specific. See Flatten.swift.gyb. extension BidirectionalCollection where Iterator.Element == String { /// Returns a new string by concatenating the elements of the sequence, /// adding the given separator between each element. /// /// The following example shows how an array of strings can be joined to a /// single, comma-separated string: /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let list = cast.joined(separator: ", ") /// print(list) /// // Prints "Vivien, Marlon, Kim, Karl" /// /// - Parameter separator: A string to insert between each of the elements /// in this sequence. The default separator is an empty string. /// - Returns: A single, concatenated string. public func joined(separator: String = "") -> String { return _joined(separator: separator) } } #if _runtime(_ObjC) @_silgen_name("swift_stdlib_NSStringLowercaseString") func _stdlib_NSStringLowercaseString(_ str: AnyObject) -> _CocoaString @_silgen_name("swift_stdlib_NSStringUppercaseString") func _stdlib_NSStringUppercaseString(_ str: AnyObject) -> _CocoaString #else internal func _nativeUnicodeLowercaseString(_ str: String) -> String { var buffer = _StringBuffer( capacity: str._core.count, initialSize: str._core.count, elementWidth: 2) // Allocation of a StringBuffer requires binding the memory to the correct // encoding type. let dest = buffer.start.bindMemory( to: UTF16.CodeUnit.self, capacity: str._core.count) // Try to write it out to the same length. let z = _swift_stdlib_unicode_strToLower( dest, Int32(str._core.count), str._core.startUTF16, Int32(str._core.count)) let correctSize = Int(z) // If more space is needed, do it again with the correct buffer size. if correctSize != str._core.count { buffer = _StringBuffer( capacity: correctSize, initialSize: correctSize, elementWidth: 2) let dest = buffer.start.bindMemory( to: UTF16.CodeUnit.self, capacity: str._core.count) _swift_stdlib_unicode_strToLower( dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count)) } return String(_storage: buffer) } internal func _nativeUnicodeUppercaseString(_ str: String) -> String { var buffer = _StringBuffer( capacity: str._core.count, initialSize: str._core.count, elementWidth: 2) // Allocation of a StringBuffer requires binding the memory to the correct // encoding type. let dest = buffer.start.bindMemory( to: UTF16.CodeUnit.self, capacity: str._core.count) // Try to write it out to the same length. let z = _swift_stdlib_unicode_strToUpper( dest, Int32(str._core.count), str._core.startUTF16, Int32(str._core.count)) let correctSize = Int(z) // If more space is needed, do it again with the correct buffer size. if correctSize != str._core.count { buffer = _StringBuffer( capacity: correctSize, initialSize: correctSize, elementWidth: 2) let dest = buffer.start.bindMemory( to: UTF16.CodeUnit.self, capacity: str._core.count) _swift_stdlib_unicode_strToUpper( dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count)) } return String(_storage: buffer) } #endif // Unicode algorithms extension String { // FIXME: implement case folding without relying on Foundation. // <rdar://problem/17550602> [unicode] Implement case folding /// A "table" for which ASCII characters need to be upper cased. /// To determine which bit corresponds to which ASCII character, subtract 1 /// from the ASCII value of that character and divide by 2. The bit is set iff /// that character is a lower case character. internal var _asciiLowerCaseTable: UInt64 { @inline(__always) get { return 0b0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000 } } /// The same table for upper case characters. internal var _asciiUpperCaseTable: UInt64 { @inline(__always) get { return 0b0000_0000_0000_0000_0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000 } } /// Returns a lowercase version of the string. /// /// Here's an example of transforming a string to all lowercase letters. /// /// let cafe = "Café 🍵" /// print(cafe.lowercased()) /// // Prints "café 🍵" /// /// - Returns: A lowercase copy of the string. /// /// - Complexity: O(*n*) public func lowercased() -> String { if let asciiBuffer = self._core.asciiBuffer { let count = asciiBuffer.count let source = asciiBuffer.baseAddress! let buffer = _StringBuffer( capacity: count, initialSize: count, elementWidth: 1) let dest = buffer.start for i in 0..<count { // For each character in the string, we lookup if it should be shifted // in our ascii table, then we return 0x20 if it should, 0x0 if not. // This code is equivalent to: // switch source[i] { // case let x where (x >= 0x41 && x <= 0x5a): // dest[i] = x &+ 0x20 // case let x: // dest[i] = x // } let value = source[i] let isUpper = _asciiUpperCaseTable &>> UInt64(((value &- 1) & 0b0111_1111) &>> 1) let add = (isUpper & 0x1) &<< 5 // Since we are left with either 0x0 or 0x20, we can safely truncate to // a UInt8 and add to our ASCII value (this will not overflow numbers in // the ASCII range). dest.storeBytes(of: value &+ UInt8(truncatingIfNeeded: add), toByteOffset: i, as: UInt8.self) } return String(_storage: buffer) } #if _runtime(_ObjC) return _cocoaStringToSwiftString_NonASCII( _stdlib_NSStringLowercaseString(self._bridgeToObjectiveCImpl())) #else return _nativeUnicodeLowercaseString(self) #endif } /// Returns an uppercase version of the string. /// /// The following example transforms a string to uppercase letters: /// /// let cafe = "Café 🍵" /// print(cafe.uppercased()) /// // Prints "CAFÉ 🍵" /// /// - Returns: An uppercase copy of the string. /// /// - Complexity: O(*n*) public func uppercased() -> String { if let asciiBuffer = self._core.asciiBuffer { let count = asciiBuffer.count let source = asciiBuffer.baseAddress! let buffer = _StringBuffer( capacity: count, initialSize: count, elementWidth: 1) let dest = buffer.start for i in 0..<count { // See the comment above in lowercaseString. let value = source[i] let isLower = _asciiLowerCaseTable &>> UInt64(((value &- 1) & 0b0111_1111) &>> 1) let add = (isLower & 0x1) &<< 5 dest.storeBytes(of: value &- UInt8(truncatingIfNeeded: add), toByteOffset: i, as: UInt8.self) } return String(_storage: buffer) } #if _runtime(_ObjC) return _cocoaStringToSwiftString_NonASCII( _stdlib_NSStringUppercaseString(self._bridgeToObjectiveCImpl())) #else return _nativeUnicodeUppercaseString(self) #endif } /// Creates an instance from the description of a given /// `LosslessStringConvertible` instance. public init<T : LosslessStringConvertible>(_ value: T) { self = value.description } } extension String : CustomStringConvertible { public var description: String { return self } }
624386571da7e9b7df8513a926cf7e7a
35.666948
103
0.666199
false
false
false
false
flodolo/firefox-ios
refs/heads/main
Storage/SQL/SQLiteHistory.swift
mpl-2.0
2
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import Shared import Glean private let log = Logger.syncLogger public let TopSiteCacheSize: Int32 = 16 class NoSuchRecordError: MaybeErrorType { let guid: GUID init(guid: GUID) { self.guid = guid } var description: String { return "No such record: \(guid)." } } private var ignoredSchemes = ["about"] public func isIgnoredURL(_ url: URL) -> Bool { guard let scheme = url.scheme else { return false } if ignoredSchemes.contains(scheme) { return true } if url.host == "localhost" { return true } return false } public func isIgnoredURL(_ url: String) -> Bool { if let url = URL(string: url) { return isIgnoredURL(url) } return false } /* // Here's the Swift equivalent of the below. func simulatedFrecency(now: MicrosecondTimestamp, then: MicrosecondTimestamp, visitCount: Int) -> Double { let ageMicroseconds = (now - then) let ageDays = Double(ageMicroseconds) / 86400000000.0 // In SQL the .0 does the coercion. let f = 100 * 225 / ((ageSeconds * ageSeconds) + 225) return Double(visitCount) * max(1.0, f) } */ // The constants in these functions were arrived at by utterly unscientific experimentation. func getRemoteFrecencySQL() -> String { let visitCountExpression = "remoteVisitCount" let now = Date().toMicrosecondsSince1970() let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24 let ageDays = "((\(now) - remoteVisitDate) / \(microsecondsPerDay))" return "\(visitCountExpression) * max(1, 100 * 110 / (\(ageDays) * \(ageDays) + 110))" } func getLocalFrecencySQL() -> String { let visitCountExpression = "((2 + localVisitCount) * (2 + localVisitCount))" let now = Date().toMicrosecondsSince1970() let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24 let ageDays = "((\(now) - localVisitDate) / \(microsecondsPerDay))" return "\(visitCountExpression) * max(2, 100 * 225 / (\(ageDays) * \(ageDays) + 225))" } private func escapeFTSSearchString(_ search: String) -> String { // Remove double-quotes, split search string on whitespace // and remove any empty strings let words = search.replacingOccurrences(of: "\"", with: "").components(separatedBy: .whitespaces).filter({ !$0.isEmpty }) // If there's only one word, ensure it is longer than 2 // characters. Otherwise, form a different type of search // string to attempt to match the start of URLs. guard words.count > 1 else { guard let word = words.first else { return "" } let charThresholdForSearchAll = 2 if word.count > charThresholdForSearchAll { return "\"\(word)*\"" } else { let titlePrefix = "title: \"^" let httpPrefix = "url: \"^http://" let httpsPrefix = "url: \"^https://" return [titlePrefix, httpPrefix, httpsPrefix, httpPrefix + "www.", httpsPrefix + "www.", httpPrefix + "m.", httpsPrefix + "m."] .map({ "\($0)\(word)*\"" }) .joined(separator: " OR ") } } // Remove empty strings, wrap each word in double-quotes, append // "*", then join it all back together. For words with fewer than // three characters, anchor the search to the beginning of word // bounds by prepending "^". // Example: "foo bar a b" -> "\"foo*\"\"bar*\"\"^a*\"\"^b*\"" return words.map({ "\"\($0)*\"" }).joined() } extension SDRow { func getTimestamp(_ column: String) -> Timestamp? { return (self[column] as? NSNumber)?.uint64Value } func getBoolean(_ column: String) -> Bool { if let val = self[column] as? Int { return val != 0 } return false } } /** * The sqlite-backed implementation of the history protocol. */ open class SQLiteHistory { let database: BrowserDB let favicons: SQLiteFavicons let prefs: Prefs let clearTopSitesQuery: (String, Args?) = ("DELETE FROM cached_top_sites", nil) let notificationCenter: NotificationCenter required public init(database: BrowserDB, prefs: Prefs, notificationCenter: NotificationCenter = NotificationCenter.default) { self.database = database self.favicons = SQLiteFavicons(db: self.database) self.prefs = prefs self.notificationCenter = notificationCenter // We report the number of visits a user has // this is helpful in determining what the size of users' history visits // is like, to help guide testing the migration to the // application-services implementation and testing the // performance of the awesomebar. self.countVisits { numVisits in if let numVisits = numVisits { GleanMetrics.History.numVisits.set(Int64(numVisits)) } } } public func getSites(forURLs urls: [String]) -> Deferred<Maybe<Cursor<Site?>>> { let inExpression = urls.joined(separator: "\",\"") let sql = """ SELECT history.id AS historyID, history.url AS url, title, guid, iconID, iconURL, iconDate, iconType, iconWidth FROM view_favicons_widest, history WHERE history.id = siteID AND history.url IN (\"\(inExpression)\") """ let args: Args = [] return database.runQueryConcurrently(sql, args: args, factory: SQLiteHistory.iconHistoryColumnFactory) } public func countVisits(callback: @escaping (Int?) -> Void) { let sql = "SELECT COUNT(*) FROM visits" database.runQueryConcurrently(sql, args: nil, factory: SQLiteHistory.countAllVisitsFactory).uponQueue(.main) { result in guard result.isSuccess else { callback(nil) return } // The result of a count query is only one row if let res = result.successValue?.asArray().first { if let res = res { callback(res) return } } callback(nil) } } } private let topSitesQuery = """ SELECT cached_top_sites.*, page_metadata.provider_name \ FROM cached_top_sites \ LEFT OUTER JOIN page_metadata ON cached_top_sites.url = page_metadata.site_url \ ORDER BY frecencies DESC LIMIT (?) """ /** * The init for this will perform the heaviest part of the frecency query * and create a temporary table that can be queried quickly. Currently this accounts for * >75% of the query time. * The scope/lifetime of this object is important as the data is 'frozen' until a new instance is created. */ private struct SQLiteFrecentHistory: FrecentHistory { private let database: BrowserDB private let prefs: Prefs init(database: BrowserDB, prefs: Prefs) { self.database = database self.prefs = prefs let empty = "DELETE FROM \(MatViewAwesomebarBookmarksWithFavicons)" let insert = """ INSERT INTO \(MatViewAwesomebarBookmarksWithFavicons) SELECT guid, url, title, description, visitDate, iconID, iconURL, iconDate, iconType, iconWidth FROM \(ViewAwesomebarBookmarksWithFavicons) """ _ = database.transaction { connection in try connection.executeChange(empty) try connection.executeChange(insert) } } func getSites(matchingSearchQuery filter: String?, limit: Int) -> Deferred<Maybe<Cursor<Site>>> { let factory = SQLiteHistory.iconHistoryColumnFactory let params = FrecencyQueryParams.urlCompletion(whereURLContains: filter ?? "", groupClause: "GROUP BY historyID ") let (query, args) = getFrecencyQuery(limit: limit, params: params) return database.runQueryConcurrently(query, args: args, factory: factory) } fileprivate func updateTopSitesCacheQuery() -> (String, Args?) { let limit = Int(prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? TopSiteCacheSize) let (topSitesQuery, args) = getTopSitesQuery(historyLimit: limit) let insertQuery = """ WITH siteFrecency AS (\(topSitesQuery)) INSERT INTO cached_top_sites SELECT historyID, url, title, guid, domain_id, domain, localVisitDate, remoteVisitDate, localVisitCount, remoteVisitCount, iconID, iconURL, iconDate, iconType, iconWidth, frecencies FROM siteFrecency LEFT JOIN view_favicons_widest ON siteFrecency.historyID = view_favicons_widest.siteID """ return (insertQuery, args) } private func topSiteClauses() -> (String, String) { let whereData = "(domains.showOnTopSites IS 1) AND (domains.domain NOT LIKE 'r.%') AND (domains.domain NOT LIKE 'google.%') " let groupBy = "GROUP BY domain_id " return (whereData, groupBy) } enum FrecencyQueryParams { case urlCompletion(whereURLContains: String, groupClause: String) case topSites(groupClause: String, whereData: String) } private func getFrecencyQuery(limit: Int, params: FrecencyQueryParams) -> (String, Args?) { let groupClause: String let whereData: String? let urlFilter: String? switch params { case let .urlCompletion(filter, group): urlFilter = filter groupClause = group whereData = nil case let .topSites(group, whereArg): urlFilter = nil whereData = whereArg groupClause = group } let localFrecencySQL = getLocalFrecencySQL() let remoteFrecencySQL = getRemoteFrecencySQL() let sixMonthsInMicroseconds: UInt64 = 15_724_800_000_000 // 182 * 1000 * 1000 * 60 * 60 * 24 let sixMonthsAgo = Date().toMicrosecondsSince1970() - sixMonthsInMicroseconds let args: Args let ftsWhereClause: String let whereFragment = (whereData == nil) ? "" : " AND (\(whereData!))" if let urlFilter = urlFilter?.trimmingCharacters(in: .whitespaces), !urlFilter.isEmpty { // No deleted item has a URL, so there is no need to explicitly add that here. ftsWhereClause = " WHERE (history_fts MATCH ?)\(whereFragment)" args = [escapeFTSSearchString(urlFilter)] } else { ftsWhereClause = " WHERE (history.is_deleted = 0)\(whereFragment)" args = [] } // Innermost: grab history items and basic visit/domain metadata. let ungroupedSQL = """ SELECT history.id AS historyID, history.url AS url, history.title AS title, history.guid AS guid, domain_id, domain, coalesce(max(CASE visits.is_local WHEN 1 THEN visits.date ELSE 0 END), 0) AS localVisitDate, coalesce(max(CASE visits.is_local WHEN 0 THEN visits.date ELSE 0 END), 0) AS remoteVisitDate, coalesce(sum(visits.is_local), 0) AS localVisitCount, coalesce(sum(CASE visits.is_local WHEN 1 THEN 0 ELSE 1 END), 0) AS remoteVisitCount FROM history INNER JOIN domains ON domains.id = history.domain_id INNER JOIN visits ON visits.siteID = history.id INNER JOIN history_fts ON history_fts.rowid = history.rowid \(ftsWhereClause) GROUP BY historyID """ // Next: limit to only those that have been visited at all within the last six months. // (Don't do that in the innermost: we want to get the full count, even if some visits are older.) // Discard all but the 1000 most frecent. // Compute and return the frecency for all 1000 URLs. let frecenciedSQL = """ SELECT *, (\(localFrecencySQL) + \(remoteFrecencySQL)) AS frecency FROM (\(ungroupedSQL)) WHERE ( -- Eliminate dead rows from coalescing. ((localVisitCount > 0) OR (remoteVisitCount > 0)) AND -- Exclude really old items. ((localVisitDate > \(sixMonthsAgo)) OR (remoteVisitDate > \(sixMonthsAgo))) ) ORDER BY frecency DESC -- Don't even look at a huge set. This avoids work. LIMIT 1000 """ // Next: merge by domain and select the URL with the max frecency of a domain, ordering by that sum frecency and reducing to a (typically much lower) limit. // NOTE: When using GROUP BY we need to be explicit about which URL to use when grouping. By using "max(frecency)" the result row // for that domain will contain the projected URL corresponding to the history item with the max frecency, https://sqlite.org/lang_select.html#resultset // This is the behavior we want in order to ensure that the most popular URL for a domain is used for the top sites tile. // TODO: make is_bookmarked here accurate by joining against ViewAllBookmarks. // TODO: ensure that the same URL doesn't appear twice in the list, either from duplicate // bookmarks or from being in both bookmarks and history. let historySQL = """ SELECT historyID, url, title, guid, domain_id, domain, max(localVisitDate) AS localVisitDate, max(remoteVisitDate) AS remoteVisitDate, sum(localVisitCount) AS localVisitCount, sum(remoteVisitCount) AS remoteVisitCount, max(frecency) AS maxFrecency, sum(frecency) AS frecencies, 0 AS is_bookmarked FROM (\(frecenciedSQL)) \(groupClause) ORDER BY frecencies DESC LIMIT \(limit) """ let allSQL = """ SELECT * FROM (\(historySQL)) AS hb LEFT OUTER JOIN view_favicons_widest ON view_favicons_widest.siteID = hb.historyID ORDER BY is_bookmarked DESC, frecencies DESC """ return (allSQL, args) } private func getTopSitesQuery(historyLimit: Int) -> (String, Args?) { let localFrecencySQL = getLocalFrecencySQL() let remoteFrecencySQL = getRemoteFrecencySQL() // Innermost: grab history items and basic visit/domain metadata. let ungroupedSQL = """ SELECT history.id AS historyID, history.url AS url, history.title AS title, history.guid AS guid, domain_id, domain, coalesce(max(CASE visits.is_local WHEN 1 THEN visits.date ELSE 0 END), 0) AS localVisitDate, coalesce(max(CASE visits.is_local WHEN 0 THEN visits.date ELSE 0 END), 0) AS remoteVisitDate, coalesce(sum(visits.is_local), 0) AS localVisitCount, coalesce(sum(CASE visits.is_local WHEN 1 THEN 0 ELSE 1 END), 0) AS remoteVisitCount FROM history INNER JOIN ( SELECT siteID FROM ( SELECT COUNT(rowid) AS visitCount, siteID FROM visits GROUP BY siteID ORDER BY visitCount DESC LIMIT 5000 ) UNION ALL SELECT siteID FROM ( SELECT siteID FROM visits GROUP BY siteID ORDER BY max(date) DESC LIMIT 1000 ) ) AS groupedVisits ON groupedVisits.siteID = history.id INNER JOIN domains ON domains.id = history.domain_id INNER JOIN visits ON visits.siteID = history.id WHERE (history.is_deleted = 0) AND ((domains.showOnTopSites IS 1) AND (domains.domain NOT LIKE 'r.%') AND (domains.domain NOT LIKE 'google.%')) AND (history.url LIKE 'http%') GROUP BY historyID """ let frecenciedSQL = """ SELECT *, (\(localFrecencySQL) + \(remoteFrecencySQL)) AS frecency FROM (\(ungroupedSQL)) """ let historySQL = """ SELECT historyID, url, title, guid, domain_id, domain, max(localVisitDate) AS localVisitDate, max(remoteVisitDate) AS remoteVisitDate, sum(localVisitCount) AS localVisitCount, sum(remoteVisitCount) AS remoteVisitCount, max(frecency) AS maxFrecency, sum(frecency) AS frecencies, 0 AS is_bookmarked FROM (\(frecenciedSQL)) GROUP BY domain_id ORDER BY frecencies DESC LIMIT \(historyLimit) """ return (historySQL, nil) } } extension SQLiteHistory: BrowserHistory { public func removeSiteFromTopSites(_ site: Site) -> Success { if let host = (site.url as String).asURL?.normalizedHost { return self.removeHostFromTopSites(host) } return deferMaybe(DatabaseError(description: "Invalid url for site \(site.url)")) } public func removeFromPinnedTopSites(_ site: Site) -> Success { guard let host = (site.url as String).asURL?.normalizedHost else { return deferMaybe(DatabaseError(description: "Invalid url for site \(site.url)")) } notificationCenter.post(name: .TopSitesUpdated, object: self) // do a fuzzy delete so dupes can be removed let query: (String, Args?) = ("DELETE FROM pinned_top_sites where domain = ?", [host]) return database.run([query]) >>== { return self.database.run([("UPDATE domains SET showOnTopSites = 1 WHERE domain = ?", [host])]) } } public func isPinnedTopSite(_ url: String) -> Deferred<Maybe<Bool>> { let sql = """ SELECT * FROM pinned_top_sites WHERE url = ? LIMIT 1 """ let args: Args = [url] return self.database.queryReturnsResults(sql, args: args) } public func getPinnedTopSites() -> Deferred<Maybe<Cursor<Site>>> { let sql = """ SELECT * FROM pinned_top_sites LEFT OUTER JOIN view_favicons_widest ON historyID = view_favicons_widest.siteID ORDER BY pinDate DESC """ return database.runQueryConcurrently(sql, args: [], factory: SQLiteHistory.iconHistoryMetadataColumnFactory) } public func addPinnedTopSite(_ site: Site) -> Success { // needs test let now = Date.now() guard let guid = site.guid, let host = (site.url as String).asURL?.normalizedHost else { return deferMaybe(DatabaseError(description: "Invalid site \(site.url)")) } notificationCenter.post(name: .TopSitesUpdated, object: self) let args: Args = [site.url, now, site.title, site.id, guid, host] let arglist = BrowserDB.varlist(args.count) // Prevent the pinned site from being used in topsite calculations // We dont have to worry about this when removing a pin because the assumption is that a user probably doesnt want it being recommended as a topsite either return self.removeHostFromTopSites(host) >>== { return self.database.run([("INSERT OR REPLACE INTO pinned_top_sites (url, pinDate, title, historyID, guid, domain) VALUES \(arglist)", args)]) } } public func removeHostFromTopSites(_ host: String) -> Success { return database.run([("UPDATE domains SET showOnTopSites = 0 WHERE domain = ?", [host])]) } public func removeHistoryForURL(_ url: String) -> Success { let visitArgs: Args = [url] let deleteVisits = "DELETE FROM visits WHERE siteID = (SELECT id FROM history WHERE url = ?)" let markArgs: Args = [Date.nowNumber(), url] let markDeleted = "UPDATE history SET url = NULL, is_deleted = 1, title = '', should_upload = 1, local_modified = ? WHERE url = ?" return database.run([ (sql: deleteVisits, args: visitArgs), (sql: markDeleted, args: markArgs), favicons.getCleanupFaviconsQuery(), favicons.getCleanupFaviconSiteURLsQuery() ]) } public func removeHistoryFromDate(_ date: Date) -> Success { let visitTimestamp = date.toMicrosecondsSince1970() let historyRemoval = """ WITH deletionIds as (SELECT history.id from history INNER JOIN visits on history.id = visits.siteID WHERE visits.date > ?) UPDATE history SET url = NULL, is_deleted=1, title = '', should_upload = 1, local_modified = ? WHERE history.id in deletionIds """ let historyRemovalArgs: Args = [visitTimestamp, Date.nowNumber()] let visitRemoval = "DELETE FROM visits WHERE visits.date > ?" let visitRemovalArgs: Args = [visitTimestamp] return database.run([ (sql: historyRemoval, args: historyRemovalArgs), (sql: visitRemoval, args: visitRemovalArgs), favicons.getCleanupFaviconsQuery(), favicons.getCleanupFaviconSiteURLsQuery() ]) } // Note: clearing history isn't really a sane concept in the presence of Sync. // This method should be split to do something else. // Bug 1162778. public func clearHistory() -> Success { return self.database.run([ ("DELETE FROM visits", nil), ("DELETE FROM history", nil), ("DELETE FROM domains", nil), ("DELETE FROM page_metadata", nil), ("DELETE FROM favicon_site_urls", nil), ("DELETE FROM favicons", nil), ]) // We've probably deleted a lot of stuff. Vacuum now to recover the space. >>> effect({ self.database.vacuum() }) } func recordVisitedSite(_ site: Site) -> Success { // Don't store visits to sites with about: protocols if isIgnoredURL(site.url as String) { return deferMaybe(IgnoredSiteError()) } notificationCenter.post(name: .TopSitesUpdated, object: self) return database.withConnection { conn -> Void in let now = Date.now() if self.updateSite(site, atTime: now, withConnection: conn) > 0 { return } // Insert instead. if self.insertSite(site, atTime: now, withConnection: conn) > 0 { return } let err = DatabaseError(description: "Unable to update or insert site; Invalid key returned") log.error("recordVisitedSite encountered an error: \(err.localizedDescription)") throw err } } func updateSite(_ site: Site, atTime time: Timestamp, withConnection conn: SQLiteDBConnection) -> Int { // We know we're adding a new visit, so we'll need to upload this record. // If we ever switch to per-visit change flags, this should turn into a CASE statement like // CASE WHEN title IS ? THEN max(should_upload, 1) ELSE should_upload END // so that we don't flag this as changed unless the title changed. // // Note that we will never match against a deleted item, because deleted items have no URL, // so we don't need to unset is_deleted here. guard let host = (site.url as String).asURL?.normalizedHost else { return 0 } let update = "UPDATE history SET title = ?, local_modified = ?, should_upload = 1, domain_id = (SELECT id FROM domains where domain = ?) WHERE url = ?" let updateArgs: Args? = [site.title, time, host, site.url] if Logger.logPII { log.debug("Setting title to \(site.title) for URL \(site.url)") } do { try conn.executeChange(update, withArgs: updateArgs) return conn.numberOfRowsModified } catch let error as NSError { log.warning("Update failed with error: \(error.localizedDescription)") return 0 } } fileprivate func insertSite(_ site: Site, atTime time: Timestamp, withConnection conn: SQLiteDBConnection) -> Int { if let host = (site.url as String).asURL?.normalizedHost { do { try conn.executeChange("INSERT OR IGNORE INTO domains (domain) VALUES (?)", withArgs: [host]) } catch let error as NSError { log.warning("Domain insertion failed with \(error.localizedDescription)") return 0 } let insert = """ INSERT INTO history ( guid, url, title, local_modified, is_deleted, should_upload, domain_id ) SELECT ?, ?, ?, ?, 0, 1, id FROM domains WHERE domain = ? """ let insertArgs: Args? = [site.guid ?? Bytes.generateGUID(), site.url, site.title, time, host] do { try conn.executeChange(insert, withArgs: insertArgs) } catch let error as NSError { log.warning("Site insertion failed with \(error.localizedDescription)") return 0 } return 1 } if Logger.logPII { log.warning("Invalid URL \(site.url). Not stored in history.") } return 0 } // TODO: thread siteID into this to avoid the need to do the lookup. func addLocalVisitForExistingSite(_ visit: SiteVisit) -> Success { return database.withConnection { conn -> Void in // INSERT OR IGNORE because we *might* have a clock error that causes a timestamp // collision with an existing visit, and it would really suck to error out for that reason. let insert = """ INSERT OR IGNORE INTO visits ( siteID, date, type, is_local ) VALUES ( (SELECT id FROM history WHERE url = ?), ?, ?, 1 ) """ let realDate = visit.date let insertArgs: Args? = [visit.site.url, realDate, visit.type.rawValue] try conn.executeChange(insert, withArgs: insertArgs) } } public func addLocalVisit(_ visit: SiteVisit) -> Success { return recordVisitedSite(visit.site) >>> { self.addLocalVisitForExistingSite(visit) } } public func getFrecentHistory() -> FrecentHistory { return SQLiteFrecentHistory(database: database, prefs: prefs) } public func getHistory(matching searchTerm: String, limit: Int, offset: Int, completion: @escaping ([Site]) -> Void) { let query = """ SELECT hist.* FROM history hist INNER JOIN history_fts historyFTS ON historyFTS.rowid = hist.rowid WHERE historyFTS.title LIKE ? OR historyFTS.url LIKE ? ORDER BY local_modified DESC LIMIT \(limit) OFFSET \(offset); """ let args: Args = ["%\(searchTerm)%", "%\(searchTerm)%"] database.runQueryConcurrently(query, args: args, factory: SQLiteHistory.basicHistoryColumnFactory).uponQueue(.main) { result in guard result.isSuccess else { completion([Site]()) return } completion(result.successValue?.asArray() ?? [Site]()) } } public func getTopSitesWithLimit(_ limit: Int) -> Deferred<Maybe<Cursor<Site>>> { return self.database.runQueryConcurrently(topSitesQuery, args: [limit], factory: SQLiteHistory.iconHistoryMetadataColumnFactory) } public func setTopSitesNeedsInvalidation() { prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid) } public func setTopSitesCacheSize(_ size: Int32) { let oldValue = prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? 0 if oldValue != size { prefs.setInt(size, forKey: PrefsKeys.KeyTopSitesCacheSize) setTopSitesNeedsInvalidation() } } public func refreshTopSitesQuery() -> [(String, Args?)] { return [clearTopSitesQuery, getFrecentHistory().updateTopSitesCacheQuery()] } public func clearTopSitesCache() -> Success { return self.database.run([clearTopSitesQuery]) >>> { self.prefs.removeObjectForKey(PrefsKeys.KeyTopSitesCacheIsValid) return succeed() } } public func getSitesByLastVisit(limit: Int, offset: Int) -> Deferred<Maybe<Cursor<Site>>> { let sql = """ SELECT history.id AS historyID, history.url, title, guid, domain_id, domain, coalesce(max(CASE visits.is_local WHEN 1 THEN visits.date ELSE 0 END), 0) AS localVisitDate, coalesce(max(CASE visits.is_local WHEN 0 THEN visits.date ELSE 0 END), 0) AS remoteVisitDate, coalesce(count(visits.is_local), 0) AS visitCount , iconID, iconURL, iconDate, iconType, iconWidth FROM history INNER JOIN ( SELECT siteID, max(date) AS latestVisitDate FROM visits GROUP BY siteID ORDER BY latestVisitDate DESC LIMIT \(limit) OFFSET \(offset) ) AS latestVisits ON latestVisits.siteID = history.id INNER JOIN domains ON domains.id = history.domain_id INNER JOIN visits ON visits.siteID = history.id LEFT OUTER JOIN view_favicons_widest ON view_favicons_widest.siteID = history.id WHERE (history.is_deleted = 0) GROUP BY history.id ORDER BY latestVisits.latestVisitDate DESC """ return database.runQueryConcurrently(sql, args: nil, factory: SQLiteHistory.iconHistoryColumnFactory) } } extension SQLiteHistory: SyncableHistory { /** * TODO: * When we replace an existing row, we want to create a deleted row with the old * GUID and switch the new one in -- if the old record has escaped to a Sync server, * we want to delete it so that we don't have two records with the same URL on the server. * We will know if it's been uploaded because it'll have a server_modified time. */ public func ensurePlaceWithURL(_ url: String, hasGUID guid: GUID) -> Success { let args: Args = [guid, url, guid] // The additional IS NOT is to ensure that we don't do a write for no reason. return database.run("UPDATE history SET guid = ? WHERE url = ? AND guid IS NOT ?", withArgs: args) } public func deleteByGUID(_ guid: GUID, deletedAt: Timestamp) -> Success { let args: Args = [guid] // This relies on ON DELETE CASCADE to remove visits. return database.run("DELETE FROM history WHERE guid = ?", withArgs: args) } // Fails on non-existence. fileprivate func getSiteIDForGUID(_ guid: GUID) -> Deferred<Maybe<Int>> { let args: Args = [guid] let query = "SELECT id FROM history WHERE guid = ?" let factory: (SDRow) -> Int = { return $0["id"] as! Int } return database.runQueryConcurrently(query, args: args, factory: factory) >>== { cursor in let cursorCount = cursor.count if cursorCount == 0 { return deferMaybe(NoSuchRecordError(guid: guid)) } return deferMaybe(cursor[0]!) } } public func storeRemoteVisits(_ visits: [Visit], forGUID guid: GUID) -> Success { return self.getSiteIDForGUID(guid) >>== { (siteID: Int) -> Success in let visitArgs = visits.map { (visit: Visit) -> Args in let realDate = visit.date let isLocal = 0 let args: Args = [siteID, realDate, visit.type.rawValue, isLocal] return args } // Magic happens here. The INSERT OR IGNORE relies on the multi-column uniqueness // constraint on `visits`: we allow only one row for (siteID, date, type), so if a // local visit already exists, this silently keeps it. End result? Any new remote // visits are added with only one query, keeping any existing rows. return self.database.bulkInsert(TableVisits, op: .InsertOrIgnore, columns: ["siteID", "date", "type", "is_local"], values: visitArgs) } } fileprivate struct HistoryMetadata { let id: Int let serverModified: Timestamp? let localModified: Timestamp? let isDeleted: Bool let shouldUpload: Bool let title: String } fileprivate func metadataForGUID(_ guid: GUID) -> Deferred<Maybe<HistoryMetadata?>> { let select = "SELECT id, server_modified, local_modified, is_deleted, should_upload, title FROM history WHERE guid = ?" let args: Args = [guid] let factory = { (row: SDRow) -> HistoryMetadata in return HistoryMetadata( id: row["id"] as! Int, serverModified: row.getTimestamp("server_modified"), localModified: row.getTimestamp("local_modified"), isDeleted: row.getBoolean("is_deleted"), shouldUpload: row.getBoolean("should_upload"), title: row["title"] as! String ) } return database.runQueryConcurrently(select, args: args, factory: factory) >>== { cursor in return deferMaybe(cursor[0]) } } public func insertOrUpdatePlace(_ place: Place, modified: Timestamp) -> Deferred<Maybe<GUID>> { // One of these things will be true here. // 0. The item is new. // (a) We have a local place with the same URL but a different GUID. // (b) We have never visited this place locally. // In either case, reconcile and proceed. // 1. The remote place is not modified when compared to our mirror of it. This // can occur when we redownload after a partial failure. // (a) And it's not modified locally, either. Nothing to do. Ideally we // will short-circuit so we don't need to update visits. (TODO) // (b) It's modified locally. Don't overwrite anything; let the upload happen. // 2. The remote place is modified (either title or visits). // (a) And it's not locally modified. Update the local entry. // (b) And it's locally modified. Preserve the title of whichever was modified last. // N.B., this is the only instance where we compare two timestamps to see // which one wins. // We use this throughout. let serverModified = modified // Check to see if our modified time is unchanged, if the record exists locally, etc. let insertWithMetadata = { (metadata: HistoryMetadata?) -> Deferred<Maybe<GUID>> in if let metadata = metadata { // The item exists locally (perhaps originally with a different GUID). if metadata.serverModified == modified { log.verbose("History item \(place.guid) is unchanged; skipping insert-or-update.") return deferMaybe(place.guid) } // Otherwise, the server record must have changed since we last saw it. if metadata.shouldUpload { // Uh oh, it changed locally. // This might well just be a visit change, but we can't tell. Usually this conflict is harmless. log.debug("Warning: history item \(place.guid) changed both locally and remotely. Comparing timestamps from different clocks!") if let localModified = metadata.localModified, localModified > modified { log.debug("Local changes overriding remote.") // Update server modified time only. (Though it'll be overwritten again after a successful upload.) let update = "UPDATE history SET server_modified = ? WHERE id = ?" let args: Args = [serverModified, metadata.id] return self.database.run(update, withArgs: args) >>> always(place.guid) } log.verbose("Remote changes overriding local.") // Fall through. } // The record didn't change locally. Update it. log.verbose("Updating local history item for guid \(place.guid).") let update = "UPDATE history SET title = ?, server_modified = ?, is_deleted = 0 WHERE id = ?" let args: Args = [place.title, serverModified, metadata.id] return self.database.run(update, withArgs: args) >>> always(place.guid) } // The record doesn't exist locally. Insert it. log.verbose("Inserting remote history item for guid \(place.guid).") if let host = place.url.asURL?.normalizedHost { if Logger.logPII { log.debug("Inserting: \(place.url).") } let insertDomain = "INSERT OR IGNORE INTO domains (domain) VALUES (?)" let insertHistory = """ INSERT INTO history ( guid, url, title, server_modified, is_deleted, should_upload, domain_id ) SELECT ?, ?, ?, ?, 0, 0, id FROM domains WHERE domain = ? """ return self.database.run([ (insertDomain, [host]), (insertHistory, [place.guid, place.url, place.title, serverModified, host]) ]) >>> always(place.guid) } else { // This is a URL with no domain. Insert it directly. if Logger.logPII { log.debug("Inserting: \(place.url) with no domain.") } let insertHistory = """ INSERT INTO history ( guid, url, title, server_modified, is_deleted, should_upload, domain_id ) VALUES (?, ?, ?, ?, 0, 0, NULL) """ return self.database.run([ (insertHistory, [place.guid, place.url, place.title, serverModified]) ]) >>> always(place.guid) } } // Make sure that we only need to compare GUIDs by pre-merging on URL. return self.ensurePlaceWithURL(place.url, hasGUID: place.guid) >>> { self.metadataForGUID(place.guid) >>== insertWithMetadata } } public func getDeletedHistoryToUpload() -> Deferred<Maybe<[GUID]>> { // Use the partial index on should_upload to make this nice and quick. let sql = "SELECT guid FROM history WHERE history.should_upload = 1 AND history.is_deleted = 1" let f: (SDRow) -> String = { $0["guid"] as! String } return self.database.runQuery(sql, args: nil, factory: f) >>== { deferMaybe($0.asArray()) } } public func getModifiedHistoryToUpload() -> Deferred<Maybe<[(Place, [Visit])]>> { // What we want to do: find all history items that are flagged for upload, then find a number of recent visits for each item. // This was originally all in a single SQL query but was seperated into two to save some memory when returning back the cursor. return getModifiedHistory(limit: 1000) >>== { self.attachVisitsTo(places: $0, visitLimit: 20) } } private func getModifiedHistory(limit: Int) -> Deferred<Maybe<[Int: Place]>> { let sql = """ SELECT id, guid, url, title FROM history WHERE should_upload = 1 AND NOT is_deleted = 1 ORDER BY id LIMIT ? """ var places = [Int: Place]() let placeFactory: (SDRow) -> Void = { row in let id = row["id"] as! Int let guid = row["guid"] as! String let url = row["url"] as! String let title = row["title"] as! String places[id] = Place(guid: guid, url: url, title: title) } let args: Args = [limit] return database.runQueryConcurrently(sql, args: args, factory: placeFactory) >>> { deferMaybe(places) } } private func attachVisitsTo(places: [Int: Place], visitLimit: Int) -> Deferred<Maybe<[(Place, [Visit])]>> { // A difficulty here: we don't want to fetch *all* visits, only some number of the most recent. // (It's not enough to only get new ones, because the server record should contain more.) // // That's the greatest-N-per-group problem. We used to do this in SQL, joining // the visits table to a subselect of visits table, however, ran into OOM issues (Bug 1417034) // // Now, we want a more dumb approach with no joins in SQL and doing group-by-site and limit-to-N in swift. // // We do this in a single query, rather than the N+1 that desktop takes. // // We then need to flatten the cursor. We do that by collecting // places as a side-effect of the factory, producing visits as a result, and merging in memory. // Turn our lazy collection of integers into a comma-seperated string for the IN clause. let historyIDs = Array(places.keys) let sql = """ SELECT siteID, date AS visitDate, type AS visitType FROM visits WHERE siteID IN (\(historyIDs.map(String.init).joined(separator: ","))) ORDER BY siteID DESC, date DESC """ // We want to get a tuple Visit and Place here. We can either have an explicit tuple factory // or we use an identity function, and make do without creating extra data structures. // Since we have a known Out Of Memory issue here, let's avoid extra data structures. let rowIdentity: (SDRow) -> SDRow = { $0 } // We'll need to runQueryUnsafe so we get a LiveSQLiteCursor, i.e. we don't get the cursor // contents into memory all at once. return database.runQueryUnsafe(sql, args: nil, factory: rowIdentity) { (cursor: Cursor<SDRow>) -> [Int: [Visit]] in // Accumulate a mapping of site IDs to list of visits. Each list should be shorter than visitLimit. // Seed our accumulator with empty lists since we already know which IDs we will be fetching. var visits = [Int: [Visit]]() historyIDs.forEach { visits[$0] = [] } // We need to iterate through these explicitly, without relying on the // factory. for row in cursor.makeIterator() { guard let row = row, cursor.status == .success else { throw NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: cursor.statusMessage]) } guard let id = row["siteID"] as? Int, let existingCount = visits[id]?.count, existingCount < visitLimit else { continue } guard let date = row.getTimestamp("visitDate"), let visitType = row["visitType"] as? Int, let type = VisitType(rawValue: visitType) else { continue } let visit = Visit(date: date, type: type) // Append the visits in descending date order, so we only get the // most recent top N. visits[id]?.append(visit) } return visits } >>== { visits in // Join up the places map we received as input with our visits map. let placesAndVisits: [(Place, [Visit])] = places.compactMap { id, place in guard let visitsList = visits[id], !visitsList.isEmpty else { return nil } return (place, visitsList) } let recentVisitCount = placesAndVisits.reduce(0) { $0 + $1.1.count } log.info("Attaching \(placesAndVisits.count) places to \(recentVisitCount) most recent visits") return deferMaybe(placesAndVisits) } } public func markAsDeleted(_ guids: [GUID]) -> Success { if guids.isEmpty { return succeed() } log.debug("Wiping \(guids.count) deleted GUIDs.") return self.database.run(chunk(guids, by: BrowserDB.MaxVariableNumber).compactMap(markAsDeletedStatementForGUIDs)) } fileprivate func markAsDeletedStatementForGUIDs(_ guids: ArraySlice<String>) -> (String, Args?) { // We deliberately don't limit this to records marked as should_upload, just // in case a coding error leaves records with is_deleted=1 but not flagged for // upload -- this will catch those and throw them away. let inClause = BrowserDB.varlist(guids.count) let sql = "DELETE FROM history WHERE is_deleted = 1 AND guid IN \(inClause)" let args: Args = guids.map { $0 } return (sql, args) } public func markAsSynchronized(_ guids: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> { if guids.isEmpty { return deferMaybe(modified) } log.debug("Marking \(guids.count) GUIDs as synchronized. Returning timestamp \(modified).") return self.database.run(chunk(guids, by: BrowserDB.MaxVariableNumber).compactMap { chunk in return markAsSynchronizedStatementForGUIDs(chunk, modified: modified) }) >>> always(modified) } fileprivate func markAsSynchronizedStatementForGUIDs(_ guids: ArraySlice<String>, modified: Timestamp) -> (String, Args?) { let inClause = BrowserDB.varlist(guids.count) let sql = """ UPDATE history SET should_upload = 0, server_modified = \(modified) WHERE guid IN \(inClause) """ let args: Args = guids.map { $0 } return (sql, args) } public func doneApplyingRecordsAfterDownload() -> Success { self.database.checkpoint() return succeed() } public func doneUpdatingMetadataAfterUpload() -> Success { self.database.checkpoint() return succeed() } } extension SQLiteHistory { // Returns a deferred `true` if there are rows in the DB that have a server_modified time. // Because we clear this when we reset or remove the account, and never set server_modified // without syncing, the presence of matching rows directly indicates that a deletion // would be synced to the server. public func hasSyncedHistory() -> Deferred<Maybe<Bool>> { return self.database.queryReturnsResults("SELECT 1 FROM history WHERE server_modified IS NOT NULL LIMIT 1") } } extension SQLiteHistory: ResettableSyncStorage { // We don't drop deletions when we reset -- we might need to upload a deleted item // that never made it to the server. public func resetClient() -> Success { let flag = "UPDATE history SET should_upload = 1, server_modified = NULL" return self.database.run(flag) } } extension SQLiteHistory: AccountRemovalDelegate { public func onRemovedAccount() -> Success { log.info("Clearing history metadata and deleted items after account removal.") let discard = "DELETE FROM history WHERE is_deleted = 1" return self.database.run(discard) >>> self.resetClient } }
f25bfe2332f5183805149680a3643398
42.506751
186
0.593884
false
false
false
false
filograno/Moya
refs/heads/master
Source/RxSwift/Moya+RxSwift.swift
mit
1
import Foundation import RxSwift /// Subclass of MoyaProvider that returns Observable instances when requests are made. Much better than using completion closures. open class RxMoyaProvider<Target>: MoyaProvider<Target> where Target: TargetType { /// Initializes a reactive provider. override public init(endpointClosure: @escaping EndpointClosure = MoyaProvider.DefaultEndpointMapping, requestClosure: @escaping RequestClosure = MoyaProvider.DefaultRequestMapping, stubClosure: @escaping StubClosure = MoyaProvider.NeverStub, manager: Manager = RxMoyaProvider<Target>.DefaultAlamofireManager(), plugins: [PluginType] = [], trackInflights: Bool = false) { super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins, trackInflights: trackInflights) } /// Designated request-making method. open func request(_ token: Target) -> Observable<Response> { // Creates an observable that starts a request each time it's subscribed to. return Observable.create { [weak self] observer in let cancellableToken = self?.request(token) { result in switch result { case let .success(response): observer.onNext(response) observer.onCompleted() case let .failure(error): observer.onError(error) } } return Disposables.create { cancellableToken?.cancel() } } } } public extension RxMoyaProvider { public func requestWithProgress(_ token: Target) -> Observable<ProgressResponse> { let progressBlock = { (observer: AnyObserver) -> (ProgressResponse) -> Void in return { (progress: ProgressResponse) in observer.onNext(progress) } } let response: Observable<ProgressResponse> = Observable.create { [weak self] observer in let cancellableToken = self?.request(token, queue: nil, progress: progressBlock(observer)) { result in switch result { case let .success(response): observer.onNext(ProgressResponse(response: response)) observer.onCompleted() case let .failure(error): observer.onError(error) } } return Disposables.create { cancellableToken?.cancel() } } // Accumulate all progress and combine them when the result comes return response.scan(ProgressResponse()) { (last, progress) in let progressObject = progress.progressObject ?? last.progressObject let response = progress.response ?? last.response return ProgressResponse(progress: progressObject, response: response) } } }
cf77ddc2903ec600a6a74d798090ec36
41.956522
182
0.626518
false
false
false
false
mcxiaoke/learning-ios
refs/heads/master
ios_programming_4th/Homepwner-ch18/Homepwner/DetailViewController.swift
apache-2.0
1
// // DetailViewController.swift // Homepwner // // Created by Xiaoke Zhang on 2017/8/17. // Copyright © 2017年 Xiaoke Zhang. All rights reserved. // /** autolayout debug https://medium.com/ios-os-x-development/auto-layout-debugging-in-swift-93bcd21a4abf for objc: po [[UIWindow keyWindow] _autolayoutTrace] for swift: expr -l objc++ -O -- [[UIWindow keyWindow] _autolayoutTrace] **/ import UIKit class DetailViewController: UIViewController { @IBOutlet weak var nameField: UITextField! @IBOutlet weak var serialField: UITextField! @IBOutlet weak var valueField: UITextField! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var toolBar: UIToolbar! @IBOutlet weak var cameraButton: UIBarButtonItem! @IBOutlet weak var removeButton: UIBarButtonItem! var dismissBlock: (() -> Void)? var createMode = false override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .all } var item:Item? { didSet { self.navigationItem.title = item?.itemName } } func cancelAndBack() { print("doneAndBack") if let item = self.item { ItemStore.shared.allItems.remove(object: item) } self.view.endEditing(true) self.presentingViewController?.dismiss(animated: true, completion: self.dismissBlock) } func doneAndBack() { print("doneAndBack") saveEdit() self.view.endEditing(true) self.presentingViewController?.dismiss(animated: true, completion: self.dismissBlock) } func saveEdit() { if let newItem = self.item { newItem.itemName = nameField.text ?? "" newItem.serialNumber = serialField.text ?? "" newItem.valueInDollars = Int(valueField.text ?? "") ?? 0 print("saveEdit \(newItem)") } } func onOrientationChange() { if UIDevice.current.userInterfaceIdiom == .pad { return } print("onOrientationChange") if UIDevice.current.orientation.isLandscape { self.imageView.isHidden = true self.cameraButton.isEnabled = false } else { self.imageView.isHidden = false self.cameraButton.isEnabled = true } } func bindViews() { if let item = self.item { print("bindViews \(item)") nameField.text = item.itemName serialField.text = item.serialNumber valueField.text = String(format:"%d", item.valueInDollars) let df = DateFormatter() df.dateStyle = .medium df.timeStyle = .none dateLabel.text = df.string(from: item.dateCreated) self.imageView.image = ImageStore.shared.image(forKey: item.key) } } func bindImage() { print("bindImage") if let item = self.item { self.imageView.image = ImageStore.shared.image(forKey: item.key) } } override func viewDidLoad() { super.viewDidLoad() if self.createMode { let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneAndBack)) let cancel = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelAndBack)) self.navigationItem.rightBarButtonItem = done self.navigationItem.leftBarButtonItem = cancel } else { let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneAndBack)) self.navigationItem.rightBarButtonItem = done } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("viewWillAppear") self.onOrientationChange() self.bindViews() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("viewWillDisappear") self.view.endEditing(true) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { self.onOrientationChange() } // MARK: IBActions @IBAction func backgroundTapped(_ sender: Any) { self.view.endEditing(true) } @IBAction func takePicture(_ sender: Any) { saveEdit() let imagePicker = UIImagePickerController() if UIImagePickerController.isSourceTypeAvailable(.camera) { imagePicker.sourceType = .camera } else { imagePicker.sourceType = .photoLibrary } imagePicker.allowsEditing = true imagePicker.delegate = self if UIDevice.current.userInterfaceIdiom == .pad { if imagePicker.sourceType == .photoLibrary { imagePicker.modalPresentationStyle = .popover } if let pop = imagePicker.popoverPresentationController { print("image picker, using popover") pop.barButtonItem = self.cameraButton pop.permittedArrowDirections = .any } } self.present(imagePicker, animated: true, completion: nil) } @IBAction func removePicture(_ sender: Any) { saveEdit() if let item = self.item { ImageStore.shared.removeImage(forKey: item.key) self.imageView.image = nil } } } extension DetailViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // print("Picked image: \(info)") if let image = info[UIImagePickerControllerEditedImage] as? UIImage, let item = self.item { print("Picked edited image: \(image)") ImageStore.shared.setImage(image: image, forKey: item.key) } else if let image = info[UIImagePickerControllerOriginalImage] as? UIImage, let item = self.item { print("Picked original image: \(image)") ImageStore.shared.setImage(image: image, forKey: item.key) } picker.dismiss(animated: true) { [weak self] in self?.bindImage() } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true) { [weak self] in self?.bindImage() } } } extension DetailViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField.returnKeyType == .done { textField.resignFirstResponder() return true } else if textField.returnKeyType == .next { // impl next action if textField.tag == 1 { textField.resignFirstResponder() self.view.viewWithTag(2)?.becomeFirstResponder() } else if textField.tag == 2 { textField.resignFirstResponder() self.view.viewWithTag(3)?.becomeFirstResponder() } return false } else { return false } } }
44e44dac4445df151e5c89031c90b4b4
32.568807
119
0.611233
false
false
false
false
jindulys/ChainPageCollectionView
refs/heads/master
Sources/EdgeCardLayout.swift
mit
1
/** * Copyright (c) 2017 Yansong Li * * 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. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * 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 /// The layout that can place a card at the left edge of screen. public class EdgeCardLayout: UICollectionViewFlowLayout { fileprivate var lastCollectionViewSize: CGSize = CGSize.zero public required init?(coder aDecoder: NSCoder) { fatalError() } override init() { super.init() scrollDirection = .horizontal minimumLineSpacing = 25 } public override func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) { super.invalidateLayout(with: context) guard let collectionView = collectionView else { return } if collectionView.bounds.size != lastCollectionViewSize { configureInset() lastCollectionViewSize = collectionView.bounds.size } } public override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { guard let collectionView = collectionView else { return proposedContentOffset } let proposedRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.bounds.width, height: collectionView.bounds.height) guard var layoutAttributes = layoutAttributesForElements(in: proposedRect) else { return proposedContentOffset } layoutAttributes = layoutAttributes.sorted { $0.frame.origin.x < $1.frame.origin.x } let leftMostAttribute = layoutAttributes[0] if leftMostAttribute.frame.origin.x > proposedContentOffset.x { return CGPoint(x: leftMostAttribute.frame.origin.x - minimumLineSpacing, y: proposedContentOffset.y) } if velocity.x > 0 { if fabs(leftMostAttribute.frame.origin.x - proposedContentOffset.x) > (itemSize.width / 2) || velocity.x > 0.3 { return CGPoint(x: leftMostAttribute.frame.maxX, y: proposedContentOffset.y) } else { return CGPoint(x: leftMostAttribute.frame.origin.x - minimumLineSpacing, y: proposedContentOffset.y) } } if velocity.x < 0 { if fabs(leftMostAttribute.frame.origin.x - proposedContentOffset.x) <= (itemSize.width / 2) || velocity.x < -0.3 { return CGPoint(x: leftMostAttribute.frame.origin.x - minimumLineSpacing, y: proposedContentOffset.y) } else { return CGPoint(x: leftMostAttribute.frame.maxX, y: proposedContentOffset.y) } } return proposedContentOffset } } // MARK: helpers extension EdgeCardLayout { fileprivate func configureInset() -> Void { guard let collectionView = collectionView else { return } let inset = minimumLineSpacing collectionView.contentInset = UIEdgeInsetsMake(0, inset, 0, inset) collectionView.contentOffset = CGPoint(x: -inset, y: 0) } }
acc6cc3afec51c58c683c9baad492822
38.119658
99
0.698711
false
false
false
false
igroomgrim/swift101
refs/heads/master
Swift101_Playground.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit // Day 92 - Import your class into XCODE 7 Playground /* let userAddress = Address(buildingName: "Shanghai Tower", buildingNumber: "BD01", street: "Shanghai Road") userAddress.buildingName userAddress.buildingNumber userAddress.street userAddress.displayDetail() */ // Day 91 - Strings in Swift 2 /* var letters: [Character] = ["A", "R", "S", "E", "N", "A", "L"] var string: String = String(letters) print(letters.count) print(string) print(string.characters.count) let registeredTrademark: Character = "\u{00AE}" string.append(registeredTrademark) print(string.characters.count) print(string.characters.last!) print(string.characters.first!) string.characters.contains("S") */ // Day 90 - UIKit on playground /* let maView = MaView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) maView.backgroundColor = UIColor.blueColor() maView let testButton = UIButton(frame: CGRect(x: 0, y: 0, width: 80, height: 44)) testButton.backgroundColor = UIColor.greenColor() testButton let maButton = MaButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) maButton.backgroundColor = UIColor.greenColor() maButton.layer.cornerRadius = 4 maButton */ // Day 89 - Sets var characters = Set<Character>() characters.insert("R") characters.insert("O") characters.insert("C") characters.insert("K") characters var pointSet: Set<Int> = [1,2,3,4,5,6,7,8,9] for point in pointSet { print("\(point)") } for point in pointSet.sort() { print("\(point)") } var setOne: Set<Int> = [4,5,6,7,8,8] var setTwo: Set<Int> = [1,2,3,4,5] setOne.intersect(setTwo) setOne.subtract(setTwo)
ed14ee09cf91b9dd95a5bf273bc70e9c
22.782609
106
0.714808
false
false
false
false
marinehero/swift-perf
refs/heads/master
src/tests/RenderGradient.swift
mit
1
/*! =========================================================================== @file RenderGradient.swift @brief A simple function that fills in an array of pixel data. @copyright 2015 David Owens II. All rights reserved. ============================================================================ */ import simd func renderGradient_PixelArray(samples: Int, iterations: Int) -> Result { struct Pixel { var red: UInt8 var green: UInt8 var blue: UInt8 var alpha: UInt8 } struct RenderBuffer { var pixels: [Pixel] var width: Int var height: Int init(width: Int, height: Int) { assert(width > 0) assert(height > 0) let pixel = Pixel(red: 0, green: 0, blue: 0, alpha: 0xFF) pixels = [Pixel](count: width * height, repeatedValue: pixel) self.width = width self.height = height } } func RenderGradient(inout buffer: RenderBuffer, offsetX: Int, offsetY: Int) { // I truly hope you have turned down the number of iterations or you have picked // up a new build of Swift where this is not dog slow with -Onone. var offset = 0 for (var y = 0, height = buffer.height; y < height; ++y) { for (var x = 0, width = buffer.width; x < width; ++x) { let pixel = Pixel( red: 0, green: UInt8((y + offsetY) & 0xFF), blue: UInt8((x + offsetX) & 0xFF), alpha: 0xFF) buffer.pixels[offset] = pixel; ++offset; } } } var buffer = RenderBuffer(width: 960, height: 540) return perflib.measure(samples, iterations) { RenderGradient(&buffer, offsetX: 2, offsetY: 1) } } func renderGradient_PixelArray_UInt32(samples: Int, iterations: Int) -> Result { typealias Pixel = UInt32 struct RenderBuffer { var pixels: [Pixel] var width: Int var height: Int static func rgba(red: UInt8, _ green: UInt8, _ blue: UInt8, _ alpha: UInt8) -> Pixel { let r = UInt32(red) let g = UInt32(green) << 8 let b = UInt32(blue) << 16 let a = UInt32(alpha) << 24 return r | g | b | a } init(width: Int, height: Int) { assert(width > 0) assert(height > 0) let pixel = RenderBuffer.rgba(0, 0, 0, 0xFF) pixels = [Pixel](count: width * height, repeatedValue: pixel) self.width = width self.height = height } } func RenderGradient(inout buffer: RenderBuffer, offsetX: Int, offsetY: Int) { // I truly hope you have turned down the number of iterations or you have picked // up a new build of Swift where this is not dog slow with -Onone. var offset = 0 for (var y = 0, height = buffer.height; y < height; ++y) { for (var x = 0, width = buffer.width; x < width; ++x) { let pixel = RenderBuffer.rgba( 0, UInt8((y + offsetY) & 0xFF), UInt8((x + offsetX) & 0xFF), 0xFF) buffer.pixels[offset] = pixel; ++offset; } } } var buffer = RenderBuffer(width: 960, height: 540) return perflib.measure(samples, iterations) { RenderGradient(&buffer, offsetX: 2, offsetY: 1) } } func renderGradient_unsafeMutablePointer(samples: Int, iterations: Int) -> Result { struct Pixel { var red: UInt8 var green: UInt8 var blue: UInt8 var alpha: UInt8 } struct RenderBuffer { var pixels: UnsafeMutablePointer<Pixel> var width: Int var height: Int init(width: Int, height: Int) { assert(width > 0) assert(height > 0) pixels = UnsafeMutablePointer.alloc(width * height * sizeof(Pixel)) self.width = width self.height = height } mutating func release() { pixels.dealloc(width * height * sizeof(Pixel)) width = 0 height = 0 } } func RenderGradient(inout buffer: RenderBuffer, offsetX: Int, offsetY: Int) { var offset = 0 for (var y = 0, height = buffer.height; y < height; ++y) { for (var x = 0, width = buffer.width; x < width; ++x) { let pixel = Pixel( red: 0, green: UInt8((y + offsetY) & 0xFF), blue: UInt8((x + offsetX) & 0xFF), alpha: 0xFF) buffer.pixels[offset] = pixel; ++offset; } } } var buffer = RenderBuffer(width: 960, height: 540) return perflib.measure(samples, iterations) { RenderGradient(&buffer, offsetX: 2, offsetY: 1) } } func renderGradient_unsafeMutablePointer_UInt32(samples: Int, iterations: Int) -> Result { typealias Pixel = UInt32 struct RenderBuffer { var pixels: UnsafeMutablePointer<Pixel> var width: Int var height: Int static func rgba(red: UInt8, _ green: UInt8, _ blue: UInt8, _ alpha: UInt8) -> Pixel { let r = UInt32(red) let g = UInt32(green) << 8 let b = UInt32(blue) << 16 let a = UInt32(alpha) << 24 return r | g | b | a } init(width: Int, height: Int) { assert(width > 0) assert(height > 0) pixels = UnsafeMutablePointer.alloc(width * height * sizeof(Pixel)) self.width = width self.height = height } mutating func release() { pixels.dealloc(width * height * sizeof(Pixel)) width = 0 height = 0 } } func RenderGradient(inout buffer: RenderBuffer, offsetX: Int, offsetY: Int) { var offset = 0 for (var y = 0, height = buffer.height; y < height; ++y) { for (var x = 0, width = buffer.width; x < width; ++x) { let pixel = RenderBuffer.rgba( 0, UInt8((y + offsetY) & 0xFF), UInt8((x + offsetX) & 0xFF), 0xFF) buffer.pixels[offset] = pixel; ++offset; } } } var buffer = RenderBuffer(width: 960, height: 540) return perflib.measure(samples, iterations) { RenderGradient(&buffer, offsetX: 2, offsetY: 1) } } func renderGradient_ArrayUsingUnsafeMutablePointer(samples: Int, iterations: Int) -> Result { struct Pixel { var red: UInt8 var green: UInt8 var blue: UInt8 var alpha: UInt8 } struct RenderBuffer { var pixels: [Pixel] var width: Int var height: Int init(width: Int, height: Int) { assert(width > 0) assert(height > 0) let pixel = Pixel(red: 0, green: 0, blue: 0, alpha: 0xFF) pixels = [Pixel](count: width * height, repeatedValue: pixel) self.width = width self.height = height } } func RenderGradient(inout buffer: RenderBuffer, offsetX: Int, offsetY: Int) { // Turn this code on for at least some sanity back to your debug builds. It's still // going to be slow, but at compared to the code above, it's going to feel glorious. buffer.pixels.withUnsafeMutableBufferPointer { (inout p: UnsafeMutableBufferPointer<Pixel>) -> () in var offset = 0 for (var y = 0, height = buffer.height; y < height; ++y) { for (var x = 0, width = buffer.width; x < width; ++x) { let pixel = Pixel( red: 0, green: UInt8((y + offsetY) & 0xFF), blue: UInt8((x + offsetX) & 0xFF), alpha: 0xFF) p[offset] = pixel ++offset; } } } } var buffer = RenderBuffer(width: 960, height: 540) return perflib.measure(samples, iterations) { RenderGradient(&buffer, offsetX: 2, offsetY: 1) } } func renderGradient_ArrayUsingUnsafeMutablePointer_UInt32(samples: Int, iterations: Int) -> Result { typealias Pixel = UInt32 struct RenderBuffer { var pixels: [Pixel] var width: Int var height: Int static func rgba(red: UInt8, _ green: UInt8, _ blue: UInt8, _ alpha: UInt8) -> Pixel { let r = UInt32(red) let g = UInt32(green) << 8 let b = UInt32(blue) << 16 let a = UInt32(alpha) << 24 return r | g | b | a } init(width: Int, height: Int) { assert(width > 0) assert(height > 0) let pixel = RenderBuffer.rgba(0, 0, 0, 0xFF) pixels = [Pixel](count: width * height, repeatedValue: pixel) self.width = width self.height = height } } func RenderGradient(inout buffer: RenderBuffer, offsetX: Int, offsetY: Int) { // Turn this code on for at least some sanity back to your debug builds. It's still // going to be slow, but at compared to the code above, it's going to feel glorious. buffer.pixels.withUnsafeMutableBufferPointer { (inout p: UnsafeMutableBufferPointer<Pixel>) -> () in var offset = 0 for (var y = 0, height = buffer.height; y < height; ++y) { for (var x = 0, width = buffer.width; x < width; ++x) { let pixel = RenderBuffer.rgba( 0, UInt8((y + offsetY) & 0xFF), UInt8((x + offsetX) & 0xFF), 0xFF) p[offset] = pixel ++offset; } } } } var buffer = RenderBuffer(width: 960, height: 540) return perflib.measure(samples, iterations) { RenderGradient(&buffer, offsetX: 2, offsetY: 1) } } func renderGradient_ArrayUsingUnsafeMutablePointer_Pixel_SIMD(samples: Int, iterations: Int) -> Result { struct Pixel { var red: UInt8 var green: UInt8 var blue: UInt8 var alpha: UInt8 init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8 = 255) { self.red = red self.green = green self.blue = blue self.alpha = alpha } init(red: Int32, green: Int32, blue: Int32, alpha: Int32 = 255) { self.red = UInt8(red & 255) self.green = UInt8(green & 255) self.blue = UInt8(blue & 255) self.alpha = UInt8(alpha & 255) } init(red: Int, green: Int, blue: Int, alpha: Int = 255) { self.red = UInt8(red & 255) self.green = UInt8(green & 255) self.blue = UInt8(blue & 255) self.alpha = UInt8(alpha & 255) } } struct RenderBuffer { var pixels: [Pixel] var width: Int var height: Int init(width: Int, height: Int) { precondition(width > 0) precondition(height > 0) let pixel = Pixel(red: 0, green: 0, blue: 0, alpha: 0xFF) pixels = [Pixel](count: width * height, repeatedValue: pixel) self.width = width self.height = height } } func RenderGradient(inout buffer: RenderBuffer, offsetX: Int, offsetY: Int) { buffer.pixels.withUnsafeMutableBufferPointer { (inout p: UnsafeMutableBufferPointer<Pixel>) -> () in var offset = 0 let yoffset = int4(Int32(offsetY)) let xoffset = int4(Int32(offsetX)) // NOTE(owensd): There is a performance loss using the friendly versions. //for y in 0..<buffer.height { for var y = 0, height = buffer.height; y < height; ++y { let green = min(int4(Int32(y)) + yoffset, 255) //for x in stride(from: 0, through: buffer.width - 1, by: 4) { for var x: Int32 = 0, width = buffer.width; x < Int32(width); x += 4 { let blue = min(int4(x, x + 1, x + 2, x + 3) + xoffset, 255) p[offset++] = Pixel(red: 0, green: green.x, blue: blue.x, alpha: 255) p[offset++] = Pixel(red: 0, green: green.y, blue: blue.y, alpha: 255) p[offset++] = Pixel(red: 0, green: green.z, blue: blue.z, alpha: 255) p[offset++] = Pixel(red: 0, green: green.w, blue: blue.w, alpha: 255) } } } } var buffer = RenderBuffer(width: 960, height: 540) return perflib.measure(samples, iterations) { RenderGradient(&buffer, offsetX: 2, offsetY: 1) } } func renderGradient_ArrayUsingUnsafeMutablePointer_UInt32_SIMD(samples: Int, iterations: Int) -> Result { typealias Pixel = UInt32 struct RenderBuffer { var pixels: [Pixel] var width: Int var height: Int static func rgba(red: UInt8, _ green: UInt8, _ blue: UInt8, _ alpha: UInt8) -> Pixel { let r = UInt32(red) let g = UInt32(green) << 8 let b = UInt32(blue) << 16 let a = UInt32(alpha) << 24 return r | g | b | a } init(width: Int, height: Int) { precondition(width > 0) precondition(height > 0) let pixel = RenderBuffer.rgba(0, 0, 0, 255) pixels = [Pixel](count: width * height, repeatedValue: pixel) self.width = width self.height = height } } func RenderGradient(inout buffer: RenderBuffer, offsetX: Int, offsetY: Int) { buffer.pixels.withUnsafeMutableBufferPointer { (inout p: UnsafeMutableBufferPointer<Pixel>) -> () in var offset = 0 let yoffset = int4(Int32(offsetY)) let xoffset = int4(Int32(offsetX)) let inc = int4(0, 1, 2, 3) let blueaddr = inc + xoffset // TODO(owensd): Move to the 8-bit SIMD instructions when they are available. // NOTE(owensd): There is a performance loss using the friendly versions. //for y in 0..<buffer.height { for var y: Int32 = 0, height = buffer.height; y < Int32(height); ++y { let green = int4(y) + yoffset //for x in stride(from: 0, through: buffer.width - 1, by: 4) { for var x: Int32 = 0, width = buffer.width; x < Int32(width); x += 4 { let blue = int4(x) + blueaddr p[offset++] = 0xFF << 24 | UInt32(blue.x & 0xFF) << 16 | UInt32(green.x & 0xFF) << 8 p[offset++] = 0xFF << 24 | UInt32(blue.y & 0xFF) << 16 | UInt32(green.y & 0xFF) << 8 p[offset++] = 0xFF << 24 | UInt32(blue.z & 0xFF) << 16 | UInt32(green.z & 0xFF) << 8 p[offset++] = 0xFF << 24 | UInt32(blue.w & 0xFF) << 16 | UInt32(green.w & 0xFF) << 8 } } } } var buffer = RenderBuffer(width: 960, height: 540) return perflib.measure(samples, iterations) { RenderGradient(&buffer, offsetX: 2, offsetY: 1) } }
3a17e0e8a31b159646e8267ee58867f5
32.970402
108
0.495301
false
false
false
false
HJliu1123/LearningNotes-LHJ
refs/heads/master
April/Xbook/Xbook/pushNewBook/Controller/HJPhotoPickerController.swift
apache-2.0
1
// // HJPhotoPickerController.swift // Xbook // // Created by liuhj on 16/1/22. // Copyright © 2016年 liuhj. All rights reserved. // import UIKit protocol HJPhotoPickerDelegate { func getImageFromPicker(image:UIImage) } class HJPhotoPickerController: UIViewController ,UIImagePickerControllerDelegate, UINavigationControllerDelegate{ var alert : UIAlertController? var picker : UIImagePickerController! var delegate : HJPhotoPickerDelegate! override func viewDidLoad() { super.viewDidLoad() } init() { super.init(nibName: nil, bundle: nil) self.modalPresentationStyle = .OverFullScreen self.view.backgroundColor = UIColor.clearColor() self.picker = UIImagePickerController() self.picker.allowsEditing = false self.picker.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidAppear(animated: Bool) { if (self.alert == nil) { self.alert = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) self.alert?.addAction(UIAlertAction(title: "从相册选择", style: .Default, handler: { (action) -> Void in self.localPhoto() })) self.alert?.addAction(UIAlertAction(title: "打开相机", style: .Default, handler: { (action) -> Void in self.takePhoto() })) self.alert?.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: { (action) -> Void in })) self.presentViewController(self.alert!, animated: true, completion: { () -> Void in }) } } /* 打开相机 */ func takePhoto() { //判断该机型是否有相机功能 if (UIImagePickerController.isSourceTypeAvailable(.Camera)) { self.picker?.sourceType = .Camera self.presentViewController(self.picker!, animated: true, completion: { () -> Void in }) } else { let alertView = UIAlertController(title: "无相机", message: nil, preferredStyle: .Alert) alertView.addAction(UIAlertAction(title: "关闭", style: .Cancel, handler: { (ACTION) -> Void in self.dismissViewControllerAnimated(true, completion: { () -> Void in }) })) self.presentViewController(alertView, animated: true, completion: { () -> Void in }) } } /* 打开本地相册 */ func localPhoto() { self.picker?.sourceType = .PhotoLibrary self.presentViewController(self.picker, animated: true) { () -> Void in } } func imagePickerControllerDidCancel(picker: UIImagePickerController) { self.picker?.dismissViewControllerAnimated(true) { () -> Void in self.dismissViewControllerAnimated(true, completion: { () -> Void in }) } } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage self.picker?.dismissViewControllerAnimated(true){ () -> Void in self.dismissViewControllerAnimated(true, completion: { () -> Void in self.delegate.getImageFromPicker(image) }) } } }
9f49e1a51a742b7babfac2ef746990d7
26.107914
123
0.550159
false
false
false
false
zhangjk4859/NextStep
refs/heads/master
代码实现/测试区域/基本语法/基本语法/struct.swift
gpl-3.0
1
// // struct.swift // 基本语法 // // Created by 张俊凯 on 2017/1/13. // Copyright © 2017年 张俊凯. All rights reserved. // import Foundation //class Person { // var residence: Residence? //} // //// 定义了一个变量 rooms,它被初始化为一个Room[]类型的空数组 //class Residence { // var rooms = [Room]() // var numberOfRooms: Int { // return rooms.count // } // subscript(i: Int) -> Room { // return rooms[i] // } // func printNumberOfRooms() { // print("房间号为 \(numberOfRooms)") // } // var address: Address? //} // //// Room 定义一个name属性和一个设定room名的初始化器 //class Room { // let name: String // init(name: String) { self.name = name } //} // //// 模型中的最终类叫做Address //class Address { // var buildingName: String? // var buildingNumber: String? // var street: String? // func buildingIdentifier() -> String? { // if (buildingName != nil) { // return buildingName // } else if (buildingNumber != nil) { // return buildingNumber // } else { // return nil // } // } //} // //let john = Person() // // //if ((john.residence?.printNumberOfRooms()) != nil) { // print("输出房间号") //} else { // print("无法输出房间号") //} //class Person { // var residence: Residence? //} // //// 定义了一个变量 rooms,它被初始化为一个Room[]类型的空数组 //class Residence { // var rooms = [Room]() // var numberOfRooms: Int { // return rooms.count // } // subscript(i: Int) -> Room { // return rooms[i] // } // func printNumberOfRooms() { // print("房间号为 \(numberOfRooms)") // } // var address: Address? //} // //// Room 定义一个name属性和一个设定room名的初始化器 //class Room { // let name: String // init(name: String) { self.name = name } //} // //// 模型中的最终类叫做Address //class Address { // var buildingName: String? // var buildingNumber: String? // var street: String? // func buildingIdentifier() -> String? { // if (buildingName != nil) { // return buildingName // } else if (buildingNumber != nil) { // return buildingNumber // } else { // return nil // } // } //} //class Person { // var residence: Residence? //} // //class Residence { // var numberOfRooms = 1 //} // //let john = Person() // //// 链接可选residence?属性,如果residence存在则取回numberOfRooms的值 //if let roomCount = john.residence?.numberOfRooms { // print("John 的房间号为 \(roomCount)。") //} else { // print("不能查看房间号") //} // //class Person { // var residence: Residence? //} // //class Residence { // var numberOfRooms = 1 //} // //let john = Person() // ////将导致运行时错误 //let roomCount = john.residence?.numberOfRooms // //print(roomCount) //var counter = 0; // 引用计数器 //class BaseClass { // init() { // counter += 1; // } // // deinit { // counter -= 1; // } //} // //var show: BaseClass? = BaseClass() // //print(counter) //print(counter) //var counter = 0; // 引用计数器 //class BaseClass { // init() { // counter += 1; // } // deinit { // counter -= 1; // } //} // //var show: BaseClass? = BaseClass() //print(counter) //show = nil //print(counter) //struct StudRecord { // let stname: String // // init!(stname: String) { // if stname.isEmpty {return nil } // self.stname = stname // } //} // //let stmark = StudRecord(stname: "Runoob") //if let name = stmark { // print("指定了学生名") //} // //let blankname = StudRecord(stname: "") //if blankname == nil { // print("学生名为空") //} //class Planet { // var name: String // // init(name: String) { // self.name = name // } // // convenience init() { // self.init(name: "[No Planets]") // } //} //let plName = Planet(name: "Mercury") //print("行星的名字是: \(plName.name)") // //let noplName = Planet() //print("没有这个名字的行星: \(noplName.name)") // //class planets: Planet { // var count: Int // // init(name: String, count: Int) { // self.count = count // super.init(name: name) // } // // override convenience init(name: String) { // self.init(name: name, count: 1) // } //} //class StudRecord { // let studname: String! // init?(studname: String) { // self.studname = studname // if studname.isEmpty { return nil } // } //} //if let stname = StudRecord(studname: "失败构造器") { // print("模块为 \(stname.studname)") //} //enum TemperatureUnit { // // 开尔文,摄氏,华氏 // case Kelvin, Celsius, Fahrenheit // init?(symbol: Character) { // switch symbol { // case "K": // self = .Kelvin // case "C": // self = .Celsius // case "F": // self = .Fahrenheit // default: // return nil // } // } //} // // //let fahrenheitUnit = TemperatureUnit(symbol: "F") //if fahrenheitUnit != nil { // print("这是一个已定义的温度单位,所以初始化成功。") //} // //let unknownUnit = TemperatureUnit(symbol: "X") //if unknownUnit == nil { // print("这不是一个已定义的温度单位,所以初始化失败。") //} //struct Animal { // let species: String // init?(species: String) { // if species.isEmpty { return nil } // self.species = species // } //} // ////通过该可失败构造器来构建一个Animal的对象,并检查其构建过程是否成功 //// someCreature 的类型是 Animal? 而不是 Animal //let someCreature = Animal(species: "长颈鹿") // //// 打印 "动物初始化为长颈鹿" //if let giraffe = someCreature { // print("动物初始化为\(giraffe.species)") //} //class SuperClass { // var corners = 4 // var description: String { // return "\(corners) 边" // } //} //let rectangle = SuperClass() //print("矩形: \(rectangle.description)") // //class SubClass: SuperClass { // override init() { //重载构造器 // super.init() // corners = 5 // } //} // //let subClass = SubClass() //print("五角型: \(subClass.description)") //class mainClass { // var no1 : Int // 局部存储变量 // init(no1 : Int) { // self.no1 = no1 // 初始化 // } //} // //class subClass : mainClass { // var no2 : Int // init(no1 : Int, no2 : Int) { // self.no2 = no2 // super.init(no1:no1) // } // // 便利方法只需要一个参数 // override convenience init(no1: Int) { // self.init(no1:no1, no2:0) // } //} //let res = mainClass(no1: 20) //let res2 = subClass(no1: 30, no2: 50) // //print("res 为: \(res.no1)") //print("res2 为: \(res2.no1)") //print("res2 为: \(res2.no2)") //class mainClass { // var no1 : Int // 局部存储变量 // init(no1 : Int) { // self.no1 = no1 // 初始化 // } //} //class subClass : mainClass { // var no2 : Int // 新的子类存储变量 // init(no1 : Int, no2 : Int) { // self.no2 = no2 // 初始化 // super.init(no1:no1) // 初始化超类 // } //} // //let res = mainClass(no1: 10) //let res2 = subClass(no1: 10, no2: 20) // //print("res 为: \(res.no1)") //print("res2 为: \(res2.no1)") //print("res2 为: \(res2.no2)") ////在init方法里做事情,节省代码 //struct Size { // var width = 0.0, height = 0.0 //} //struct Point { // var x = 0.0, y = 0.0 //} // //struct Rect { // var origin = Point() // var size = Size() // init() {} // init(origin: Point, size: Size) { // self.origin = origin // self.size = size // } // init(center: Point, size: Size) { // let originX = center.x - (size.width / 2) // let originY = center.y - (size.height / 2) // self.init(origin: Point(x: originX, y: originY), size: size) // } //} // // //// origin和size属性都使用定义时的默认值Point(x: 0.0, y: 0.0)和Size(width: 0.0, height: 0.0): //let basicRect = Rect() //print("Size 结构体初始值: \(basicRect.size.width, basicRect.size.height) ") //print("Rect 结构体初始值: \(basicRect.origin.x, basicRect.origin.y) ") // //// 将origin和size的参数值赋给对应的存储型属性 //let originRect = Rect(origin: Point(x: 2.0, y: 2.0), // size: Size(width: 5.0, height: 5.0)) // //print("Size 结构体初始值: \(originRect.size.width, originRect.size.height) ") //print("Rect 结构体初始值: \(originRect.origin.x, originRect.origin.y) ") // // ////先通过center和size的值计算出origin的坐标。 ////然后再调用(或代理给)init(origin:size:)构造器来将新的origin和size值赋值到对应的属性中 //let centerRect = Rect(center: Point(x: 4.0, y: 4.0), // size: Size(width: 3.0, height: 3.0)) // //print("Size 结构体初始值: \(centerRect.size.width, centerRect.size.height) ") //print("Rect 结构体初始值: \(centerRect.origin.x, centerRect.origin.y) ") //struct Rectangle { // var length = 100.0, breadth = 200.0 //} //let area = Rectangle(length: 24.0, breadth: 32.0) // //print("矩形的面积: \(area.length)") //print("矩形的面积: \(area.breadth)") //class ShoppingListItem { // var name: String? // var quantity = 1 // var purchased = false //} //var item = ShoppingListItem() // // //print("名字为: \(item.name)") //print("数理为: \(item.quantity)") //print("是否付款: \(item.purchased)") //struct Rectangle { // let length: Double? // // init(frombreadth breadth: Double) { // length = breadth * 10 // } // // init(frombre bre: Double) { // length = bre * 30 // } // // init(_ area: Double) { // length = area // } //} // //let rectarea = Rectangle(180.0) //print("面积为:\(rectarea.length)") // //let rearea = Rectangle(370.0) //print("面积为:\(rearea.length)") // //let recarea = Rectangle(110.0) //print("面积为:\(recarea.length)") //struct Rectangle { // var length: Double? // // init(frombreadth breadth: Double) { // length = breadth * 10 // } // // init(frombre bre: Double) { // length = bre * 30 // } // // init(_ area: Double) { // length = area // } //} // //let rectarea = Rectangle(180.0) //print("面积为:\(rectarea.length)") // //let rearea = Rectangle(370.0) //print("面积为:\(rearea.length)") // //let recarea = Rectangle(110.0) //print("面积为:\(recarea.length)") //struct Rectangle { // var length: Double // // init(frombreadth breadth: Double) { // length = breadth * 10 // } // // init(frombre bre: Double) { // length = bre * 30 // } // //不提供外部名字 // init(_ area: Double) { // length = area // } //} // //// 调用不提供外部名字 //let rectarea = Rectangle(180.0) //print("面积为: \(rectarea.length)") // //// 调用不提供外部名字 //let rearea = Rectangle(370.0) //print("面积为: \(rearea.length)") // //// 调用不提供外部名字 //let recarea = Rectangle(110.0) //print("面积为: \(recarea.length)") //struct Color { // let red, green, blue: Double // init(red: Double, green: Double, blue: Double) { // self.red = red // self.green = green // self.blue = blue // } // init(white: Double) { // red = white // green = white // blue = white // } //} // //// 创建一个新的Color实例,通过三种颜色的外部参数名来传值,并调用构造器 //let magenta = Color(red: 1.0, green: 0.0, blue: 1.0) // //print("red 值为: \(magenta.red)") //print("green 值为: \(magenta.green)") //print("blue 值为: \(magenta.blue)") // //// 创建一个新的Color实例,通过三种颜色的外部参数名来传值,并调用构造器 //let halfGray = Color(white: 0.5) //print("red 值为: \(halfGray.red)") //print("green 值为: \(halfGray.green)") //print("blue 值为: \(halfGray.blue)") //struct Rectangle { // var length: Double // var breadth: Double // var area: Double // // init(fromLength length: Double, fromBreadth breadth: Double) { // self.length = length // self.breadth = breadth // self.area = length * breadth // } // // init(fromLeng leng: Double, fromBread bread: Double) { // self.length = leng // self.breadth = bread // self.area = leng * bread // } //} // //let ar = Rectangle(fromLength: 6, fromBreadth: 12) //print("面积为: \(ar.area)") // //let are = Rectangle(fromLeng: 36, fromBread: 12) //print("面积为: \(are.area)") //struct rectangle { // // 设置默认值 // var length = 6 // var breadth = 12 //} //var area = rectangle() //print("矩形的面积为 \(area.length*area.breadth)") //struct rectangle { // var length: Double // var breadth: Double // init() { // length = 6 // breadth = 12 // } //} //var area = rectangle() //print("矩形面积为 \(area.length*area.breadth)")
327abe97fec623f485607fce9959fbfe
20.056738
80
0.55128
false
false
false
false
auth0/JWTDecode.swift
refs/heads/master
JWTDecodeTests/JWTDecodeSpec.swift
mit
1
import Quick import Nimble import JWTDecode import Foundation class JWTDecodeSpec: QuickSpec { override func spec() { describe("decode") { it("should tell a jwt is expired") { expect(expiredJWT().expired).to(beTruthy()) } it("should tell a jwt is not expired") { expect(nonExpiredJWT().expired).to(beFalsy()) } it("should tell a jwt is expired with a close enough timestamp") { expect(jwtThatExpiresAt(date: Date()).expired).to(beTruthy()) } it("should obtain payload") { let jwt = jwt(withBody: ["sub": "myid", "name": "Shawarma Monk"]) let payload = jwt.body as! [String: String] expect(payload).to(equal(["sub": "myid", "name": "Shawarma Monk"])) } it("should return original jwt string representation") { let jwtString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJjb20uc29td2hlcmUuZmFyLmJleW9uZDphcGkiLCJpc3MiOiJhdXRoMCIsInVzZXJfcm9sZSI6ImFkbWluIn0.sS84motSLj9HNTgrCPcAjgZIQ99jXNN7_W9fEIIfxz0" let jwt = try! decode(jwt: jwtString) expect(jwt.string).to(equal(jwtString)) } it("should return expire date") { expect(expiredJWT().expiresAt).toNot(beNil()) } it("should decode valid jwt") { let jwtString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJjb20uc29td2hlcmUuZmFyLmJleW9uZDphcGkiLCJpc3MiOiJhdXRoMCIsInVzZXJfcm9sZSI6ImFkbWluIn0.sS84motSLj9HNTgrCPcAjgZIQ99jXNN7_W9fEIIfxz0" expect(try! decode(jwt: jwtString)).toNot(beNil()) } it("should decode valid jwt with empty json body") { let jwtString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.Et9HFtf9R3GEMA0IICOfFMVXY7kkTX1wr4qCyhIf58U" expect(try! decode(jwt: jwtString)).toNot(beNil()) } it("should raise exception with invalid base64 encoding") { let invalidChar = "%" let jwtString = "\(invalidChar).BODY.SIGNATURE" expect { try decode(jwt: jwtString) } .to(throwError { (error: Error) in expect(error).to(beJWTDecodeError(.invalidBase64URL(invalidChar))) }) } it("should raise exception with invalid json in jwt") { let jwtString = "HEADER.BODY.SIGNATURE" expect { try decode(jwt: jwtString) } .to(throwError { (error: Error) in expect(error).to(beJWTDecodeError(.invalidJSON("HEADER"))) }) } it("should raise exception with missing parts") { let jwtString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzdWIifQ" expect { try decode(jwt: jwtString) } .to(throwError { (error: Error) in expect(error).to(beJWTDecodeError(.invalidPartCount(jwtString, 2))) }) } } describe("jwt parts") { let sut = try! decode(jwt: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzdWIifQ.xXcD7WOvUDHJ94E6aVHYgXdsJHLl2oW7ZXm4QpVvXnY") it("should return header") { expect(sut.header as? [String: String]).to(equal(["alg": "HS256", "typ": "JWT"])) } it("should return body") { expect(sut.body as? [String: String]).to(equal(["sub": "sub"])) } it("should return signature") { expect(sut.signature).to(equal("xXcD7WOvUDHJ94E6aVHYgXdsJHLl2oW7ZXm4QpVvXnY")) } } describe("claims") { var sut: JWT! describe("expiresAt claim") { it("should handle expired jwt") { sut = expiredJWT() expect(sut.expiresAt).toNot(beNil()) expect(sut.expired).to(beTruthy()) } it("should handle non-expired jwt") { sut = nonExpiredJWT() expect(sut.expiresAt).toNot(beNil()) expect(sut.expired).to(beFalsy()) } it("should handle jwt without expiresAt claim") { sut = jwt(withBody: ["sub": UUID().uuidString]) expect(sut.expiresAt).to(beNil()) expect(sut.expired).to(beFalsy()) } } describe("registered claims") { let sut = try! decode(jwt: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL3NhbXBsZXMuYXV0aDAuY29tIiwic3ViIjoiYXV0aDB8MTAxMDEwMTAxMCIsImF1ZCI6Imh0dHBzOi8vc2FtcGxlcy5hdXRoMC5jb20iLCJleHAiOjEzNzI2NzQzMzYsImlhdCI6MTM3MjYzODMzNiwianRpIjoicXdlcnR5MTIzNDU2IiwibmJmIjoxMzcyNjM4MzM2fQ.LvF9wSheCB5xarpydmurWgi9NOZkdES5AbNb_UWk9Ew") it("should return issuer") { expect(sut.issuer).to(equal("https://samples.auth0.com")) } it("should return subject") { expect(sut.subject).to(equal("auth0|1010101010")) } it("should return single audience") { expect(sut.audience).to(equal(["https://samples.auth0.com"])) } context("multiple audiences") { let sut = try! decode(jwt: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiaHR0cHM6Ly9zYW1wbGVzLmF1dGgwLmNvbSIsImh0dHBzOi8vYXBpLnNhbXBsZXMuYXV0aDAuY29tIl19.cfWFPuJbQ7NToa-BjHgHD1tHn3P2tOP5wTQaZc1qg6M") it("should return all audiences") { expect(sut.audience).to(equal(["https://samples.auth0.com", "https://api.samples.auth0.com"])) } } it("should return issued at") { expect(sut.issuedAt).to(equal(Date(timeIntervalSince1970: 1372638336))) } it("should return not before") { expect(sut.notBefore).to(equal(Date(timeIntervalSince1970: 1372638336))) } it("should return jwt id") { expect(sut.identifier).to(equal("qwerty123456")) } } describe("custom claim") { beforeEach { sut = jwt(withBody: ["sub": UUID().uuidString, "custom_string_claim": "Shawarma Friday!", "custom_integer_claim": 10, "custom_double_claim": 3.4, "custom_double_string_claim": "1.3", "custom_true_boolean_claim": true, "custom_false_boolean_claim": false]) } it("should return claim by name") { let claim = sut.claim(name: "custom_string_claim") expect(claim.rawValue).toNot(beNil()) } it("should return string claim") { let claim = sut["custom_string_claim"] expect(claim.string) == "Shawarma Friday!" expect(claim.array) == ["Shawarma Friday!"] expect(claim.integer).to(beNil()) expect(claim.double).to(beNil()) expect(claim.date).to(beNil()) expect(claim.boolean).to(beNil()) } it("should return integer claim") { let claim = sut["custom_integer_claim"] expect(claim.string).to(beNil()) expect(claim.array).to(beNil()) expect(claim.integer) == 10 expect(claim.double) == 10.0 expect(claim.date) == Date(timeIntervalSince1970: 10) expect(claim.boolean).to(beNil()) } it("should return double claim") { let claim = sut["custom_double_claim"] expect(claim.string).to(beNil()) expect(claim.array).to(beNil()) expect(claim.integer) == 3 expect(claim.double) == 3.4 expect(claim.date) == Date(timeIntervalSince1970: 3.4) expect(claim.boolean).to(beNil()) } it("should return double as string claim") { let claim = sut["custom_double_string_claim"] expect(claim.string) == "1.3" expect(claim.array) == ["1.3"] expect(claim.integer).to(beNil()) expect(claim.double) == 1.3 expect(claim.date) == Date(timeIntervalSince1970: 1.3) expect(claim.boolean).to(beNil()) } it("should return true boolean claim") { let claim = sut["custom_true_boolean_claim"] expect(claim.string).to(beNil()) expect(claim.array).to(beNil()) expect(claim.integer).to(beNil()) expect(claim.double).to(beNil()) expect(claim.date).to(beNil()) expect(claim.boolean) == true } it("should return false boolean claim") { let claim = sut["custom_false_boolean_claim"] expect(claim.string).to(beNil()) expect(claim.array).to(beNil()) expect(claim.integer).to(beNil()) expect(claim.double).to(beNil()) expect(claim.date).to(beNil()) expect(claim.boolean) == false } it("should return no value when claim is not present") { let unknownClaim = sut["missing_claim"] expect(unknownClaim.array).to(beNil()) expect(unknownClaim.string).to(beNil()) expect(unknownClaim.integer).to(beNil()) expect(unknownClaim.double).to(beNil()) expect(unknownClaim.date).to(beNil()) expect(unknownClaim.boolean).to(beNil()) } context("raw claim") { var sut: JWT! beforeEach { sut = try! decode(jwt: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL3NhbXBsZXMuYXV0aDAuY29tIiwic3ViIjoiYXV0aDB8MTAxMDEwMTAxMCIsImF1ZCI6Imh0dHBzOi8vc2FtcGxlcy5hdXRoMC5jb20iLCJleHAiOjEzNzI2NzQzMzYsImlhdCI6MTM3MjYzODMzNiwianRpIjoicXdlcnR5MTIzNDU2IiwibmJmIjoxMzcyNjM4MzM2LCJlbWFpbCI6InVzZXJAaG9zdC5jb20iLCJjdXN0b20iOlsxLDIsM119.JeMRyHLkcoiqGxd958B6PABKNvhOhIgw-kbjecmhR_E") } it("should return email") { expect(sut["email"].string) == "[email protected]" } it("should return array") { expect(sut["custom"].rawValue as? [Int]).toNot(beNil()) } } } } } } public func beJWTDecodeError(_ code: JWTDecodeError) -> Predicate<Error> { return Predicate<Error>.define("be jwt decode error <\(code)>") { expression, failureMessage -> PredicateResult in guard let actual = try expression.evaluate() as? JWTDecodeError else { return PredicateResult(status: .doesNotMatch, message: failureMessage) } return PredicateResult(bool: actual == code, message: failureMessage) } } extension JWTDecodeError: Equatable {} public func ==(lhs: JWTDecodeError, rhs: JWTDecodeError) -> Bool { return lhs.localizedDescription == rhs.localizedDescription && lhs.errorDescription == rhs.errorDescription }
f60cee492a6ded42a66ee1aa642aa80f
44.187739
407
0.54019
false
false
false
false
cyanzhong/TodayMind
refs/heads/master
TodayMind/Main/View/SwitchCell.swift
gpl-3.0
2
// // SwitchCell.swift // TodayMind // // Created by cyan on 2017/2/21. // Copyright © 2017 cyan. All rights reserved. // import UIKit import TMKit class SwitchCell: BaseCell { let switcher = UISwitch() init(title: String, identifier: String, on: Bool) { super.init(style: .default, reuseIdentifier: identifier) textLabel?.text = title switcher.isOn = on accessoryView = switcher selectionStyle = .none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
44e488d36fdec6b252ee8b01f4a9296e
19.444444
60
0.67029
false
false
false
false
gservera/ScheduleKit
refs/heads/master
ScheduleKit/BaseDefinitions.swift
mit
1
/* * BaseDefinitions.swift * ScheduleKit * * Created: Guillem Servera on 24/12/2014. * Copyright: © 2014-2019 Guillem Servera (https://github.com/gservera) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Cocoa /// The shared calendar object used by the ScheduleKit framework. var sharedCalendar = Calendar.current /// A `Double` value that represents relative time points between the lower and /// upper date bounds in a concrete `SCKView` subclass. Valid values are the ones /// between 0.0 and 1.0, which represent the start date and the end date, /// respectively. Any other values are not valid and should be represented using /// `SCKRelativeTimeLocationInvalid`. internal typealias SCKRelativeTimeLocation = Double /// A `Double` value that represents the relative length (in percentage) for an /// event in a concrete `SCKView` subclass. Valid values are the ones /// between 0.0 and 1.0, which represent zero-length and full length values, /// respectively. Behaviour when using any other values in undefined. internal typealias SCKRelativeTimeLength = Double /// A fallback value generated by ScheduleKit the date of an event object used /// in a `SCKView` subclass does not fit in the view's date interval. internal let SCKRelativeTimeLocationInvalid = SCKRelativeTimeLocation(-Int.max) /// A fallback value generated by ScheduleKit the duration of an event object used /// in a `SCKView` subclass is invalid (negative or too wide). internal let SCKRelativeTimeLengthInvalid = SCKRelativeTimeLocation.leastNormalMagnitude /// Possible color styles for drawing event view backgrounds. @objc public enum SCKEventColorMode: Int { /// Colors events according to their event kind. case byEventKind /// Colors events according to their user's event color. case byEventOwner } extension Calendar { func dateInterval(_ interval: DateInterval, offsetBy value: Int, _ unit: Calendar.Component) -> DateInterval { let start = date(byAdding: unit, value: value, to: interval.start) let end = date(byAdding: unit, value: value, to: interval.end) return DateInterval(start: start!, end: end!) } } extension NSTextField { static func makeLabel(fontSize: CGFloat, color: NSColor) -> NSTextField { let label = NSTextField(frame: .zero) label.translatesAutoresizingMaskIntoConstraints = false label.isBordered = false label.isEditable = false label.isBezeled = false label.drawsBackground = false label.font = .systemFont(ofSize: fontSize) label.textColor = color return label } } extension CGRect { static func fill(_ xPos: CGFloat, _ yPos: CGFloat, _ wDim: CGFloat, _ hDim: CGFloat) { CGRect(x: xPos, y: yPos, width: wDim, height: hDim).fill() } }
b0fe5be72971465a696561c9ba321f40
40.591398
114
0.732678
false
false
false
false
seankim2/TodayWeather
refs/heads/master
ios/watch Extension/WatchTWeatherDraw.swift
mit
1
// // WatchTWeatherDraw.swift // watch Extension // // Created by KwangHo Kim on 2017. 11. 6.. // import WatchKit import WatchConnectivity import Foundation //let watchTWUtil = WatchTWeatherUtil(); class WatchTWeatherDraw : WKInterfaceController{ // @IBOutlet var updateDateLabel: WKInterfaceLabel! // @IBOutlet var currentPosImage: WKInterfaceImage! // @IBOutlet var addressLabel: WKInterfaceLabel! // @IBOutlet var curWeatherImage: WKInterfaceImage! // // @IBOutlet var curTempLabel: WKInterfaceLabel! // @IBOutlet var minMaxLabel: WKInterfaceLabel! // // @IBOutlet var precLabel: WKInterfaceLabel! // @IBOutlet var airAQILabel: WKInterfaceLabel! var curJsonDict : Dictionary<String, Any>? = nil; // Singleton static let sharedInstance : WatchTWeatherDraw = { let instance = WatchTWeatherDraw() //setup code return instance }() #if false struct StaticInstance { static var instance: WatchTWeatherDraw? } class func sharedInstance() -> WatchTWeatherDraw { if !(StaticInstance.instance != nil) { StaticInstance.instance = WatchTWeatherDraw() } return StaticInstance.instance! } #endif // let watchTWUtil = WatchTWeatherUtil.sharedInstance(); // let watchTWReq = WatchTWeatherRequest.sharedInstance(); // let watchTWSM = WatchTWeatherShowMore.sharedInstance(); #if false func processWeatherResultsWithShowMore( jsonDict : Dictionary<String, AnyObject>?) { //var currentDict : Dictionary<String, Any>; //var currentArpltnDict : Dictionary<String, Any>; var todayDict : Dictionary<String, Any>; // Date var strDateTime : String!; //var strTime : String? = nil; // Image //var strCurIcon : String? = nil; var strCurImgName : String? = nil; // Temperature var currentTemp : Float = 0; var todayMinTemp : Int = 0; var todayMaxTemp : Int = 0; // Dust var strAirState : String = ""; var attrStrAirState : NSAttributedString = NSAttributedString(); //NSMutableAttributedString *nsmasAirState = nil; // Address var strAddress : String? = nil; // Pop var numberTodPop : NSNumber; var todayPop : Int = 0; // current temperature var numberT1h : NSNumber; var numberTaMin : NSNumber; var numberTaMax : NSNumber; if(jsonDict == nil) { print("jsonDict is nil!!!"); return; } //print("processWeatherResultsWithShowMore : \(String(describing: jsonDict))"); setCurJsonDict( dict : jsonDict! ) ; // Address if let strRegionName : String = jsonDict?["regionName"] as? String { print("strRegionName is \(strRegionName).") strAddress = strRegionName; } else { print("That strRegionName is not in the jsonDict dictionary.") } if let strCityName : String = jsonDict?["cityName"] as? String { print("strCityName is \(strCityName).") strAddress = strCityName; } else { print("That strCityName is not in the jsonDict dictionary.") } if let strTownName : String = jsonDict?["townName"] as? String { print("strTownName is \(strTownName).") strAddress = strTownName; } else { print("That strTownName is not in the jsonDict dictionary.") } // if address is current position... add this emoji //목격자 //유니코드: U+1F441 U+200D U+1F5E8, UTF-8: F0 9F 91 81 E2 80 8D F0 9F 97 A8 print("strAddress \(String(describing: strAddress)))") strAddress = NSString(format: "👁‍🗨%@˚", strAddress!) as String let tempUnit : TEMP_UNIT? = watchTWUtil.getTemperatureUnit(); //#if KKH // Current if let currentDict : Dictionary<String, Any> = jsonDict?["current"] as? Dictionary<String, Any>{ //print("currentDict is \(currentDict).") if let strCurIcon : String = currentDict["skyIcon"] as? String { //strCurImgName = "weatherIcon2-color/\(strCurIcon).png"; strCurImgName = strCurIcon; } else { print("That strCurIcon is not in the jsonDict dictionary.") } if let strTime : String = currentDict["time"] as? String { let index = strTime.index(strTime.startIndex, offsetBy: 2) //let strHour = strTime.substring(to:index); let strHour = strTime[..<index]; //let strMinute = strTime.substring(from:index); let strMinute = strTime[index...]; strDateTime = NSLocalizedString("LOC_UPDATE", comment:"업데이트") + " " + strHour + ":" + strMinute; print("strTime => \(strTime)") print("strHour => \(strHour)") print("strMinute => \(strMinute)") } else { print("That strTime is not in the jsonDict dictionary.") strDateTime = ""; } print("strDateTime => \(strDateTime)") if let currentArpltnDict : Dictionary<String, Any> = currentDict["arpltn"] as? Dictionary<String, Any> { strAirState = watchTWSM.getAirState(currentArpltnDict); // Test //nssAirState = [NSString stringWithFormat:@"통합대기 78 나쁨"]; attrStrAirState = watchTWSM.getChangedColorAirState(strAirState:strAirState); print("[processWeatherResultsWithShowMore] attrStrAirState : \(String(describing: attrStrAirState))"); print("[processWeatherResultsWithShowMore] strAirState : \(String(describing: strAirState))"); } else { print("That currentArpltnDict is not in the jsonDict dictionary.") } if (currentDict["t1h"] != nil) { numberT1h = currentDict["t1h"] as! NSNumber; currentTemp = Float(numberT1h.doubleValue); if(tempUnit == TEMP_UNIT.FAHRENHEIT) { currentTemp = Float(watchTWUtil.convertFromCelsToFahr(cels: currentTemp)); } } } else { print("That currentDict is not in the jsonDict dictionary.") } //currentHum = [[currentDict valueForKey:@"reh"] intValue]; todayDict = watchTWUtil.getTodayDictionary(jsonDict: jsonDict!); // Today if (todayDict["taMin"] != nil) { numberTaMin = todayDict["taMin"] as! NSNumber; todayMinTemp = Int(numberTaMin.intValue); } else { print("That idTaMin is not in the todayDict dictionary.") } if(tempUnit == TEMP_UNIT.FAHRENHEIT) { todayMinTemp = Int( watchTWUtil.convertFromCelsToFahr(cels: Float(todayMinTemp) ) ); } if (todayDict["taMax"] != nil) { numberTaMax = todayDict["taMax"] as! NSNumber; todayMaxTemp = Int(numberTaMax.intValue); } else { print("That numberTaMax is not in the todayDict dictionary.") } if(tempUnit == TEMP_UNIT.FAHRENHEIT) { todayMaxTemp = Int(watchTWUtil.convertFromCelsToFahr(cels: Float(todayMaxTemp) )) ; } if (todayDict["pop"] != nil) { numberTodPop = todayDict["pop"] as! NSNumber; todayPop = Int(numberTodPop.intValue); } else { print("That pop is not in the todayDict dictionary.") } print("todayMinTemp: \(todayMinTemp), todayMaxTemp:\(todayMaxTemp)"); print("todayPop: \(todayPop)"); DispatchQueue.global(qos: .background).async { // Background Thread DispatchQueue.main.async { // Run UI Updates if(strDateTime != nil) { self.updateDateLabel.setText("\(strDateTime!)"); } print("=======> date : \(strDateTime!)"); if( (strAddress == nil) || ( strAddress == "(null)" )) { self.addressLabel.setText(""); } else { self.addressLabel.setText("\(strAddress!)"); } print("=======> strCurImgName : \(strCurImgName!)"); if(strCurImgName != nil) { self.curWeatherImage.setImage ( UIImage(named:strCurImgName!) ); } if(tempUnit == TEMP_UNIT.FAHRENHEIT) { self.curTempLabel.setText( NSString(format: "%d˚", currentTemp) as String ); } else { self.curTempLabel.setText( NSString(format: "%.01f˚", currentTemp) as String); } print("[processWeatherResultsWithShowMore] attrStrAirState2 : \(String(describing: attrStrAirState))"); self.airAQILabel.setAttributedText( attrStrAirState ); self.minMaxLabel.setText(NSString(format: "%d˚/ %d˚", todayMinTemp, todayMaxTemp) as String ); self.precLabel.setText(NSString(format: "%d%%", todayPop) as String ); //locationView.hidden = false; } } //#endif // Draw ShowMore //[todayWSM processDailyData:jsonDict type:TYPE_REQUEST_WEATHER_KR]; } func processWeatherResultsAboutGlobal( jsonDict : Dictionary<String, AnyObject>?) { let watchTWSM = WatchTWeatherShowMore(); var currentDict : Dictionary<String, Any>; //var currentArpltnDict : Dictionary<String, Any>; var todayDict : Dictionary<String, Any>? = nil; // Date var strDateTime : String!; //var strTime : String? = nil; // Image //var strCurIcon : String? = nil; var strCurImgName : String? = nil; // Temperature var tempUnit : TEMP_UNIT? = TEMP_UNIT.CELSIUS; var currentTemp : Float = 0; var todayMinTemp : Int = 0; var todayMaxTemp : Int = 0; // Dust var strAirState : String = ""; var attrStrAirState : NSAttributedString = NSAttributedString(); //NSMutableAttributedString *nsmasAirState = nil; // Address var strAddress : String? = nil; // Pop var numberTodPop : NSNumber; var todayPop : Int = 0; // Humid var numberTodHumid : NSNumber; var todayHumid = 0; if(jsonDict == nil) { print("jsonDict is nil!!!"); return; } //print("processWeatherResultsWithShowMore : \(String(describing: jsonDict))"); setCurJsonDict( dict : jsonDict! ) ; // Address //NSLog(@"mCurrentCityIdx : %d", mCurrentCityIdx); //NSMutableDictionary* nsdCurCity = [mCityDictList objectAtIndex:mCurrentCityIdx]; //NSLog(@"[processWeatherResultsAboutGlobal] nsdCurCity : %@", nsdCurCity); // Address //nssAddress = [nsdCurCity objectForKey:@"name"]; //nssCountry = [nsdCurCity objectForKey:@"country"]; //if(nssCountry == nil) //{ // nssCountry = @"KR"; //} //NSLog(@"[Global]nssAddress : %@, nssCountry : %@", nssAddress, nssCountry); // if address is current position... add this emoji //목격자 //유니코드: U+1F441 U+200D U+1F5E8, UTF-8: F0 9F 91 81 E2 80 8D F0 9F 97 A8 //print("strAddress \(String(describing: strAddress)))") //strAddress = NSString(format: "👁‍🗨%@˚", strAddress!) as String strAddress = NSString(format: "뉴욕") as String; // Current if let thisTimeArr : NSArray = jsonDict?["thisTime"] as? NSArray { if(thisTimeArr.count == 2) { currentDict = thisTimeArr[1] as! Dictionary<String, Any>; // Use second index; That is current weahter. } else { currentDict = thisTimeArr[0] as! Dictionary<String, Any>; // process about thisTime } if let strCurIcon : String = currentDict["skyIcon"] as? String { //strCurImgName = "weatherIcon2-color/\(strCurIcon).png"; strCurImgName = strCurIcon; } else { print("That strCurIcon is not in the jsonDict dictionary.") } tempUnit = watchTWUtil.getTemperatureUnit(); if let strTime : String = currentDict["date"] as? String { let index = strTime.index(strTime.startIndex, offsetBy: 11) let strHourMin = strTime[index...]; strDateTime = NSLocalizedString("LOC_UPDATE", comment:"업데이트") + " " + strHourMin; print("strTime => \(strHourMin)") todayDict = watchTWUtil.getTodayDictionaryInGlobal(jsonDict: jsonDict!, strTime:strTime); if(todayDict != nil) { if(tempUnit == TEMP_UNIT.FAHRENHEIT) { let idTaMin = todayDict!["tempMin_f"] as! NSNumber; todayMinTemp = Int(truncating: idTaMin); let idTaMax = todayDict!["tempMax_f"] as! NSNumber; todayMaxTemp = Int(truncating: idTaMax); } else { let idTaMin = todayDict!["tempMin_c"] as! NSNumber; todayMinTemp = Int(truncating: idTaMin); let idTaMax = todayDict!["tempMax_c"] as! NSNumber; todayMaxTemp = Int(truncating: idTaMax); } // PROBABILITY_OF_PRECIPITATION if (todayDict!["precProb"] != nil) { numberTodPop = todayDict!["precProb"] as! NSNumber; todayPop = Int(numberTodPop.intValue); } else { print("That precProb is not in the todayDict dictionary.") } // HUMID if (todayDict!["humid"] != nil) { numberTodHumid = todayDict!["humid"] as! NSNumber; todayHumid = Int(numberTodHumid.intValue); } else { print("That humid is not in the todayDict dictionary.") } strAirState = NSLocalizedString("LOC_HUMIDITY", comment:"습도") + " \(todayHumid)% "; } } else { print("That strTime is not in the jsonDict dictionary.") let strHourMin = ""; strDateTime = NSLocalizedString("LOC_UPDATE", comment:"업데이트") + " " + strHourMin; } print("strDateTime => \(strDateTime)") if(tempUnit == TEMP_UNIT.FAHRENHEIT) { let idT1h = currentDict["temp_f"] as! NSNumber; currentTemp = Float(Int(truncating: idT1h)); } else { let idT1h = currentDict["temp_c"] as! NSNumber; currentTemp = Float(truncating: idT1h); } } print("todayMinTemp: \(todayMinTemp), todayMaxTemp:\(todayMaxTemp)"); print("todayPop: \(todayPop)"); #if KKH if let currentDict : Dictionary<String, Any> = jsonDict?["current"] as? Dictionary<String, Any>{ //print("currentDict is \(currentDict).") if let currentArpltnDict : Dictionary<String, Any> = currentDict["arpltn"] as? Dictionary<String, Any> { strAirState = watchTWSM.getAirState(currentArpltnDict); // Test //nssAirState = [NSString stringWithFormat:@"통합대기 78 나쁨"]; attrStrAirState = watchTWSM.getChangedColorAirState(strAirState:strAirState); print("[processWeatherResultsWithShowMore] attrStrAirState : \(String(describing: attrStrAirState))"); print("[processWeatherResultsWithShowMore] strAirState : \(String(describing: strAirState))"); } else { print("That currentArpltnDict is not in the jsonDict dictionary.") } } else { print("That currentDict is not in the jsonDict dictionary.") } #endif DispatchQueue.global(qos: .background).async { // Background Thread DispatchQueue.main.async { // Run UI Updates if(strDateTime != nil) { self.updateDateLabel.setText("\(strDateTime!)"); } print("=======> date : \(strDateTime!)"); if( (strAddress == nil) || ( strAddress == "(null)" )) { self.addressLabel.setText(""); } else { self.addressLabel.setText("\(strAddress!)"); } print("=======> strCurImgName : \(strCurImgName!)"); strCurImgName = "MoonBigCloudRainLightning"; if(strCurImgName != nil) { self.curWeatherImage.setImage ( UIImage(named:"Moon"/*strCurImgName!*/) ); print("111=======> strCurImgName : \(strCurImgName!)"); } if(tempUnit == TEMP_UNIT.FAHRENHEIT) { self.curTempLabel.setText( NSString(format: "%d˚", currentTemp) as String ); } else { self.curTempLabel.setText( NSString(format: "%.01f˚", currentTemp) as String); } #if KKH print("[processWeatherResultsWithShowMore] attrStrAirState2 : \(String(describing: attrStrAirState))"); self.airAQILabel.setAttributedText( attrStrAirState ); #endif self.minMaxLabel.setText(NSString(format: "%d˚/ %d˚", todayMinTemp, todayMaxTemp) as String ); self.precLabel.setText(NSString(format: "%d%%", todayPop) as String ); self.airAQILabel.setText(strAirState); //locationView.hidden = false; } } //#endif // Draw ShowMore //[todayWSM processDailyData:jsonDict type:TYPE_REQUEST_WEATHER_KR]; } #endif func setCurJsonDict( dict : Dictionary<String, Any> ) { if(curJsonDict == nil) { curJsonDict = [String : String] () } else { curJsonDict = dict; } } }
ac6ca5f3086db460aa7f84f314dee948
30.706796
122
0.622512
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
WMF Framework/PageIDToURLFetcher.swift
mit
1
import Foundation public final class PageIDToURLFetcher: Fetcher { private let maxNumPageIDs = 50 /// Fetches equivalent page URLs for every pageID passed in. Automatically makes additional calls if number of pageIDs is greater than API maximum (50). public func fetchPageURLs(_ siteURL: URL, pageIDs: [Int], failure: @escaping WMFErrorHandler, success: @escaping ([URL]) -> Void) { guard !pageIDs.isEmpty else { failure(RequestError.invalidParameters) return } let pageIDChunks = pageIDs.chunked(into: maxNumPageIDs) var finalURLs: [URL] = [] var errors: [Error] = [] let group = DispatchGroup() for pageIDChunk in pageIDChunks { group.enter() fetchMaximumPageURLs(siteURL, pageIDs: pageIDChunk) { error in DispatchQueue.main.async { errors.append(error) group.leave() } } success: { urls in DispatchQueue.main.async { finalURLs.append(contentsOf: urls) group.leave() } } } group.notify(queue: .main) { if let error = errors.first { failure(error) } else if finalURLs.isEmpty { failure(RequestError.unexpectedResponse) } else { success(finalURLs) } } } /// Fetches equivalent page URLs for every pageID passed in. Maximum of 50 page IDs allowed. Use fetchPageURLs(siteURL:pageID:failure:success) method if requesting > 50 pageIDs. private func fetchMaximumPageURLs(_ siteURL: URL, pageIDs: [Int], failure: @escaping WMFErrorHandler, success: @escaping ([URL]) -> Void) { guard pageIDs.count <= maxNumPageIDs else { failure(RequestError.invalidParameters) return } var params: [String: AnyObject] = [ "action": "query" as AnyObject, "prop": "info" as AnyObject, "inprop": "url" as AnyObject, "format": "json" as AnyObject ] let stringPageIDs = pageIDs.map { String($0) } params["pageids"] = stringPageIDs.joined(separator: "|") as AnyObject performMediaWikiAPIGET(for: siteURL, with: params, cancellationKey: nil) { (result, response, error) in if let error = error { failure(error) return } guard let result = result else { failure(RequestError.unexpectedResponse) return } guard let query = result["query"] as? [String: Any], let pages = query["pages"] as? [String: AnyObject] else { failure(RequestError.unexpectedResponse) return } var finalURLs: [URL] = [] for (_, value) in pages { guard let fullURLString = value["fullurl"] as? String, let url = URL(string: fullURLString) else { continue } finalURLs.append(url) } success(finalURLs) } } }
dcf3dd65ee194cb777bb8260d9c77e04
33
181
0.539216
false
false
false
false
WeMadeCode/ZXPageView
refs/heads/master
Example/Pods/SwifterSwift/Sources/SwifterSwift/CoreGraphics/CGSizeExtensions.swift
mit
1
// // CGSizeExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/22/16. // Copyright © 2016 SwifterSwift // #if canImport(CoreGraphics) import CoreGraphics #if canImport(UIKit) import UIKit #endif #if canImport(Cocoa) import Cocoa #endif // MARK: - Methods public extension CGSize { /// SwifterSwift: Aspect fit CGSize. /// /// let rect = CGSize(width: 120, height: 80) /// let parentRect = CGSize(width: 100, height: 50) /// let newRect = rect.aspectFit(to: parentRect) /// //newRect.width = 75 , newRect = 50 /// /// - Parameter boundingSize: bounding size to fit self to. /// - Returns: self fitted into given bounding size func aspectFit(to boundingSize: CGSize) -> CGSize { let minRatio = min(boundingSize.width / width, boundingSize.height / height) return CGSize(width: width * minRatio, height: height * minRatio) } /// SwifterSwift: Aspect fill CGSize. /// /// let rect = CGSize(width: 20, height: 120) /// let parentRect = CGSize(width: 100, height: 60) /// let newRect = rect.aspectFit(to: parentRect) /// //newRect.width = 100 , newRect = 60 /// /// - Parameter boundingSize: bounding size to fill self to. /// - Returns: self filled into given bounding size func aspectFill(to boundingSize: CGSize) -> CGSize { let minRatio = max(boundingSize.width / width, boundingSize.height / height) let aWidth = min(width * minRatio, boundingSize.width) let aHeight = min(height * minRatio, boundingSize.height) return CGSize(width: aWidth, height: aHeight) } } // MARK: - Operators public extension CGSize { /// SwifterSwift: Add two CGSize /// /// let sizeA = CGSize(width: 5, height: 10) /// let sizeB = CGSize(width: 3, height: 4) /// let result = sizeA + sizeB /// //result = CGSize(width: 8, height: 14) /// /// - Parameters: /// - lhs: CGSize to add to. /// - rhs: CGSize to add. /// - Returns: The result comes from the addition of the two given CGSize struct. static func + (lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width + rhs.width, height: lhs.height + rhs.height) } /// SwifterSwift: Add a CGSize to self. /// /// let sizeA = CGSize(width: 5, height: 10) /// let sizeB = CGSize(width: 3, height: 4) /// sizeA += sizeB /// //sizeA = CGPoint(width: 8, height: 14) /// /// - Parameters: /// - lhs: self /// - rhs: CGSize to add. static func += (lhs: inout CGSize, rhs: CGSize) { lhs.width += rhs.width lhs.height += rhs.height } /// SwifterSwift: Subtract two CGSize /// /// let sizeA = CGSize(width: 5, height: 10) /// let sizeB = CGSize(width: 3, height: 4) /// let result = sizeA - sizeB /// //result = CGSize(width: 2, height: 6) /// /// - Parameters: /// - lhs: CGSize to subtract from. /// - rhs: CGSize to subtract. /// - Returns: The result comes from the subtract of the two given CGSize struct. static func - (lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width - rhs.width, height: lhs.height - rhs.height) } /// SwifterSwift: Subtract a CGSize from self. /// /// let sizeA = CGSize(width: 5, height: 10) /// let sizeB = CGSize(width: 3, height: 4) /// sizeA -= sizeB /// //sizeA = CGPoint(width: 2, height: 6) /// /// - Parameters: /// - lhs: self /// - rhs: CGSize to subtract. static func -= (lhs: inout CGSize, rhs: CGSize) { lhs.width -= rhs.width lhs.height -= rhs.height } /// SwifterSwift: Multiply two CGSize /// /// let sizeA = CGSize(width: 5, height: 10) /// let sizeB = CGSize(width: 3, height: 4) /// let result = sizeA * sizeB /// //result = CGSize(width: 15, height: 40) /// /// - Parameters: /// - lhs: CGSize to multiply. /// - rhs: CGSize to multiply with. /// - Returns: The result comes from the multiplication of the two given CGSize structs. static func * (lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width * rhs.width, height: lhs.height * rhs.height) } /// SwifterSwift: Multiply a CGSize with a scalar. /// /// let sizeA = CGSize(width: 5, height: 10) /// let result = sizeA * 5 /// //result = CGSize(width: 25, height: 50) /// /// - Parameters: /// - lhs: CGSize to multiply. /// - scalar: scalar value. /// - Returns: The result comes from the multiplication of the given CGSize and scalar. static func * (lhs: CGSize, scalar: CGFloat) -> CGSize { return CGSize(width: lhs.width * scalar, height: lhs.height * scalar) } /// SwifterSwift: Multiply a CGSize with a scalar. /// /// let sizeA = CGSize(width: 5, height: 10) /// let result = 5 * sizeA /// //result = CGSize(width: 25, height: 50) /// /// - Parameters: /// - scalar: scalar value. /// - rhs: CGSize to multiply. /// - Returns: The result comes from the multiplication of the given scalar and CGSize. static func * (scalar: CGFloat, rhs: CGSize) -> CGSize { return CGSize(width: scalar * rhs.width, height: scalar * rhs.height) } /// SwifterSwift: Multiply self with a CGSize. /// /// let sizeA = CGSize(width: 5, height: 10) /// let sizeB = CGSize(width: 3, height: 4) /// sizeA *= sizeB /// //result = CGSize(width: 15, height: 40) /// /// - Parameters: /// - lhs: self. /// - rhs: CGSize to multiply. static func *= (lhs: inout CGSize, rhs: CGSize) { lhs.width *= rhs.width lhs.height *= rhs.height } /// SwifterSwift: Multiply self with a scalar. /// /// let sizeA = CGSize(width: 5, height: 10) /// sizeA *= 3 /// //result = CGSize(width: 15, height: 30) /// /// - Parameters: /// - lhs: self. /// - scalar: scalar value. static func *= (lhs: inout CGSize, scalar: CGFloat) { lhs.width *= scalar lhs.height *= scalar } } #endif
ada2d865f9a007a289da7222b8b00912
31.921875
92
0.566208
false
false
false
false
alblue/swift
refs/heads/master
test/SILOptimizer/definite-init-wrongscope.swift
apache-2.0
3
// RUN: %target-swift-frontend -primary-file %s -Onone -emit-sil -Xllvm \ // RUN: -sil-print-after=raw-sil-inst-lowering -Xllvm \ // RUN: -sil-print-only-functions=$s3del1MC4fromAcA12WithDelegate_p_tKcfc \ // RUN: -Xllvm -sil-print-debuginfo -o /dev/null 2>&1 | %FileCheck %s public protocol DelegateA {} public protocol DelegateB {} public protocol WithDelegate { var delegate: DelegateA? { get } func f() throws -> Int } public enum Err: Swift.Error { case s(Int) } public class C {} public class M { let field: C var value : Int public init(from d: WithDelegate) throws { guard let delegate = d.delegate as? DelegateB else { throw Err.s(0) } self.field = C() let i: Int = try d.f() value = i } } // Make sure the expanded sequence gets the right scope. // CHECK: [[I:%.*]] = integer_literal $Builtin.Int2, 1, loc {{.*}}:20:12, scope 2 // CHECK: [[V:%.*]] = load [trivial] %2 : $*Builtin.Int2, loc {{.*}}:20:12, scope 2 // CHECK: [[OR:%.*]] = builtin "or_Int2"([[V]] : $Builtin.Int2, [[I]] : $Builtin.Int2) : $Builtin.Int2, loc {{.*}}:20:12, scope 2 // CHECK: store [[OR]] to [trivial] %2 : $*Builtin.Int2, loc {{.*}}:20:12, scope 2 // CHECK: store %{{.*}} to [init] %{{.*}} : $*C, loc {{.*}}:23:20, scope 2 // Make sure the dealloc_stack gets the same scope of the instructions surrounding it. // CHECK: destroy_addr %0 : $*WithDelegate, loc {{.*}}:26:5, scope 2 // CHECK: dealloc_stack %2 : $*Builtin.Int2, loc {{.*}}:20:12, scope 2 // CHECK: throw %{{.*}} : $Error, loc {{.*}}:20:12, scope 2
f27edf3fd981cd7f00ae51c75d37f704
37.829268
131
0.593593
false
false
false
false
delbert06/DYZB
refs/heads/master
DYZB/DYZB/HomeViewController.swift
mit
1
// // HomeViewController.swift // DYZB // // Created by 胡迪 on 2016/10/17. // Copyright © 2016年 D.Huhu. All rights reserved. // import UIKit private let ktitleViewH : CGFloat = 40 class HomeViewController: UIViewController { //MARK: -懒加载属性 lazy var pageTitleView:PageTitleView = {[weak self] in let titleFrame = CGRect(x: 0, y: kStautusBarH + kNavigationBarH, width: kScreenW, height: ktitleViewH) let titles = ["推荐","游戏","娱乐","趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) titleView.delegate = self return titleView }() lazy var pageContentView:PageContentView = { let contentH = kScreenH - kStautusBarH - kNavigationBarH - ktitleViewH - kTabbarH let contentFrame = CGRect(x: 0, y: kStautusBarH + kNavigationBarH + ktitleViewH, width: kScreenW, height: contentH) var childVCs = [UIViewController]() childVCs.append(RecommendViewController()) childVCs.append(GameViewController()) childVCs.append(PlayViewController()) let contentView = PageContentView(frame: contentFrame, childVCs: childVCs, parentVC: self) contentView.delegate = self return contentView }() override func viewDidLoad() { super.viewDidLoad() setupUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //MARK: - 设置UI界面 extension HomeViewController{ func setupUI(){ //不需要调整UIScrollView的内边距 automaticallyAdjustsScrollViewInsets = false setNavigationBar() view.addSubview(pageTitleView) view.addSubview(pageContentView) } private func setNavigationBar(){ // 1. 设置左边的item navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") // 2. 创建UICollectionView let size = CGSize(width: 40, height: 40) let his = UIBarButtonItem(imageName: "image_my_history", highImage: "Image_my_history_click", size: size) let scan = UIBarButtonItem(imageName: "Image_scan", highImage: "Image_scan_click", size: size) let search = UIBarButtonItem(imageName: "btn_search", highImage: "btn_search_clicked", size: size) navigationItem.rightBarButtonItems = [his,scan,search] } } //MARK: - 遵守PageTitleView协议 extension HomeViewController:PageTitleViewDelegate{ func pageTitle(titleView: PageTitleView, selectedIndex Index: Int) { pageContentView.setCurrentIndex(currnetIndex: Index) } } extension HomeViewController : PageCollectViewDelegate{ func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
e2a420feb515d2ee7b63d3df13a72386
30.829787
123
0.662099
false
false
false
false
AaronMT/firefox-ios
refs/heads/main
Shared/Logger.swift
mpl-2.0
13
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import XCGLogger public struct Logger {} // MARK: - Singleton Logger Instances public extension Logger { static let logPII = false /// Logger used for recording happenings with Sync, Accounts, Providers, Storage, and Profiles static let syncLogger = RollingFileLogger(filenameRoot: "sync", logDirectoryPath: Logger.logFileDirectoryPath(inDocuments: saveLogsToDocuments)) /// Logger used for recording frontend/browser happenings static let browserLogger = RollingFileLogger(filenameRoot: "browser", logDirectoryPath: Logger.logFileDirectoryPath(inDocuments: saveLogsToDocuments)) /// Logger used for recording interactions with the keychain static let keychainLogger: XCGLogger = Logger.fileLoggerWithName("keychain") /// Logger used for logging database errors such as corruption static let corruptLogger: RollingFileLogger = { let logger = RollingFileLogger(filenameRoot: "corruptLogger", logDirectoryPath: Logger.logFileDirectoryPath(inDocuments: saveLogsToDocuments)) logger.newLogWithDate(Date()) return logger }() /// Save logs to `~/Documents` folder. If this is `true`, the flag is reset in `UserDefaults` so it does not persist to the next launch. static let saveLogsToDocuments: Bool = { let value = UserDefaults.standard.bool(forKey: "SettingsBundleSaveLogsToDocuments") if value { UserDefaults.standard.set(false, forKey: "SettingsBundleSaveLogsToDocuments") } return value }() static func copyPreviousLogsToDocuments() { if let defaultLogDirectoryPath = logFileDirectoryPath(inDocuments: false), let documentsLogDirectoryPath = logFileDirectoryPath(inDocuments: true), let previousLogFiles = try? FileManager.default.contentsOfDirectory(atPath: defaultLogDirectoryPath) { let defaultLogDirectoryURL = URL(fileURLWithPath: defaultLogDirectoryPath, isDirectory: true) let documentsLogDirectoryURL = URL(fileURLWithPath: documentsLogDirectoryPath, isDirectory: true) for previousLogFile in previousLogFiles { let previousLogFileURL = defaultLogDirectoryURL.appendingPathComponent(previousLogFile) let targetLogFileURL = documentsLogDirectoryURL.appendingPathComponent(previousLogFile) try? FileManager.default.copyItem(at: previousLogFileURL, to: targetLogFileURL) } } } /** Return the log file directory path. If the directory doesn't exist, make sure it exist first before returning the path. :returns: Directory path where log files are stored */ static func logFileDirectoryPath(inDocuments: Bool) -> String? { let searchPathDirectory: FileManager.SearchPathDirectory = inDocuments ? .documentDirectory : .cachesDirectory if let targetDirectory = NSSearchPathForDirectoriesInDomains(searchPathDirectory, .userDomainMask, true).first { let logsDirectory = "\(targetDirectory)/Logs" if !FileManager.default.fileExists(atPath: logsDirectory) { do { try FileManager.default.createDirectory(atPath: logsDirectory, withIntermediateDirectories: true, attributes: nil) return logsDirectory } catch _ as NSError { return nil } } else { return logsDirectory } } return nil } static private func fileLoggerWithName(_ name: String) -> XCGLogger { let log = XCGLogger() if let logFileURL = urlForLogNamed(name) { let fileDestination = FileDestination( owner: log, writeToFile: logFileURL.absoluteString, identifier: "com.mozilla.firefox.filelogger.\(name)" ) log.add(destination: fileDestination) } return log } static private func urlForLogNamed(_ name: String) -> URL? { guard let logDir = Logger.logFileDirectoryPath(inDocuments: saveLogsToDocuments) else { return nil } return URL(string: "\(logDir)/\(name).log") } }
d0826032f4de9a5af463dd4c101f6e11
44.122449
154
0.683401
false
false
false
false
wilfreddekok/Antidote
refs/heads/master
Antidote/LoginCreatePasswordController.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 protocol LoginCreatePasswordControllerDelegate: class { func loginCreatePasswordController(controller: LoginCreatePasswordController, password: String) } class LoginCreatePasswordController: LoginGenericCreateController { weak var delegate: LoginCreatePasswordControllerDelegate? override func configureViews() { titleLabel.text = String(localized: "set_password_title") firstTextField.placeholder = String(localized: "password") firstTextField.secureTextEntry = true firstTextField.hint = String(localized: "set_password_hint") secondTextField.placeholder = String(localized: "repeat_password") secondTextField.secureTextEntry = true bottomButton.setTitle(String(localized: "create_account_go_button"), forState: .Normal) } override func bottomButtonPressed() { guard let first = firstTextField.text, let second = secondTextField.text else { handleErrorWithType(.PasswordIsEmpty) return } guard !first.isEmpty && !second.isEmpty else { handleErrorWithType(.PasswordIsEmpty) return } guard first == second else { handleErrorWithType(.PasswordsDoNotMatch) return } delegate?.loginCreatePasswordController(self, password: first) } }
d8799698cb065c191d6f9206d43997d8
33.434783
99
0.691919
false
false
false
false
hawkfalcon/Clients
refs/heads/master
Clients/ViewControllers/ClientInfoViewController.swift
mit
1
import UIKit import Contacts import ContactsUI import CoreData class ClientInfoViewController: UITableViewController { var sections = [String]() var dataContext: NSManagedObjectContext! var client: Client! // MARK: - Setup override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self var title = "New Contact" sections = ["Contact", "Categories", "Driving", "Other"] if !Settings.enabledMileage { sections.remove(at: 2) } if let client = client { if let first = client.firstName, let last = client.lastName { title = "\(first) \(last)" } for category in client.categories! { let category = category as! Category sections.insert(category.name!, at: 2) } } else { client = Client(context: dataContext) client.timestamp = NSDate() client.notes = "" client.firstName = "First" client.lastName = "Last" } navigationItem.title = title dataContext.saveChanges() } override func viewWillAppear(_ animated: Bool) { tableView.reloadData() client!.complete = client.owed() == 0.0 dataContext.saveChanges() super.viewWillAppear(animated) } // MARK: - Populate data override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let section = indexPath.section var cell: UITableViewCell if sections[section] == "Other" { cell = createNotesCell(indexPath: indexPath) } else if isCategory(section) { cell = createPaymentCell(section: section, indexPath: indexPath) } else { cell = createInfoCell(section: sections[section], indexPath: indexPath) } return cell } func createNotesCell(indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "NotesCell", for: indexPath) as! TextInputCell cell.textLabel?.text = "Notes" if let notes = client.notes { cell.textField.text = notes } cell.detailTextLabel?.lineBreakMode = .byWordWrapping; cell.detailTextLabel?.numberOfLines = 0; cell.textField.delegate = self cell.textField.addTarget(self, action: #selector(fieldDidChange), for: .editingChanged) cell.textField.placeholder = "Notes..." cell.textField.isEnabled = true cell.textField.keyboardType = .default cell.textField.frame.size.height = cell.frame.size.height * (9 / 10) return cell } func createPaymentCell(section: Int, indexPath: IndexPath) -> UITableViewCell { let last = tableView.numberOfRows(inSection: indexPath.section) - 1 if indexPath.row == last { let cell = tableView.dequeueReusableCell(withIdentifier: "NewPaymentCell", for: indexPath) as! NewPaymentCell cell.configure(type: "Payment") return cell } else { let category = client.category(section: section)! let identifier = indexPath.row == 0 ? "PaymentTotalCell" : "PaymentCell" let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! PaymentDataCell if indexPath.row == 0 { configure(cell, for: category) } else { let payment = category.payments!.object(at: indexPath.row - 1) as! Payment cell.paymentField.text = payment.name cell.valueField.text = "\(payment.value.currency)" cell.valueField.isEnabled = false } cell.addTargets(viewController: self) return cell } } func configure(_ cell: PaymentDataCell, for category: Category) { let leftLabel = UILabel() leftLabel.text = "Total: " leftLabel.textAlignment = .right leftLabel.font = UIFont.boldSystemFont(ofSize: 16) leftLabel.sizeToFit() cell.valueField.leftView = leftLabel cell.valueField.leftViewMode = .unlessEditing cell.paymentField.text = category.name cell.paymentField.isEnabled = false cell.paymentField.font = UIFont.boldSystemFont(ofSize: 16) cell.valueField.text = "\(category.total.currency)" cell.valueField.sizeToFit() cell.backgroundColor = UIColor.lightText cell.selectionStyle = .none cell.accessoryType = .none } func createInfoCell(section: String, indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell", for: indexPath) var title = "" var value = "" switch section { case "Contact": title = navigationItem.title! if (title == "New Contact") { title = "Choose a Contact" } value = "Go to Contact" case "Driving": title = "Miles Driven" //TODO recalcuate on segue from Mileage var mileTotal: Double = 0.0 for mile in client.mileage! { let mile = mile as! Mileage mileTotal += mile.miles } value = "\(mileTotal)" case "Categories": if client.categories!.count == 0 { title = "Add a Category +" } default: print("?") } if section == "Contact" || section == "Driving" { cell.selectionStyle = .default cell.accessoryType = .disclosureIndicator } else { cell.accessoryType = .none cell.selectionStyle = .none } cell.textLabel?.text = title cell.detailTextLabel?.text = value return cell } // MARK: - Tapped on cell override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let cell = tableView.cellForRow(at: indexPath)! as UITableViewCell if let text = cell.detailTextLabel?.text, text == "Go to Contact" { if let contact = client.contact { loadContact(identifier: contact) } else { showContactsPicker() } } else if let text = cell.textLabel?.text, text == "Miles Driven" { performSegue(withIdentifier: "toMiles", sender: nil) } else if let text = cell.textLabel?.text, text == "Add a Category +" { performSegue(withIdentifier: "addCategory", sender: nil) } else if cell is NewPaymentCell { let category = client.category(section: indexPath.section) let payment = Payment(context: dataContext) payment.name = Settings.defaultPaymentNames[0] payment.type = Settings.defaultPaymentType payment.value = 0.0 payment.date = NSDate() category?.addToPayments(payment) dataContext.saveChanges() tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) self.performSegue(withIdentifier: "toPayment", sender: self) } else { if let textCell = cell as? TextInputCell, textCell.textField != nil { textCell.textField.becomeFirstResponder() } } } // MARK: - Setup layout override func numberOfSections(in tableView: UITableView) -> Int { return sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if isCategory(section) { let category = client.category(section: section)! return category.payments!.count + 2 } return 1 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let category = sections[section] if isCategory(section) { return nil } return category } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let section = sections[indexPath.section] switch section { case "Other": return 150.0 case "Categories": if client.categories!.count == 0 { return 55.0 } return 0 case "Driving": return 55.0 case "Contact": return 55.0 default: if indexPath.row == 0 { return 35.0 } return 55.0 } } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { if isCategory(indexPath.section) && indexPath.row == 0 { return nil } return indexPath } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { let category = sections[section] if isCategory(section) || category == "Categories" { return 0.0001 } return 18.0; } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let category = sections[section] if isCategory(section) { return 0.0001 } else if category == "Contact" || category == "Driving" || (category == "Other" && !Settings.enabledMileage) { return 36.0 } return 18.0; } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { let last = tableView.numberOfRows(inSection: indexPath.section) - 1 if isCategory(indexPath.section) && indexPath.row != last { return true } return false } override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { tableView.endEditing(true) } // MARK: - Allow deletion override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { tableView.beginUpdates() if indexPath.row == 0 { client.removeFromCategories(at: indexPath.section - 2) sections.remove(at: 2) tableView.deleteSections([indexPath.section], with: .automatic) if client.categories!.count == 0 { let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 1)) cell!.textLabel!.text = "Add a Category +" } } else { let category = client.category(section: indexPath.section)! category.removeFromPayments(at: indexPath.row - 1) tableView.deleteRows(at: [indexPath], with: .automatic) } dataContext.saveChanges() tableView.endUpdates() } } // MARK: - Return from new category @IBAction func unwindAndAddCategory(_ segue: UIStoryboardSegue) { let source = segue.source as! NewCategoryViewController let category = Category(context: dataContext) category.name = source.name category.total = source.total client.addToCategories(category) dataContext.saveChanges() sections.insert(category.name!, at: 2) tableView.reloadData() } @IBAction func unwindToClient(_ segue: UIStoryboardSegue) { //Cancelled } // Prepare to edit client or go to mileage override func prepare(for segue: UIStoryboardSegue, sender: Any!) { if let id = segue.identifier { if id == "toMiles", let destination = segue.destination as? MileageTableViewController { destination.mileage = client.mileage! destination.client = client destination.dataContext = dataContext } else if id == "toPayment", let destination = segue.destination as? PaymentInfoViewController { if let index = tableView.indexPathForSelectedRow { let category = client.category(section: index.section)! let payment = category.payments!.object(at: index.row - 1) as! Payment destination.payment = payment } } } } func isCategory(_ section: Int) -> Bool { return section > 1 && section < client.categories!.count + 2 } } extension NSManagedObjectContext { func saveChanges() { if self.hasChanges { do { try self.save() } catch { print("An error occurred while saving: \(error)") } } } } extension ClientInfoViewController: UITextFieldDelegate { // Allow editing in place func fieldDidChange(_ textField: UITextField) { if let name = textField.placeholder, let cell = textField.superview?.superview as? UITableViewCell, let indexPath = tableView.indexPath(for: cell), let text = textField.text { if name == "Notes..." { client.notes = text } else if let category = client.category(section: indexPath.section) { if indexPath.row > 0 { let payment = category.payments!.object(at: indexPath.row - 1) as! Payment if name == "Name" { payment.name = text } else if let value = text.rawDouble { payment.value = value } } else if let value = text.rawDouble { category.total = value } } dataContext.saveChanges() } } // Setup reponse func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } func textFieldDidEndEditing(_ textField: UITextField) { if let money = textField.text?.rawDouble { textField.text = money.currency } } /*func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { return range.length < 1 || range.location + range.length > 1 }*/ } extension ClientInfoViewController: CNContactPickerDelegate { func loadContact(identifier: String) { do { let contact = try CNContactStore().unifiedContact(withIdentifier: identifier, keysToFetch: [CNContactViewController.descriptorForRequiredKeys()]) let viewController = CNContactViewController(for: contact) viewController.contactStore = CNContactStore() viewController.delegate = self self.navigationController?.pushViewController(viewController, animated: true) } catch { print("Can't load contact") } } func showContactsPicker() { let contactPicker = CNContactPickerViewController() contactPicker.delegate = self; // TODO: fix predicate // let predicate = NSPredicate(format: "phoneNumbers.@count > 0") // contactPicker.predicateForEnablingContact = predicate self.present(contactPicker, animated: true, completion: nil) } } extension ClientInfoViewController: CNContactViewControllerDelegate { func contactPicker(_ picker: CNContactPickerViewController, didSelect contactSelected: CNContact) { client.contact = contactSelected.identifier client.firstName = contactSelected.givenName client.lastName = contactSelected.familyName dataContext.saveChanges() navigationItem.title = "\(contactSelected.givenName) \(contactSelected.familyName)" } } extension Client { func category(section: Int) -> Category? { return self.categories!.object(at: section - 2) as? Category } } extension Double { var currency: String { let formatter = NumberFormatter() formatter.numberStyle = .currency return formatter.string(from: NSNumber(value: self))! } } extension String { var rawDouble: Double? { var raw = self.replacingOccurrences(of: "$", with: "") raw = raw.replacingOccurrences(of: ",", with: "") return Double(raw) } }
86cfc2e00ba980b9583f5e3ac4b64f60
34.033755
157
0.594424
false
false
false
false
Bunn/firefox-ios
refs/heads/master
Account/SyncAuthState.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger import SwiftyJSON private let CurrentSyncAuthStateCacheVersion = 1 private let log = Logger.syncLogger public struct SyncAuthStateCache { let token: TokenServerToken let forKey: Data let expiresAt: Timestamp } public protocol SyncAuthState { func invalidate() func token(_ now: Timestamp, canBeExpired: Bool) -> Deferred<Maybe<(token: TokenServerToken, forKey: Data)>> var deviceID: String? { get } var enginesEnablements: [String: Bool]? { get set } var clientName: String? { get set } } public func syncAuthStateCachefromJSON(_ json: JSON) -> SyncAuthStateCache? { if let version = json["version"].int { if version != CurrentSyncAuthStateCacheVersion { log.warning("Sync Auth State Cache is wrong version; dropping.") return nil } if let token = TokenServerToken.fromJSON(json["token"]), let forKey = json["forKey"].string?.hexDecodedData, let expiresAt = json["expiresAt"].int64 { return SyncAuthStateCache(token: token, forKey: forKey, expiresAt: Timestamp(expiresAt)) } } return nil } extension SyncAuthStateCache: JSONLiteralConvertible { public func asJSON() -> JSON { return JSON([ "version": CurrentSyncAuthStateCacheVersion, "token": token.asJSON(), "forKey": forKey.hexEncodedString, "expiresAt": NSNumber(value: expiresAt), ] as NSDictionary) } } open class FirefoxAccountSyncAuthState: SyncAuthState { fileprivate let account: FirefoxAccount fileprivate let cache: KeychainCache<SyncAuthStateCache> public var deviceID: String? { return account.deviceRegistration?.id } public var enginesEnablements: [String: Bool]? public var clientName: String? init(account: FirefoxAccount, cache: KeychainCache<SyncAuthStateCache>) { self.account = account self.cache = cache } // If a token gives you a 401, invalidate it and request a new one. open func invalidate() { log.info("Invalidating cached token server token.") self.cache.value = nil } // Generate an assertion and try to fetch a token server token, retrying at most a fixed number // of times. // // It's tricky to get Swift to recurse into a closure that captures from the environment without // segfaulting the compiler, so we pass everything around, like barbarians. fileprivate func generateAssertionAndFetchTokenAt(_ audience: String, client: TokenServerClient, clientState: String?, married: MarriedState, now: Timestamp, retryCount: Int) -> Deferred<Maybe<TokenServerToken>> { let assertion = married.generateAssertionForAudience(audience, now: now) return client.token(assertion, clientState: clientState).bind { result in if retryCount > 0 { if let tokenServerError = result.failureValue as? TokenServerError { switch tokenServerError { case let .remote(code, status, remoteTimestamp) where code == 401 && status == "invalid-timestamp": if let remoteTimestamp = remoteTimestamp { let skew = Int64(remoteTimestamp) - Int64(now) // Without casts, runtime crash due to overflow. log.info("Token server responded with 401/invalid-timestamp: retrying with remote timestamp \(remoteTimestamp), which is local timestamp + skew = \(now) + \(skew).") return self.generateAssertionAndFetchTokenAt(audience, client: client, clientState: clientState, married: married, now: remoteTimestamp, retryCount: retryCount - 1) } default: break } } } // Fall-through. return Deferred(value: result) } } open func token(_ now: Timestamp, canBeExpired: Bool) -> Deferred<Maybe<(token: TokenServerToken, forKey: Data)>> { if let value = cache.value { // Give ourselves some room to do work. let isExpired = value.expiresAt < now + 5 * OneMinuteInMilliseconds if canBeExpired { if isExpired { log.info("Returning cached expired token.") } else { log.info("Returning cached token, which should be valid.") } return deferMaybe((token: value.token, forKey: value.forKey)) } if !isExpired { log.info("Returning cached token, which should be valid.") return deferMaybe((token: value.token, forKey: value.forKey)) } } log.debug("Advancing Account state.") return account.marriedState().bind { result in if let married = result.successValue { log.info("Account is in Married state; generating assertion.") let tokenServerEndpointURL = self.account.configuration.sync15Configuration.tokenServerEndpointURL let audience = TokenServerClient.getAudience(forURL: tokenServerEndpointURL) let client = TokenServerClient(url: tokenServerEndpointURL) let clientState = married.kXCS log.debug("Fetching token server token.") let deferred = self.generateAssertionAndFetchTokenAt(audience, client: client, clientState: clientState, married: married, now: now, retryCount: 1) deferred.upon { result in // This could race to update the cache with multiple token results. // One racer will win -- that's fine, presumably she has the freshest token. // If not, that's okay, 'cuz the slightly dated token is still a valid token. if let token = result.successValue { let newCache = SyncAuthStateCache(token: token, forKey: married.kSync, expiresAt: now + 1000 * token.durationInSeconds) log.debug("Fetched token server token! Token expires at \(newCache.expiresAt).") self.cache.value = newCache } } return chain(deferred, f: { (token: $0, forKey: married.kSync) }) } return deferMaybe(result.failureValue!) } } }
d1cc62665ac8c6af3d25a90f32b00fe0
45.052632
193
0.595429
false
false
false
false
mckaskle/FlintKit
refs/heads/master
FlintKit/UIKit/NetworkActivityIndicatorManager.swift
mit
1
// // MIT License // // NetworkActivityIndicatorManager.swift // // Copyright (c) 2016 Devin McKaskle // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import UIKit @available(iOS 10.0, *) @available(iOSApplicationExtension, unavailable) public final class NetworkActivityIndicatorManager { // MARK: - Enum private enum State { case notActive, delayingStart, active, delayingEnd } // MARK: - Object Lifecycle init(application: UIApplication) { self.application = application } // MARK: - Public Properties static public let shared = NetworkActivityIndicatorManager(application: .shared) public private(set) var activityCount = 0 { didSet { switch state { case .notActive: if activityCount > 0 { state = .delayingStart } case .delayingStart: // No-op, let the timer finish. break case .active: if activityCount <= 0 { state = .delayingEnd } case .delayingEnd: if activityCount > 0 { state = .active } } } } // MARK: - Public Methods public func incrementActivityCount() { let f = { self.activityCount += 1 } if Thread.isMainThread { f() } else { DispatchQueue.main.async(execute: f) } } public func decrementActivityCount() { let f = { self.activityCount = max(0, self.activityCount - 1) } if Thread.isMainThread { f() } else { DispatchQueue.main.async(execute: f) } } // MARK: - Private Properties private let application: UIApplication private var startTimer: Timer? private var endTimer: Timer? private var state: State = .notActive { didSet { switch state { case .notActive: startTimer?.invalidate() endTimer?.invalidate() application.isNetworkActivityIndicatorVisible = false case .delayingStart: // Apple's HIG describes the following: // > Display the network activity indicator to provide feedback when your app accesses // > the network for more than a couple of seconds. If the operation finishes sooner // > than that, you don’t have to show the network activity indicator, because the // > indicator is likely to disappear before users notice its presence. startTimer = .scheduledTimer(withTimeInterval: 1, repeats: false) { [weak self] _ in guard let s = self else { return } s.state = s.activityCount > 0 ? .active : .notActive } case .active: endTimer?.invalidate() application.isNetworkActivityIndicatorVisible = true case .delayingEnd: endTimer?.invalidate() // Delay hiding the indicator so that if multiple requests are happening one after another, // there is one continuous showing of the network indicator. endTimer = .scheduledTimer(withTimeInterval: 0.17, repeats: false) { [weak self] _ in self?.state = .notActive } } } } }
f703a44d50359d8e90ff3d174381f2da
28.70922
99
0.650036
false
false
false
false
flodolo/firefox-ios
refs/heads/main
Client/Frontend/Home/RecentlySaved/RecentlySavedCell.swift
mpl-2.0
2
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import Foundation import Storage /// A cell used in FxHomeScreen's Recently Saved section. It holds bookmarks and reading list items. class RecentlySavedCell: UICollectionViewCell, ReusableCell { private struct UX { static let bookmarkTitleFontSize: CGFloat = 12 static let containerSpacing: CGFloat = 16 static let heroImageSize: CGSize = CGSize(width: 126, height: 82) static let fallbackFaviconSize = CGSize(width: 36, height: 36) static let generalSpacing: CGFloat = 8 } // MARK: - UI Elements private var rootContainer: UIView = .build { view in view.backgroundColor = .clear view.layer.cornerRadius = HomepageViewModel.UX.generalCornerRadius } // Contains the hero image and fallback favicons private var imageContainer: UIView = .build { view in view.backgroundColor = .clear } let heroImageView: UIImageView = .build { imageView in imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.layer.masksToBounds = true imageView.layer.cornerRadius = HomepageViewModel.UX.generalCornerRadius } // Used as a fallback if hero image isn't set private let fallbackFaviconImage: UIImageView = .build { imageView in imageView.contentMode = .scaleAspectFit imageView.clipsToBounds = true imageView.backgroundColor = .clear imageView.layer.cornerRadius = HomepageViewModel.UX.generalIconCornerRadius imageView.layer.masksToBounds = true } private var fallbackFaviconBackground: UIView = .build { view in view.layer.cornerRadius = HomepageViewModel.UX.generalCornerRadius view.layer.borderWidth = HomepageViewModel.UX.generalBorderWidth } let itemTitle: UILabel = .build { label in label.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .body, size: UX.bookmarkTitleFontSize) label.adjustsFontForContentSizeCategory = true } // MARK: - Inits override init(frame: CGRect) { super.init(frame: .zero) setupLayout() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() heroImageView.image = nil fallbackFaviconImage.image = nil itemTitle.text = nil setFallBackFaviconVisibility(isHidden: false) } override func layoutSubviews() { super.layoutSubviews() rootContainer.layer.shadowPath = UIBezierPath(roundedRect: rootContainer.bounds, cornerRadius: HomepageViewModel.UX.generalCornerRadius).cgPath } func configure(viewModel: RecentlySavedCellViewModel, theme: Theme) { configureImages(heroImage: viewModel.heroImage, favIconImage: viewModel.favIconImage) itemTitle.text = viewModel.site.title applyTheme(theme: theme) } private func configureImages(heroImage: UIImage?, favIconImage: UIImage?) { if heroImage == nil { // Sets a small favicon in place of the hero image in case there's no hero image fallbackFaviconImage.image = favIconImage } else if heroImage?.size.width == heroImage?.size.height { // If hero image is a square use it as a favicon fallbackFaviconImage.image = heroImage } else { setFallBackFaviconVisibility(isHidden: true) heroImageView.image = heroImage } } private func setFallBackFaviconVisibility(isHidden: Bool) { fallbackFaviconBackground.isHidden = isHidden fallbackFaviconImage.isHidden = isHidden heroImageView.isHidden = !isHidden } // MARK: - Helpers private func setupLayout() { contentView.backgroundColor = .clear fallbackFaviconBackground.addSubviews(fallbackFaviconImage) imageContainer.addSubviews(heroImageView, fallbackFaviconBackground) rootContainer.addSubviews(imageContainer, itemTitle) contentView.addSubview(rootContainer) NSLayoutConstraint.activate([ rootContainer.topAnchor.constraint(equalTo: contentView.topAnchor), rootContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), rootContainer.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), rootContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), // Image container, hero image and fallback imageContainer.topAnchor.constraint(equalTo: rootContainer.topAnchor, constant: UX.containerSpacing), imageContainer.leadingAnchor.constraint(equalTo: rootContainer.leadingAnchor, constant: UX.containerSpacing), imageContainer.trailingAnchor.constraint(equalTo: rootContainer.trailingAnchor, constant: -UX.containerSpacing), imageContainer.heightAnchor.constraint(equalToConstant: UX.heroImageSize.height), imageContainer.widthAnchor.constraint(equalToConstant: UX.heroImageSize.width), heroImageView.topAnchor.constraint(equalTo: imageContainer.topAnchor), heroImageView.leadingAnchor.constraint(equalTo: imageContainer.leadingAnchor), heroImageView.trailingAnchor.constraint(equalTo: imageContainer.trailingAnchor), heroImageView.bottomAnchor.constraint(equalTo: imageContainer.bottomAnchor), itemTitle.topAnchor.constraint(equalTo: heroImageView.bottomAnchor, constant: UX.generalSpacing), itemTitle.leadingAnchor.constraint(equalTo: heroImageView.leadingAnchor), itemTitle.trailingAnchor.constraint(equalTo: heroImageView.trailingAnchor), itemTitle.bottomAnchor.constraint(equalTo: rootContainer.bottomAnchor, constant: -UX.generalSpacing), fallbackFaviconBackground.centerXAnchor.constraint(equalTo: imageContainer.centerXAnchor), fallbackFaviconBackground.centerYAnchor.constraint(equalTo: imageContainer.centerYAnchor), fallbackFaviconBackground.heightAnchor.constraint(equalToConstant: UX.heroImageSize.height), fallbackFaviconBackground.widthAnchor.constraint(equalToConstant: UX.heroImageSize.width), fallbackFaviconImage.heightAnchor.constraint(equalToConstant: UX.fallbackFaviconSize.height), fallbackFaviconImage.widthAnchor.constraint(equalToConstant: UX.fallbackFaviconSize.width), fallbackFaviconImage.centerXAnchor.constraint(equalTo: fallbackFaviconBackground.centerXAnchor), fallbackFaviconImage.centerYAnchor.constraint(equalTo: fallbackFaviconBackground.centerYAnchor), itemTitle.topAnchor.constraint(equalTo: heroImageView.bottomAnchor, constant: UX.generalSpacing), itemTitle.leadingAnchor.constraint(equalTo: heroImageView.leadingAnchor), itemTitle.trailingAnchor.constraint(equalTo: heroImageView.trailingAnchor), itemTitle.bottomAnchor.constraint(equalTo: rootContainer.bottomAnchor, constant: -UX.generalSpacing) ]) } private func setupShadow(theme: Theme) { rootContainer.layer.shadowPath = UIBezierPath(roundedRect: rootContainer.bounds, cornerRadius: HomepageViewModel.UX.generalCornerRadius).cgPath rootContainer.layer.shadowColor = theme.colors.shadowDefault.cgColor rootContainer.layer.shadowOpacity = HomepageViewModel.UX.shadowOpacity rootContainer.layer.shadowOffset = HomepageViewModel.UX.shadowOffset rootContainer.layer.shadowRadius = HomepageViewModel.UX.shadowRadius } } // MARK: - ThemeApplicable extension RecentlySavedCell: ThemeApplicable { func applyTheme(theme: Theme) { itemTitle.textColor = theme.colors.textPrimary fallbackFaviconBackground.backgroundColor = theme.colors.layer1 fallbackFaviconBackground.layer.borderColor = theme.colors.layer1.cgColor adjustBlur(theme: theme) } } // MARK: - Blurrable extension RecentlySavedCell: Blurrable { func adjustBlur(theme: Theme) { // If blur is disabled set background color if shouldApplyWallpaperBlur { rootContainer.addBlurEffectWithClearBackgroundAndClipping(using: .systemThickMaterial) } else { rootContainer.removeVisualEffectView() rootContainer.backgroundColor = theme.colors.layer5 setupShadow(theme: theme) } } }
034f49d642694030935d74f0665f96bc
44.133005
116
0.68413
false
false
false
false
aquarchitect/MyKit
refs/heads/master
Sources/iOS/Extensions/UIKit/UICollectionViewFlowLayout+.swift
mit
1
// // UICollectionViewFlowLayout+.swift // MyKit // // Created by Hai Nguyen. // Copyright (c) 2017 Hai Nguyen. // import UIKit public extension UICollectionViewFlowLayout { func delegateInsetForSection(at section: Int) -> UIEdgeInsets? { guard let collectionView = self.collectionView else { return nil } return collectionView.delegate .flatMap({ $0 as? UICollectionViewDelegateFlowLayout })? .collectionView?(collectionView, layout: self, insetForSectionAt: section) } func delegateMinimumLineSpacingForSection(at section: Int) -> CGFloat? { guard let collectionView = self.collectionView else { return nil } return collectionView.delegate .flatMap({ $0 as? UICollectionViewDelegateFlowLayout })? .collectionView?(collectionView, layout: self, minimumLineSpacingForSectionAt: section) } func delegateMinimumInteritemSpacingForSection(at section: Int) -> CGFloat? { guard let collectionView = self.collectionView else { return nil } return collectionView.delegate .flatMap({ $0 as? UICollectionViewDelegateFlowLayout })? .collectionView?(collectionView, layout: self, minimumInteritemSpacingForSectionAt: section) } func delegateReferenceSizeForHeader(in section: Int) -> CGSize? { guard let collectionView = self.collectionView else { return nil } return collectionView.delegate .flatMap({ $0 as? UICollectionViewDelegateFlowLayout })? .collectionView?(collectionView, layout: self, referenceSizeForHeaderInSection: section) } func delegateReferenceSizeForFooter(in section: Int) -> CGSize? { guard let collectionView = self.collectionView else { return nil } return collectionView.delegate .flatMap({ $0 as? UICollectionViewDelegateFlowLayout })? .collectionView?(collectionView, layout: self, referenceSizeForFooterInSection: section) } func delegateSizeForCell(at indexPath: IndexPath) -> CGSize? { guard let collectionView = self.collectionView else { return nil } return collectionView.delegate .flatMap({ $0 as? UICollectionViewDelegateFlowLayout })? .collectionView?(collectionView, layout: self, sizeForItemAt: indexPath) } } public extension UICollectionViewFlowLayout { /// Return an estimated number of elements that are visible /// in bounds by using known layout attributes including item size, /// section insets, spacing, and scroll direction. /// /// - Warning: the calculation is only capable of simple flow layout. @available(*, deprecated) var estimatedNumberOfVisibleElements: Int { guard let collectionView = self.collectionView else { return 0 } switch self.scrollDirection { case .vertical: return Int((collectionView.bounds.height - self.sectionInset.vertical + self.minimumLineSpacing) / (self.itemSize.height + self.minimumLineSpacing)) case .horizontal: return Int((collectionView.bounds.width - self.sectionInset.horizontal + self.minimumLineSpacing) / (self.itemSize.width + self.minimumInteritemSpacing)) } } }
86abd95c57b46490ce8bb772032659a7
40.2
165
0.68932
false
false
false
false
philipgreat/b2b-swift-app
refs/heads/master
B2BSimpleApp/B2BSimpleApp/ProcessingRemoteManagerImpl.swift
mit
1
//Domain B2B/Processing/ import SwiftyJSON import Alamofire import ObjectMapper class ProcessingRemoteManagerImpl:RemoteManagerImpl,CustomStringConvertible{ override init(){ //lazy load for all the properties //This is good for UI applications as it might saves RAM which is very expensive in mobile devices } override var remoteURLPrefix:String{ //Every manager need to config their own URL return "https://philipgreat.github.io/naf/processingManager/" } func loadProcessingDetail(processingId:String, processingSuccessAction: (Processing)->String, processingErrorAction: (String)->String){ let methodName = "loadProcessingDetail" let parameters = [processingId] let url = compositeCallURL(methodName, parameters: parameters) Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) if let processing = self.extractProcessingFromJSON(json){ processingSuccessAction(processing) } } case .Failure(let error): print(error) processingErrorAction("\(error)") } } } func extractProcessingFromJSON(json:JSON) -> Processing?{ let jsonTool = SwiftyJSONTool() let processing = jsonTool.extractProcessing(json) return processing } //Confirming to the protocol CustomStringConvertible of Foundation var description: String{ //Need to find out a way to improve this method performance as this method might called to //debug or log, using + is faster than \(var). let result = "ProcessingRemoteManagerImpl, V1" return result } static var CLASS_VERSION = 1 //This value is for serializer like message pack to identify the versions match between //local and remote object. } //Reference http://grokswift.com/simple-rest-with-swift/ //Reference https://github.com/SwiftyJSON/SwiftyJSON //Reference https://github.com/Alamofire/Alamofire //Reference https://github.com/Hearst-DD/ObjectMapper //let remote = RemoteManagerImpl() //let result = remote.compositeCallURL(methodName: "getDetail",parameters:["O0000001"]) //print(result)
0037b3573658fbe25735e335211b1192
26.207317
100
0.697363
false
false
false
false
aschwaighofer/swift
refs/heads/master
test/IRGen/address_sanitizer_recover.swift
apache-2.0
5
// RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-recover=address %s | %FileCheck %s -check-prefix=ASAN_RECOVER // RUN: %target-swift-frontend -emit-ir -sanitize=address %s | %FileCheck %s -check-prefix=ASAN_NO_RECOVER // RUN: %target-swift-frontend -emit-ir -sanitize-recover=address %s | %FileCheck %s -check-prefix=NO_ASAN_RECOVER // ASAN_RECOVER: declare void @__asan_loadN_noabort( // ASAN_NO_RECOVER: declare void @__asan_loadN( let size:Int = 128; let x = UnsafeMutablePointer<UInt8>.allocate(capacity: size) x.initialize(repeating: 0, count: size) x.advanced(by: 0).pointee = 5; print("Read first element:\(x.advanced(by: 0).pointee)") x.deallocate(); // There should be no ASan instrumentation in this case. // NO_ASAN_RECOVER-NOT: declare void @__asan_load
689f95ddf03a5cb8900a7455ed92c408
48.3125
129
0.727503
false
false
false
false
samwyndham/DictateSRS
refs/heads/master
DictateSRS/Shared/AlertPresenter.swift
mit
1
// // AlertPresenter.swift // DictateSRS // // Created by Sam Wyndham on 30/01/2017. // Copyright © 2017 Sam Wyndham. All rights reserved. // import UIKit /// Presents `UIAlertController`s without needing a `UIViewController` to /// present from class AlertPresenter { private var window: UIWindow? = nil /// Displays given `UIAlertController` in a new `UIWindow` /// /// Creates a window at `UIWindowLevelAlert` level and displays the given /// alert before destroying the window. If an alert is already displaying /// presenting a new alert does nothing. func presentAlert(_ alert: UIAlertController) { guard self.window == nil else { print("Attemped to show alert when existing alert is displayed") return } let vc = AlertPresenterViewController() vc.view.backgroundColor = UIColor.clear vc.didDismiss = { [unowned self] in self.window = nil } let window = UIWindow(frame: UIScreen.main.bounds) window.windowLevel = UIWindowLevelAlert window.backgroundColor = UIColor.clear window.rootViewController = vc window.makeKeyAndVisible() self.window = window window.rootViewController!.present(alert, animated: true, completion: nil) } } private class AlertPresenterViewController: UIViewController { var didDismiss: (() -> Void)? = nil override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { super.dismiss(animated: flag) { [unowned self] in completion?() self.didDismiss?() } } }
72334b5db999407a352a4496b9b00598
30.566038
82
0.633592
false
false
false
false
ray3132138/TestKitchen_1606
refs/heads/master
TestKitchen/TestKitchen/classes/common/Const.swift
mit
1
// // Const.swift // TestKitchen // // Created by qianfeng on 16/8/16. // Copyright © 2016年 ray. All rights reserved. // import UIKit //屏幕的宽度和高度 public let kScreenWidth = UIScreen.mainScreen().bounds.size.width public let kScreenHeight = UIScreen.mainScreen().bounds.size.height //首页推荐点击事件的类型 //接口 //大部分是Post请求 public let kHostUrl = "http://api.izhangchu.com/?appVersion=4.5&sysVersion=9.3.2&devModel=iPhone" //一、食谱 //1、推荐 //首页推荐参数 //methodName=SceneHome&token=&user_id=&version=4.5 //1)广告 //广告详情 //methodName=CourseSeriesView&series_id=22&token=&user_id=&version=4.32 //广告分享 //methodName=AppShare&shareID=&shareModule=course&token=&user_id=&version=4.32 //评论 //methodName=CommentList&page=1&relate_id=22&size=10&token=&type=2&user_id=&version=4.32 //methodName=CommentList&page=2&relate_id=22&size=10&token=&type=2&user_id=&version=4.32 //评论发送 //content=%E5%AD%A6%E4%B9%A0%E4%BA%86&methodName=CommentInsert&parent_id=0&relate_id=23&token=8ABD36C80D1639D9E81130766BE642B7&type=2&user_id=1386387&version=4.32 //content="学习了" //2)基本类型 //新手入门 //食材搭配 //material_ids=45%2C47&methodName=SearchMix&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //material_ids=45%2C47&methodName=SearchMix&page=2&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //场景菜谱 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //methodName=SceneList&page=1&size=18&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=SceneList&page=2&size=18&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //点击进详情 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //methodName=AppShare&shareID=105&shareModule=scene&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //methodName=SceneInfo&scene_id=105&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //再点击列表进详情 //做法 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //dishes_id=14528&methodName=DishesView&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //食材 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //dishes_id=14528&methodName=DishesMaterial&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //相关常识 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //dishes_id=14528&methodName=DishesCommensense&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //相宜相克 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //dishes_id=14528&methodName=DishesSuitable&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //评论数 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //dishes_id=14528&methodName=DishesViewnew&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //发布 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //收藏 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //ids=14528&methodName=UserUpdatelikes&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32 //dishes_id=14528&methodName=DishesViewnew&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //评论 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //methodName=CommentList&page=1&relate_id=14528&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32 //发送评论 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //content=%E5%AD%A6%E4%B9%A0%E4%B8%80%E4%B8%8B&methodName=CommentInsert&parent_id=0&relate_id=14528&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32 //content=@"学习一下" //dishes_id=14528&methodName=DishesViewnew&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //上传照片 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //methodName=ShequTopic&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //activity_id=&content=%E5%BE%88%E5%A5%BD%E5%90%83&image=1457877114055_8928429596.jpg&methodName=ShequPostadd&token=8ABD36C80D1639D9E81130766BE642B7&topics=%5B%7B%22topic_id%22%3A%226%22%2C%22topic_name%22%3A%22%E4%B8%80%E4%BA%BA%E9%A3%9F%22%2C%22locx%22%3A%22160%22%2C%22locy%22%3A%22160%22%2C%22width%22%3A%22320%22%7D%5D&user_id=1386387&version=4.32&video= //content = @“很好吃” //猜你喜欢 //methodName=UserLikes&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //口味有变 //methodName=LbsProvince&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //baidu_city=%E6%B7%B1%E5%9C%B3%E5%B8%82&baidu_province=%E5%B9%BF%E4%B8%9C%E7%9C%81&effect=312&like=230&methodName=UserDraw&province=3&taste=316&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //点击一个标签进入搜索列表 //cat_id=252&methodName=CategorySearch&page=1&size=6&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32 //搜索 //keyword=%E6%97%A9%E9%A4%90&methodName=SearchDishes&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //keyword=早餐 //日食记 //methodName=AppShare&shareID=&shareModule=course&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=CourseSeriesView&series_id=18&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=CommentList&page=1&relate_id=18&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=2&user_id=1386387&version=4.32 //台湾食记 //methodName=AppShare&shareID=&shareModule=course&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=CourseSeriesView&series_id=12&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=CommentList&page=1&relate_id=12&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=2&user_id=1386387&version=4.32 //3)今日食谱推荐 //进列表 //methodName=AppShare&shareID=51&shareModule=scene&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=SceneInfo&scene_id=51&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //相关场景 //methodName=SceneInfo&scene_id=112&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //4)春季养生肝为先 //methodName=AppShare&shareID=127&shareModule=scene&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=SceneInfo&scene_id=127&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //5)场景菜谱 //methodName=SceneList&page=1&size=18&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=SceneInfo&scene_id=134&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //6)推荐达人 //methodName=TalentRecommend&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //关注 //ids=1249795&methodName=UpdateFollow&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32 //取消关注 //ids=1249795&methodName=UpdateFollow&token=8ABD36C80D1639D9E81130766BE642B7&type=0&user_id=1386387&version=4.32 //达人详情页 // //7)精选作品 //is_marrow=1&methodName=ShequList&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //作品详情 //methodName=CommentList&page=1&relate_id=35282&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=3&user_id=1386387&version=4.32 //methodName=AppShare&shareID=35282&shareModule=shequ&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //methodName=ShequPostview&post_id=35282&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //8)美食专题 //methodName=TopicList&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32 //专题详情 //methodName=TopicView&version=1.0&user_id=1386387&topic_id=175&_time=1457878578&_signature=0ba3640c73c17441b675a7dd968a66e8 //http://h5.izhangchu.com/topic_view/index.html?&topic_id=134&user_id=1386387&token=8ABD36C80D1639D9E81130766BE642B7&app_exitpage= //2、食材 //methodName=MaterialSubtype&token=&user_id=&version=4.32 //详情 //material_id=62&methodName=MaterialView&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //相关菜例 //material_id=62&methodName=MaterialDishes&page=1&size=6&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //选购要诀 //营养功效 //实用百科 //material_id=62&methodName=MaterialDishes&page=2&size=6&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //3、分类 //methodName=CategoryIndex&token=&user_id=&version=4.32 //进列表 //cat_id=316&methodName=CategorySearch&page=1&size=6&token=8ABD36C80D1639D9E81130766BE642B7&type=1&user_id=1386387&version=4.32 //4、搜索 //热门搜索 //methodName=SearchHot&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //二、社区 //推荐 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //methodName=ShequRecommend&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.33 //最新 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //last_id=0&methodName=ShequList&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //关注 //http://api.izhangchu.com/?appVersion=4.3.2&sysVersion=9.2.1&devModel=iPhone //methodName=ShequFollow&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //三、商城 //四、食课 //methodName=CourseIndex&page=1&size=10&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //五、我的 //注册 //获取验证码 //device_id=021fc7f7528&methodName=UserLogin&mobile=13716422377&token=&user_id=&version=4.32 //code=173907&device_id=021fc7f7528&methodName=UserAuth&mobile=13716422377&token=&user_id=&version=4.32 // //GET : http://182.92.228.160:80/zhangchu/onlinezhangchu/users/1386387 //注册 //methodName=UserPwd&nickname=sh%E6%8E%8C%E5%8E%A8&password=9745b090734f44cdd7b2ef1d88c26b1f&token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32 //sh掌厨 05513867720
ff88c481c18f8d5d7b9dc7cf20ac001d
33.385135
359
0.798978
false
false
false
false
gp09/Beefit
refs/heads/master
BeefitMsc/BeefitMsc/BeeKeychainService.swift
mit
1
// // KeychainService.swift // Beefit // // Created by Priyank on 22/07/2017. // Copyright © 2017 priyank. All rights reserved. // import Foundation import Security // Constant Identifiers let userAccount = "AuthenticatedUser" let accessGroup = "SecuritySerivice" /** * User defined keys for new entry * Note: add new keys for new secure item and use them in load and save methods */ let passwordKey = "KeyForPassword" // Arguments for the keychain queries let kSecClassValue = NSString(format: kSecClass) let kSecAttrAccountValue = NSString(format: kSecAttrAccount) let kSecValueDataValue = NSString(format: kSecValueData) let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword) let kSecAttrServiceValue = NSString(format: kSecAttrService) let kSecMatchLimitValue = NSString(format: kSecMatchLimit) let kSecReturnDataValue = NSString(format: kSecReturnData) let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne) public class BeeKeychainService: NSObject { /** * Exposed methods to perform save and load queries. */ public class func saveToken(token: NSString) { self.save(service: passwordKey as NSString, data: token) } public class func loadToken() -> NSString? { return self.load(service: passwordKey as NSString) } /** * Internal methods for querying the keychain. */ private class func save(service: NSString, data: NSString) { let dataFromString: NSData = data.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)! as NSData // Instantiate a new default keychain query let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, dataFromString], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecValueDataValue]) // Delete any existing items SecItemDelete(keychainQuery as CFDictionary) // Add the new keychain item SecItemAdd(keychainQuery as CFDictionary, nil) } private class func load(service: NSString) -> NSString? { // Instantiate a new default keychain query // Tell the query to return a result // Limit our results to one item let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue]) var dataTypeRef :AnyObject? // Search for the keychain items let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef) var contentsOfKeychain: NSString? = nil if status == errSecSuccess { if let retrievedData = dataTypeRef as? NSData { contentsOfKeychain = NSString(data: retrievedData as Data, encoding: String.Encoding.utf8.rawValue) } } else { print("Nothing was retrieved from the keychain. Status code \(status)") } return contentsOfKeychain } }
59163a3f78e6afc37cf75f8bf5039b60
35.977011
285
0.705316
false
false
false
false
salesforce-ux/design-system-ios
refs/heads/master
Demo-Swift/slds-sample-app/library/model/ApplicationModel.swift
bsd-3-clause
1
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license import UIKit class ApplicationModel: NSObject { static let sharedInstance = ApplicationModel() var showSwift : Bool = true // MARK: Color data management //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var backgroundColors : Array<ColorObject> { return self.colorsFor(.background, first: SLDSBackgroundColorTypeFirst, last: SLDSBackgroundColorTypeLast) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var borderColors : Array<ColorObject> { return self.colorsFor(.border, first: SLDSBorderColorTypeFirst, last:SLDSBorderColorTypeLast) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var fillColors : Array<ColorObject> { return self.colorsFor(.fill, first: SLDSFillTypeFirst, last:SLDSFillTypeLast) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var textColors : Array<ColorObject> { return self.colorsFor(.text, first: SLDSTextColorTypeFirst, last: SLDSTextColorTypeLast) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– private func sortHue ( c1: ColorObject, c2: ColorObject ) -> Bool { var h1:CGFloat = 0.0 var s1:CGFloat = 0.0 var b1:CGFloat = 0.0 var a1:CGFloat = 0.0 var h2:CGFloat = 0.0 var s2:CGFloat = 0.0 var b2:CGFloat = 0.0 var a2:CGFloat = 0.0 c1.color?.getHue(&h1, saturation: &s1, brightness: &b1, alpha: &a1) c2.color?.getHue(&h2, saturation: &s2, brightness: &b2, alpha: &a2) if a1 >= a2 - 0.05 || a1 < a2 + 0.05 { if h1 == h2 { if s1 >= s2 - 0.05 || s1 < s2 + 0.05 { return b2 < b1 } else { return s1 < s2 } } else { return h1 < h2 } } else { return a1 < a2 } } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– private func colorsFor(_ type: ColorObjectType, first:NSInteger, last:NSInteger ) -> Array<ColorObject> { var colorList = Array<ColorObject>() for index in first...last { let color = ColorObject(type: type, index: index) colorList.append(color) } return colorList.sorted(by: self.sortHue) } // MARK: Icon data management //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var actionIcons : Array<IconObject> { return self.iconsFor( .action, first: SLDSActionIconTypeFirst, last: SLDSActionIconTypeLast ) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var customIcons : Array<IconObject> { return self.iconsFor( .custom, first: SLDSCustomIconTypeFirst, last: SLDSCustomIconTypeLast ) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var standardIcons : Array<IconObject> { return self.iconsFor( .standard, first: SLDSStandardIconTypeFirst, last: SLDSStandardIconTypeLast ) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var utilityIcons : Array<IconObject> { return self.iconsFor( .utility, first: SLDSUtilityIconTypeFirst, last: SLDSUtilityIconTypeLast ) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– private func iconsFor(_ type : IconObjectType, first:NSInteger, last:NSInteger ) -> Array<IconObject> { var iconList = Array<IconObject>() for index in first...last { let icon = IconObject(type: type, index: index, size: SLDSSquareIconMedium) iconList.append(icon) } return iconList } }
209768c7fe9a2e2bbed20e4927be8549
33.77686
114
0.453184
false
false
false
false
aijaz/icw1502
refs/heads/master
playgrounds/Week03.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift
mit
1
//: Playground - noun: a place where people can play import Cocoa let person = "Swift Programmer" let person2:String person2 = "Aijaz" let shouldRun:Bool shouldRun = true let travel: String if shouldRun { travel = "run" } else { travel = "walk" } print ("I am going to \(travel)") // Perfectly good use of a var variable func hello(name: String, numberOfTimes: Int) -> String { var tempGreeting = "" for _ in 1 ... numberOfTimes { tempGreeting += "Hello, \(name)!\n" } return tempGreeting } hello("Aijaz", numberOfTimes: 5) let five = 5 let threepointfour = 3.4 let simpleProduct = 5 * 3.4 //let product = five * threepointfour let workingProduct = Double(five) * threepointfour let i1 = 5 //i1 = nil var name:String? name = "Aijaz" name = nil name = "Aijaz" print(name) print(name!) name = nil print (name) name = "aijaz" if name != nil { print (name!) } else { print ("No name given") } if let validName = name { print (validName) } else { print ("No name given") }
2e1d2771ff0d51c0503b259337f3c503
10.593407
56
0.63128
false
false
false
false
hooman/SwiftMath
refs/heads/master
Sources/Algorithms.swift
apache-2.0
1
// // Algorithms.swift // SwiftMath // // Global functions (public in internal) defined by SwiftMath module. // (c) 2016 Hooman Mehr. Licensed under Apache License v2.0 with Runtime Library Exception // /// Returns the Greatest Common Divisor (GCD) of two non-negative integers /// /// For convenience, assumes gcd(0,0) == 0 /// Implemented using "binary GCD algorithm" (aka Stein's algorithm) /// /// - Precondition: `a >= 0 && b >= 0` public func gcd(_ a: Int, _ b: Int) -> Int { assert(a >= 0 && b >= 0) // Assuming gcd(0,0)=0: guard a != 0 else { return b } guard b != 0 else { return a } var a = a, b = b, n = Int() //FIXME: Shift loops are slow and should be opimized. // Remove the largest 2ⁿ from them: while (a | b) & 1 == 0 { a >>= 1; b >>= 1; n += 1 } // Reduce `a` to odd value: while a & 1 == 0 { a >>= 1 } repeat { // Reduce `b` to odd value while b & 1 == 0 { b >>= 1 } // Both `a` & `b` are odd here (or zero maybe?) // Make sure `b` is greater if a > b { swap(&a, &b) } // Subtract smaller odd `a` from the bigger odd `b`, // which always gives a positive even number (or zero) b -= a // keep repeating this, until `b` reaches zero } while b != 0 return a << n // 2ⁿ×a } /// Returns the Greatest Common Divisor (GCD) of two unsigned integers /// /// For convenience, assumes gcd(0,0) == 0 /// Implemented using "binary GCD algorithm" (aka Stein's algorithm) public func gcd(_ a: UInt, _ b: UInt) -> UInt { // Assuming gcd(0,0)=0: guard a != 0 else { return b } guard b != 0 else { return a } var a = a, b = b, n = UInt() //FIXME: Shift loops are slow and should be opimized. // Remove the largest 2ⁿ from them: while (a | b) & 1 == 0 { a >>= 1; b >>= 1; n += 1 } // Reduce `a` to odd value: while a & 1 == 0 { a >>= 1 } repeat { // Reduce `b` to odd value while b & 1 == 0 { b >>= 1 } // Both `a` & `b` are odd here (or zero maybe?) // Make sure `b` is greater if a > b { swap(&a, &b) } // Subtract smaller odd `a` from the bigger odd `b`, // which always gives a positive even number (or zero) b -= a // keep repeating this, until `b` reaches zero } while b != 0 return a << n // 2ⁿ×a }
09650d37966a3832e14845d53c3851b3
25.041237
91
0.505542
false
false
false
false
danteteam/ProLayer
refs/heads/master
ProLayer/ProLayer.swift
mit
1
// // Builder.swift // GuessPointApp // // Created by Ivan Brazhnikov on 19.08.15. // Copyright (c) 2015 Ivan Brazhnikov. All rights reserved. // import UIKit public func Layer(layer: CALayer) -> ProLayer { return ProLayer(layer) } public func Layer(view: UIView) -> ProLayer { return ProLayer(view.layer) } public class ProLayer { let layer: CALayer init(_ layer: CALayer) { self.layer = layer } public func radius(value: CGFloat) -> Self { layer.cornerRadius = value return self } public func shadow() -> Shadow { return Shadow(buider: self) } public func border() -> Border { return Border(buider: self) } public class Border { private let parent: ProLayer private var layer: CALayer { return parent.layer } init(buider: ProLayer) { self.parent = buider } public func color(value: UIColor) -> Self { layer.borderColor = value.CGColor return self } public func width(value: CGFloat) -> Self { layer.borderWidth = value return self } public func done() -> ProLayer { return parent } } public class Shadow { private let parent: ProLayer private var layer: CALayer { return parent.layer } init(buider: ProLayer) { self.parent = buider } public func color(value: UIColor) -> Self { layer.shadowColor = value.CGColor return self } public func radius(value: CGFloat) -> Self { layer.shadowRadius = value return self } public func opacity(value: Float) -> Self { layer.shadowOpacity = value return self } public func offset(value: CGSize) -> Self { layer.shadowOffset = value return self } public func path(value: CGPath) -> Self { layer.shadowPath = value return self } public func done() -> ProLayer { return parent } } }
b26c277e9c37cf37783a0cd4ad8b8bf4
21.49505
60
0.521356
false
false
false
false
gitgitcode/LearnSwift
refs/heads/master
Calculator/Caiculator/Caiculator/ViewController.swift
apache-2.0
1
// // ViewController.swift // Caiculator // // Created by xuthus on 15/6/14. // Copyright (c) 2015年 xuthus. All rights reserved. // import UIKit class ViewController: UIViewController { //定义了一个类 //有针对的名字 单继承 @IBOutlet weak var display: UILabel! //prop !是 类型 未定义 var userIsInTheMiddletofTypingANumbser: Bool = false @IBAction func appendDigit(sender: UIButton) { let digit = sender.currentTitle! if userIsInTheMiddletofTypingANumbser { display.text = display.text! + digit }else{ display.text = digit userIsInTheMiddletofTypingANumbser = true } println("digit = \(digit)") } @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddletofTypingANumbser { enter() } switch operation { case "×": performOperation{$0 * $1} case "÷": performOperation{$1 / $0} case "+": performOperation{$0 + $1} case "−": performOperation{$1 - $0} default:break } } func performOperation(operation:(Double,Double) ->Double){ if operandStack.count >= 2 { //displayValue = operandStack.removeLast() * operandStack.removeLast() displayValue = operation(operandStack.removeLast(),operandStack.removeLast()) enter() } } // var operandStack: Array<Double> = Array<Double>() var operandStack = Array<Double>() @IBAction func enter() { userIsInTheMiddletofTypingANumbser = false operandStack.append(displayValue) println("operandStack = \(operandStack)") } //转化设置dipaly的值 var displayValue: Double { get { return NSNumberFormatter().numberFromString(display.text!)!.doubleValue } set { //double -> string display.text = "\(newValue)" userIsInTheMiddletofTypingANumbser = false } } }
52f02925113431791cb6e804c3c27d58
25.818182
89
0.580145
false
false
false
false
bitboylabs/selluv-ios
refs/heads/master
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab2Search/views/SLVSearchTableCategoryCell.swift
mit
1
// // SLVSearchTableCategoryCell.swift // selluv-ios // // Created by 조백근 on 2017. 5. 21.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import UIKit class SLVSearchTableCategoryCell: UITableViewCell { @IBOutlet weak var symbolView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func imageDomain() -> String { return dnImage } func reset() { self.titleLabel.text = "" self.subLabel.text = "" self.symbolView.image = nil } func setupData(item: RecommendCategory) { self.reset() let title = item.name ?? "" let image = "" self.titleLabel.text = title self.subLabel.text = "" if image != "" { let domain = self.imageDomain() let from = URL(string: "\(domain)\(image)") let dnModel = SLVDnImageModel.shared DispatchQueue.global(qos: .default).async { dnModel.setupImageView(view: self.symbolView, from: from!) } } } }
fe4b58e41c7195d91f9d173e9600a962
23.44
74
0.565466
false
false
false
false
nbusy/nbusy-ios
refs/heads/master
NBusy/AppDelegate.swift
apache-2.0
1
import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController let controller = masterNavigationController.topViewController as! MasterViewController controller.managedObjectContext = self.managedObjectContext return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.nbusy.NBusy" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("NBusy", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "nbusy.err", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
d72471b67b18313c803a836eaa7d4c68
59.622951
291
0.733775
false
false
false
false
garethknowles/JBDatePicker
refs/heads/master
JBDatePicker/Classes/JBDatePickerDayView.swift
mit
1
// // JBDatePickerDayView.swift // JBDatePicker // // Created by Joost van Breukelen on 13-10-16. // Copyright © 2016 Joost van Breukelen. All rights reserved. // import UIKit public final class JBDatePickerDayView: UIView { // MARK: - Properties private var index: Int! private var dayInfo: JBDay! weak private var weekView: JBDatePickerWeekView! weak private var monthView: JBDatePickerMonthView! weak var datePickerView: JBDatePickerView! public var date: Date? var isToday: Bool { return date == Date().stripped(calendar: datePickerView.calendar) } private var textLabel: UILabel! private weak var selectionView: JBDatePickerSelectionView? private let longPressArea: CGFloat = 40 private var longPressAreaMaxX: CGFloat { return bounds.width + longPressArea } private var longPressAreaMaxY: CGFloat { return bounds.height + longPressArea } private var longPressAreaMin: CGFloat { return -longPressArea } // MARK: - Initialization init(datePickerView: JBDatePickerView, monthView: JBDatePickerMonthView, weekView: JBDatePickerWeekView, index: Int, dayInfo: JBDay) { self.datePickerView = datePickerView self.monthView = monthView self.weekView = weekView self.index = index self.dayInfo = dayInfo if let size = datePickerView.dayViewSize { let frame = CGRect(x: size.width * CGFloat(index), y: 0, width: size.width, height: size.height) super.init(frame: frame) } else{ super.init(frame: .zero) } //backgroundColor = randomColor() self.date = dayInfo.date labelSetup() if dayInfo.isInMonth { //set default color textLabel.textColor = datePickerView.delegate?.colorForDayLabelInMonth //check date is selectable, if not selectable, set colour and don't add gestures guard datePickerView.dateIsSelectable(date: date) else { self.textLabel.textColor = datePickerView.delegate?.colorForUnavaibleDay return } } else{ if let shouldShow = datePickerView.delegate?.shouldShowMonthOutDates { if shouldShow { textLabel.textColor = datePickerView.delegate?.colorForDayLabelOutOfMonth //check date is selectable, if not selectable, don't add gestures guard datePickerView.dateIsSelectable(date: date) else {return} } else{ self.isUserInteractionEnabled = false self.textLabel.isHidden = true } } } //highlight current day. Must come before selection of selected date, because it would override the text color set by select() if isToday { self.textLabel.textColor = datePickerView.delegate?.colorForCurrentDay } //select selected day if date == datePickerView.dateToPresent.stripped(calendar: datePickerView.calendar) { guard self.dayInfo.isInMonth else { return } datePickerView.selectedDateView = self //self.backgroundColor = randomColor() } //add tapgesture recognizer let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dayViewTapped)) self.addGestureRecognizer(tapGesture) //add longPress gesture recognizer let pressGesture = UILongPressGestureRecognizer(target: self, action: #selector(dayViewPressed(_:))) self.addGestureRecognizer(pressGesture) } public override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Label setup private func labelSetup() { textLabel = UILabel() textLabel.textAlignment = .center textLabel.translatesAutoresizingMaskIntoConstraints = false self.addSubview(textLabel) textLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true textLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true } private func setupLabelFont() { //get preferred font guard let preferredFont = datePickerView.delegate?.fontForDayLabel else { return } //get preferred size let preferredSize = preferredFont.fontSize let sizeOfFont: CGFloat //calculate fontsize to be used switch preferredSize { case .verySmall: sizeOfFont = min(frame.size.width, frame.size.height) / 3.5 case .small: sizeOfFont = min(frame.size.width, frame.size.height) / 3 case .medium: sizeOfFont = min(frame.size.width, frame.size.height) / 2.5 case .large: sizeOfFont = min(frame.size.width, frame.size.height) / 2 case .veryLarge: sizeOfFont = min(frame.size.width, frame.size.height) / 1.5 } //get font to be used let fontToUse: UIFont switch preferredFont.fontName.isEmpty { case true: fontToUse = UIFont.systemFont(ofSize: sizeOfFont, weight: UIFontWeightRegular) case false: if let customFont = UIFont(name: preferredFont.fontName, size: sizeOfFont) { fontToUse = customFont } else { print("custom font '\(preferredFont.fontName)' for dayLabel not available. JBDatePicker will use system font instead") fontToUse = UIFont.systemFont(ofSize: sizeOfFont, weight: UIFontWeightRegular) } } textLabel.attributedText = NSMutableAttributedString(string: String(dayInfo.dayValue), attributes:[NSFontAttributeName: fontToUse]) } public override func layoutSubviews() { textLabel.frame = bounds setupLabelFont() } // MARK: - Touch handling public func dayViewTapped() { datePickerView.didTapDayView(dayView: self) } public func dayViewPressed(_ gesture: UILongPressGestureRecognizer) { //if selectedDateView exists and is self, return. Long pressing shouldn't do anything on selected day. if let selectedDate = datePickerView.selectedDateView { guard selectedDate != self else { return } } let location = gesture.location(in: self) switch gesture.state { case .began: semiSelect(animated: true) case .ended: if let selView = selectionView { selView.removeFromSuperview() } datePickerView.didTapDayView(dayView: self) case .changed: if !(longPressAreaMin...longPressAreaMaxX).contains(location.x) || !(longPressAreaMin...longPressAreaMaxY).contains(location.y) { semiDeselect(animated: true) //this will cancel the longpress gesture (and enable it again for the next time) gesture.isEnabled = false gesture.isEnabled = true } default: break } } // MARK: - Reloading public func reloadContent() { textLabel.frame = bounds setupLabelFont() //reload selectionView if let selView = selectionView { selView.frame = textLabel.frame selView.setNeedsDisplay() } } // MARK: - Selection & Deselection func select() { let selView = JBDatePickerSelectionView(dayView: self, frame: self.bounds, isSemiSelected: false) insertSubview(selView, at: 0) selView.translatesAutoresizingMaskIntoConstraints = false //pin selectionView horizontally and make it's width equal to the height of the datePickerview. This way it stays centered while rotating the device. selView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true selView.widthAnchor.constraint(equalTo: heightAnchor).isActive = true //pint it to the left and right selView.topAnchor.constraint(equalTo: topAnchor).isActive = true selView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true selectionView = selView //set textcolor to selected state textLabel.textColor = datePickerView.delegate?.colorForSelelectedDayLabel } func deselect() { if let selectionView = selectionView { selectionView.removeFromSuperview() } //set textcolor to default color switch isToday { case true: textLabel.textColor = datePickerView.delegate?.colorForCurrentDay case false: textLabel.textColor = dayInfo.isInMonth ? datePickerView.delegate?.colorForDayLabelInMonth : datePickerView.delegate?.colorForDayLabelOutOfMonth } } /** creates and shows a selection circle with a semi selected color - Parameter animated: if true, this will fade in the circle */ private func semiSelect(animated: Bool) { if let selectionView = selectionView { if animated { insertCircleViewAnimated(selectionView: selectionView) } else{ insertSubview(selectionView, at: 0) } } else { let selView = JBDatePickerSelectionView(dayView: self, frame: self.bounds, isSemiSelected: true) if animated { insertCircleViewAnimated(selectionView: selView) } else{ insertSubview(selView, at: 0) } selectionView = selView } } /** removes semi selected selection circle and removes circle from superview - Parameter animated: if true, this will fade the circle out before removal */ private func semiDeselect(animated: Bool) { switch animated { case true: removeCircleViewAnimated() case false: selectionView?.removeFromSuperview() } } ///just a helper that inserts the selection circle animated private func insertCircleViewAnimated(selectionView: JBDatePickerSelectionView) { selectionView.alpha = 0.0 insertSubview(selectionView, at: 0) UIView.animate(withDuration: 0.2, animations: { selectionView.alpha = 1.0 }) } ///just a helper that removes the selection circle animated private func removeCircleViewAnimated() { UIView.animate(withDuration: 0.2, animations: { self.selectionView?.alpha = 0.0 }, completion: {_ in self.selectionView?.removeFromSuperview() }) } }
b562879ee6fceac6ff3b90a9f3c65a33
32.376471
157
0.604159
false
false
false
false
farzadshbfn/POP
refs/heads/master
Sources/SegueHandlerType.swift
mit
1
// // SegueHandlerType.swift // POP // // Created by Farzad Sharbafian on 1/8/17. // Copyright © 2017 FarzadShbfn. All rights reserved. // import Foundation import UIKit public protocol SegueHandlerType { associatedtype SegueIdentifier: RawRepresentable } extension SegueHandlerType where Self: UIViewController, SegueIdentifier.RawValue == String { public func performSegue(withSegueIdentifier segue: SegueIdentifier, sender: Any?) { performSegue(withIdentifier: segue.rawValue, sender: sender) } public func segueIdentifier(forSegue segue: UIStoryboardSegue) -> SegueIdentifier { guard let identifier = segue.identifier, let segueIdentifier = SegueIdentifier(rawValue: identifier) else { fatalError("Invalid segue identifier \(segue.identifier) for view controller of type \(type(of: self)).") } return segueIdentifier } public func destination<T: UIViewController>(forSegue segue: UIStoryboardSegue) -> T { guard let viewController = segue.destination as? T else { fatalError("Invalid Destination ViewController: \(T.self) bounded to Segue: \(segueIdentifier(forSegue: segue)), ") } return viewController } }
def19e069fc1c6798c5346328b416bd2
29.5
118
0.759275
false
false
false
false
schibsted/layout
refs/heads/master
Layout/LayoutError.swift
mit
1
// Copyright © 2017 Schibsted. All rights reserved. import Foundation private func stringify(_ error: Error) -> String { switch error { case is SymbolError, is LayoutError, is FileError, is XMLParser.Error, is Expression.Error: return "\(error)" default: return error.localizedDescription } } /// An error relating to a specific symbol/expression internal struct SymbolError: Error, CustomStringConvertible { let symbol: String let error: Error var fatal = false init(_ error: Error, for symbol: String) { self.symbol = symbol if let error = error as? SymbolError { let description = error.description if symbol == error.symbol || description.contains(symbol) { self.error = error.error } else if description.contains(error.symbol) { self.error = SymbolError(description, for: error.symbol) } else { self.error = SymbolError("\(description) for \(error.symbol)", for: error.symbol) } } else { self.error = error } } /// Creates an error for the specified symbol init(_ message: String, for symbol: String) { self.init(Expression.Error.message(message), for: symbol) } /// Creates a fatal error for the specified symbol init(fatal message: String, for symbol: String) { self.init(Expression.Error.message(message), for: symbol) fatal = true } public var description: String { var description = stringify(error) if !description.contains(symbol) { description = "\(description) in \(symbol) expression" } return description } /// Associates error thrown by the wrapped closure with the given symbol static func wrap<T>(_ closure: () throws -> T, for symbol: String) throws -> T { do { return try closure() } catch { throw self.init(error, for: symbol) } } } /// The public interface for all Layout errors public enum LayoutError: Error, Hashable, CustomStringConvertible { case message(String) case generic(Error, String?) case unknownExpression(Error /* SymbolError */, [String]) case unknownSymbol(Error /* SymbolError */, [String]) case multipleMatches([URL], for: String) public init?(_ error: Error?) { guard let error = error else { return nil } self.init(error) } public init(_ message: String, in className: String? = nil, in url: URL? = nil) { self.init(LayoutError.message(message), in: className, in: url) } @available(*, deprecated, message: "Use init(_:in:) instead") public init(_ message: String, for viewOrControllerClass: AnyClass?) { self.init(message, in: viewOrControllerClass.map(nameOfClass)) } public init(_ error: Error, in className: String?, in url: URL?) { self = .generic(LayoutError(error, in: className), url?.lastPathComponent) } public init(_ error: Error, in classNameOrFile: String?) { if let cls: AnyClass = classNameOrFile.flatMap(classFromString) { self.init(error, for: cls) } else { self.init(LayoutError.generic(error, classNameOrFile)) } } public init(_ error: Error, for viewOrControllerClass: AnyClass? = nil) { switch error { case LayoutError.multipleMatches: // Should never be wrapped or it's hard to treat as special case self = error as! LayoutError case let LayoutError.generic(_, cls) where cls == viewOrControllerClass.map(nameOfClass): self = error as! LayoutError case let error as LayoutError where viewOrControllerClass == nil: self = error default: self = .generic(error, viewOrControllerClass.map(nameOfClass)) } } public var suggestions: [String] { switch self { case let .unknownExpression(_, suggestions), let .unknownSymbol(_, suggestions): return suggestions case let .generic(error, _): return (error as? LayoutError)?.suggestions ?? [] default: return [] } } public var description: String { switch self { case let .message(message): return message case let .generic(error, className): var description = stringify(error) if let className = className { if !description.contains(className) { description = "\(description) in \(className)" } } return description case let .unknownExpression(error, _), let .unknownSymbol(error, _): return stringify(error) case let .multipleMatches(_, path): return "Layout found multiple source files matching \(path)" } } // Returns true if the error can be cleared, or false if the // error is fundamental, and requires a code change + reload to fix it public var isTransient: Bool { switch self { case let .generic(error, _), let .unknownSymbol(error, _), let .unknownExpression(error, _): if let error = error as? LayoutError { return error.isTransient } return (error as? SymbolError)?.fatal != true case .multipleMatches, _ where description.contains("XML"): // TODO: less hacky return false default: return true // TODO: handle expression parsing errors } } public func hash(into hasher: inout Hasher) { description.hash(into: &hasher) } public static func == (lhs: LayoutError, rhs: LayoutError) -> Bool { return lhs.description == rhs.description } /// Converts error thrown by the wrapped closure to a LayoutError static func wrap<T>(_ closure: () throws -> T) throws -> T { return try wrap(closure, in: nil) } static func wrap<T>(_ closure: () throws -> T, in className: String?, in url: URL? = nil) throws -> T { do { return try closure() } catch { throw self.init(error, in: className, in: url) } } }
e2ff33472b72255a1f8ace94bd099dd0
32.673684
107
0.589403
false
false
false
false
vito5314/RSSwift
refs/heads/master
RSSwift/RSSwift/FeedTableViewController.swift
apache-2.0
1
// // FeedTableViewController.swift // RSSwift // // Created by Arled Kola on 20/09/2014. // Copyright (c) 2014 Arled. All rights reserved. // import UIKit class FeedTableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate, NSXMLParserDelegate { @IBOutlet weak var menuButton: UIBarButtonItem! var myFeed : NSArray = [] var url: NSURL = NSURL() override func viewDidLoad() { super.viewDidLoad() if self.revealViewController() != nil { menuButton.target=self.revealViewController() menuButton.action="revealToggle:" self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } // Cell height. self.tableView.rowHeight = 70 self.tableView.dataSource = self self.tableView.delegate = self // Set feed url. http://www.formula1.com/rss/news/latest.rss url = NSURL(string: "http://www.skysports.com/rss/0,20514,11661,00.xml")! // Call custom function. loadRss(url); } func loadRss(data: NSURL) { // XmlParserManager instance/object/variable var myParser : XmlParserManager = XmlParserManager.alloc().initWithURL(data) as! XmlParserManager // Put feed in array myFeed = myParser.feeds tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let newUrl = segue.destinationViewController as? NewFeedViewController { newUrl.onDataAvailable = {[weak self] (data) in if let weakSelf = self { weakSelf.loadRss(data) } } } else if segue.identifier == "openPage" { var indexPath: NSIndexPath = self.tableView.indexPathForSelectedRow()! //let selectedFeedURL: String = feeds[indexPath.row].objectForKey("link") as String let selectedFTitle: String = myFeed[indexPath.row].objectForKey("title") as! String let selectedFContent: String = myFeed[indexPath.row].objectForKey("description") as! String let selectedFURL: String = myFeed[indexPath.row].objectForKey("link") as! String // Instance of our feedpageviewcontrolelr let fpvc: FeedPageViewController = segue.destinationViewController as! FeedPageViewController fpvc.selectedFeedTitle = selectedFTitle fpvc.selectedFeedFeedContent = selectedFContent fpvc.selectedFeedURL = selectedFURL } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return myFeed.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell // Feeds dictionary. var dict : NSDictionary! = myFeed.objectAtIndex(indexPath.row) as! NSDictionary // Set cell properties. cell.textLabel?.text = myFeed.objectAtIndex(indexPath.row).objectForKey("title") as? String cell.detailTextLabel?.text = myFeed.objectAtIndex(indexPath.row).objectForKey("pubDate") as? String return cell } }
32047f79db4f3027a2a66bf54e88b220
33.915094
119
0.641989
false
false
false
false
Eonil/EditorLegacy
refs/heads/trial1
Modules/SwiftCodeGeneration/Sources/Syntax.swift
mit
1
// // SwiftCodeGeneration3.swift // DataConverterClassGenerator // // Created by Hoon H. on 11/16/14. // // import Foundation public typealias Statements = NodeList<Statement> public enum Statement : NodeType { case Expression(SwiftCodeGeneration.Expression) case Declaration(SwiftCodeGeneration.Declaration) case LoopStatement(SwiftCodeGeneration.LoopStatement) public func writeTo<C : CodeWriterType>(inout w: C) { switch self { case .Expression(let s): s.writeTo(&w) case .Declaration(let s): s.writeTo(&w) case .LoopStatement(let s): s.writeTo(&w) } w.writeToken(";") } } public enum LoopStatement : NodeType { // case ForStatement case ForInStatement(pattern:Pattern, expression:Expression, codeBlock:CodeBlock) // case WhileStatement // case DoWhileStatement public func writeTo<C : CodeWriterType>(inout w: C) { switch self { case .ForInStatement(let s): w <<< "for" ~ s.pattern ~ "in" ~ s.expression ~ s.codeBlock } } } public struct Pattern : NodeType { public var text:String public func writeTo<C:CodeWriterType>(inout w:C) { w.writeToken(text) } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/code-block public struct CodeBlock : NodeType { public var statements : Statements public init() { self.statements = Statements() } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< "{" ~ statements ~ "}" } } public enum ForInStatement { public func writeTo<C : CodeWriterType>(inout w: C) { } } public enum Expression : NodeType { public func writeTo<C : CodeWriterType>(inout w: C) { } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/declaration public enum Declaration : NodeType { case Import(ImportDeclaration) // case Constant case Variable(VariableDeclaration) // case Typealias case Function(FunctionDeclaration) // case Enum case Struct(StructDeclaration) case Class(ClassDeclaration) // case Protocol case Initializer(InitializerDeclaration) // case Deinitializer case Extension(ExtensionDeclaration) // case Subscript(SubscriptDeclaration) // case Operator public func writeTo<C : CodeWriterType>(inout w: C) { switch self { case .Import(let s): w <<< s case .Variable(let s): w <<< s case .Function(let s): w <<< s case .Struct(let s): w <<< s case .Class(let s): w <<< s case .Initializer(let s): w <<< s case .Extension(let s): w <<< s } } } public typealias Declarations = NodeList<Declaration> public struct ImportDeclaration: NodeType { public var attributes : Attributes public var importKind : String public var importPath : String public func writeTo<C : CodeWriterType>(inout w: C) { w <<< attributes ~ importKind ~ importPath } } /// Simplified. public struct VariableDeclaration: NodeType { public var variableDeclarationHead : VariableDeclarationHead public var name : String public var type : Type public init(name:String, type:String) { self.variableDeclarationHead = VariableDeclarationHead(attributes: Attributes(), declarationModifiers: DeclarationModifier.AccessLevel(AccessLevelModifier.Internal)) self.name = name self.type = Type(text: type) } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< variableDeclarationHead w.writeToken(name) w.writeToken(":") w <<< type } } public struct VariableDeclarationHead: NodeType { public var attributes : Attributes public var declarationModifiers : DeclarationModifier public func writeTo<C : CodeWriterType>(inout w: C) { w <<< attributes ~ declarationModifiers ~ "var" } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/function-declaration public struct FunctionDeclaration: NodeType { var functionHead : FunctionHead var functionName : FunctionName var genericParameterClause : GenericParameterClause? var functionSignature : FunctionSignature var functionBody : FunctionBody /// Creates `()->()` function. public init(name:String) { self.init(name: name, resultType: "()") } /// Creates `()->T` function. public init(name:String, resultType:String) { self.init(name: name, inputParameters: ParameterList(), resultType: resultType) } /// Creates `T->T` function. public init(name:String, inputParameters:ParameterList, resultType:String) { self.functionHead = FunctionHead(attributes: Attributes(), declarationModifiers: DeclarationModifiers()) self.functionName = FunctionName.Identifier(Identifier(name)) self.genericParameterClause = GenericParameterClause(dummy: "") self.functionSignature = FunctionSignature(parameterClauses: ParameterClauses([ParameterClause(parameters: inputParameters, variadic: false)]), functionResult: FunctionResult(attributes: Attributes(), type: Type(text: resultType))) self.functionBody = FunctionBody() } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< functionHead ~ functionName ~ genericParameterClause ~ functionSignature ~ functionBody } } public struct FunctionHead: NodeType { var attributes : Attributes var declarationModifiers : DeclarationModifiers public func writeTo<C : CodeWriterType>(inout w: C) { w <<< attributes ~ declarationModifiers ~ "func" } } public enum FunctionName: NodeType { case Identifier(SwiftCodeGeneration.Identifier) // case Operator public func writeTo<C : CodeWriterType>(inout w: C) { switch self { case .Identifier(let s): w.writeToken(s) } } } public struct FunctionSignature: NodeType { public var parameterClauses : ParameterClauses public var functionResult : FunctionResult public func writeTo<C : CodeWriterType>(inout w: C) { w <<< parameterClauses ~ functionResult } } public struct FunctionResult: NodeType { var attributes : Attributes var type : Type public func writeTo<C : CodeWriterType>(inout w: C) { w <<< "->" ~ attributes ~ type } } public struct FunctionBody: NodeType { public var codeBlock : CodeBlock public init() { self.codeBlock = CodeBlock() } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< codeBlock } } public struct StructDeclaration: NodeType { public var attributes : Attributes? public var accessLevelModifier : AccessLevelModifier? public var structName : Identifier public var genericParameterClause : GenericParameterClause? public var typeInheritanceClause : TypeInheritanceClause? public var structBody : Declarations public init(name:String) { self.structName = Identifier(name) self.structBody = Declarations() } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< attributes ~ accessLevelModifier ~ "struct" ~ structName ~ genericParameterClause ~ typeInheritanceClause ~ "{" ~ structBody ~ "}" } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/class-declaration public struct ClassDeclaration: NodeType { public var attributes : Attributes? public var accessLevelModifier : AccessLevelModifier? public var className : Identifier public var genericParameterClause : GenericParameterClause? public var typeInheritanceClause : TypeInheritanceClause? public var classBody : Declarations public func writeTo<C : CodeWriterType>(inout w: C) { w <<< attributes ~ accessLevelModifier ~ "class" ~ className ~ genericParameterClause ~ typeInheritanceClause ~ "{" ~ classBody ~ "}" } } // enum ImportKind: NodeType { // public func writeTo<C : CodeWriterType>(inout w: C) { // } // } public struct Attribute: NodeType { public func writeTo<C : CodeWriterType>(inout w: C) { } } public typealias Attributes = NodeList<Attribute> /// Disabled due to compiler bug. public enum AccessLevelModifier: NodeType { case Internal case InternalSet case Private case PrivateSet case Public case PublicSet public func writeTo<C : CodeWriterType>(inout w: C) { switch self { case .Internal: w.writeToken("internal") case .InternalSet: w.writeToken("internal ( set )") case .Private: w.writeToken("private") case .PrivateSet: w.writeToken("private ( set )") case .Public: w.writeToken("public") case .PublicSet: w.writeToken("public ( set )") } } } public struct GenericParameterClause: NodeType { public var dummy:String public func writeTo<C : CodeWriterType>(inout w: C) { } } // Simplified... too much of needless works. public typealias TypeInheritanceClause = String // public struct TypeInheritanceClause: NodeType { // public var dummy:String // public func writeTo<C : CodeWriterType>(inout w: C) { // } // } public struct StructBody: NodeType { public var declarations:Declarations public func writeTo<C : CodeWriterType>(inout w: C) { } } public struct ClassBody: NodeType { public var declarations:Declarations public func writeTo<C : CodeWriterType>(inout w: C) { } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/initializer-declaration public struct InitializerDeclaration: NodeType { public var initializerHead:InitializerHead public var genericParameterClause:GenericParameterClause? public var parameterClause:ParameterClause public var initializerBody:CodeBlock public init() { self.init(failable: false) } public init(failable:Bool) { self.init(failable: false, parameters: ParameterList()) } public init(failable:Bool, parameters:ParameterList) { self.initializerHead = InitializerHead(attributes: Attributes(), declarations: nil, failable: failable) self.parameterClause = ParameterClause(parameters: parameters, variadic: false) self.initializerBody = CodeBlock() } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< initializerHead ~ genericParameterClause ~ parameterClause ~ initializerBody } } public struct InitializerHead: NodeType { public var attributes : Attributes public var declarations : DeclarationModifiers? public var failable : Bool public func writeTo<C : CodeWriterType>(inout w: C) { w <<< attributes ~ declarations ~ "init" ~ (failable ? "?" : "") } } public enum DeclarationModifier: NodeType { case AccessLevel(AccessLevelModifier) // case Class // case Convenience // case Dynamic // case Final // case Infix // case Lazy // case Mutating // case NonMutating // case Optional // case Override // case Postfix // case Prefix // case Required // case Static // case Unowned // case UnownedSafe // case UnownedUnsafe // case Weak public func writeTo<C : CodeWriterType>(inout w: C) { switch self { case .AccessLevel(let s): w <<< s } } } public typealias DeclarationModifiers = NodeList<DeclarationModifier> /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/parameter-clause public struct ParameterClause: NodeType { public var parameters : ParameterList public var variadic : Bool public func writeTo<C : CodeWriterType>(inout w: C) { w <<< "(" ~ parameters ~ (variadic ? "..." : "") ~ ")" } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/parameter-clauses public typealias ParameterClauses = NodeList<ParameterClause> public struct ParameterList: NodeType { public var items : [Parameter] public init() { items = [] } public func writeTo<C : CodeWriterType>(inout w: C) { for i in 0..<items.count { let m = items[i] w <<< m if i < items.count-1 { w.writeToken(",") } } } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/parameter public struct Parameter: NodeType { public var byref : Bool public var mutable : Bool public var hashsign : Bool public var externalParameterName : Identifier? public var localParameterName : Identifier public var typeAnnotation : TypeAnnotation public var defaultArgumentClause : Expression? // public var attributes = NodeList<Attribute>() // public var type : Type public init(name:String, type:String) { byref = false mutable = false hashsign = false localParameterName = Identifier(name) typeAnnotation = TypeAnnotation(attributes: Attributes(), type: Type(text: type)) } public func writeTo<C : CodeWriterType>(inout w: C) { w.writeToken(byref ? "inout" : "") w.writeToken(mutable ? "var" : "let") w.writeToken(hashsign ? "#" : "") if externalParameterName != nil { w.writeToken(externalParameterName!) } w.writeToken(localParameterName) w <<< typeAnnotation ~ defaultArgumentClause } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Types.html#//apple_ref/swift/grammar/type-annotation public struct TypeAnnotation: NodeType { public var attributes : Attributes? public var type : Type public func writeTo<C : CodeWriterType>(inout w: C) { w <<< ":" ~ attributes ~ type } } public struct Type: NodeType { public var text:String public func writeTo<C : CodeWriterType>(inout w: C) { w.writeToken(text) } } // enum Type: NodeType { //// case Array //// case Dictionary //// case Function // case TypeIdentifier(expression:String) //// case Tuple //// case Optional //// case ImplicitlyUnwrappedOptional //// case ProtocolCOmposition //// case Metatype // // public func writeTo<C : CodeWriterType>(inout w: C) { // switch self { // case .TypeIdentifier(let s): w.writeToken(s) // } // } // } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/doc/uid/TP40014097-CH34-XID_704 public struct ExtensionDeclaration: NodeType { public var accessLevelModifier:AccessLevelModifier? public var typeIdentifier:TypeIdentifier public var typeInheritanceClause:TypeInheritanceClause? public var extensionBody:Declarations public func writeTo<C : CodeWriterType>(inout w: C) { w <<< accessLevelModifier ~ typeInheritanceClause ~ "{" ~ extensionBody ~ "}" } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Types.html#//apple_ref/swift/grammar/type-identifier public struct TypeIdentifier: NodeType { public var typeName:Identifier public var genericArgumentClause:GenericArgumentClause? public var subtypeIdentifier:(()->TypeIdentifier)? public init(typeName:Identifier, genericArgumentClause:GenericArgumentClause?) { self.typeName = typeName self.genericArgumentClause = genericArgumentClause } public init(_ parts:[(typeName:Identifier, genericArgumentClause:GenericArgumentClause?)]) { precondition(parts.count >= 1) switch parts.count { case 0: fatalError("Bad input.") case 1: self.init(parts[0]) subtypeIdentifier = nil default: self.init(parts[0]) let a = TypeIdentifier(parts.rest.array) subtypeIdentifier = { a } } } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< typeName ~ genericArgumentClause if let x1 = subtypeIdentifier { w.writeToken(".") w <<< x1() } } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/GenericParametersAndArguments.html#//apple_ref/doc/uid/TP40014097-CH37-XID_872 public struct GenericArgumentClause: NodeType { public var genericArguments : Type public var additionalArgument : (()->GenericArgumentClause)? public init(_ argument:Type) { genericArguments = argument additionalArgument = nil } public init(_ arguments:[Type]) { precondition(arguments.count >= 1) genericArguments = arguments.first! if arguments.count > 1 { let rest = GenericArgumentClause(arguments.rest.array) additionalArgument = { rest } } additionalArgument = nil } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< genericArguments if let a1 = additionalArgument { w.writeToken(",") w <<< a1() } } } //public struct SubscriptDeclaration { // //} public typealias Identifier = String
f448836dfc0cb6f496a212fdda6021e1
28.11032
234
0.734963
false
false
false
false
huangboju/QMUI.swift
refs/heads/master
QMUI.swift/QMUIKit/UIComponents/ImagePickerLibrary/QMUIImagePickerCollectionViewCell.swift
mit
1
// // QMUIImagePickerCollectionViewCell.swift // QMUI.swift // // Created by 黄伯驹 on 2017/7/10. // Copyright © 2017年 伯驹 黄. All rights reserved. // // checkbox 的 margin 默认值 let QMUIImagePickerCollectionViewCellDefaultCheckboxButtonMargins = UIEdgeInsets(top: 6, left: 0, bottom: 0, right: 6) private let QMUIImagePickerCollectionViewCellDefaultVideoMarkImageViewMargins = UIEdgeInsets(top: 0, left: 8, bottom: 8, right: 0) /** * 图片选择空间里的九宫格 cell,支持显示 checkbox、饼状进度条及重试按钮(iCloud 图片需要) */ class QMUIImagePickerCollectionViewCell: UICollectionViewCell { /// checkbox 未被选中时显示的图片 var checkboxImage: UIImage! { didSet { if checkboxImage != oldValue { checkboxButton.setImage(checkboxImage, for: .normal) checkboxButton.sizeToFit() } } } /// checkbox 被选中时显示的图片 var checkboxCheckedImage: UIImage! { didSet { if checkboxCheckedImage != oldValue { checkboxButton.setImage(checkboxCheckedImage, for: .selected) checkboxButton.setImage(checkboxCheckedImage, for: [.selected, .highlighted]) checkboxButton.sizeToFit() } } } /// checkbox 的 margin,定位从每个 cell(即每张图片)的最右边开始计算 var checkboxButtonMargins = QMUIImagePickerCollectionViewCellDefaultCheckboxButtonMargins /// videoMarkImageView 的 icon var videoMarkImage: UIImage! = QMUIHelper.image(name: "QMUI_pickerImage_video_mark") { didSet { if videoMarkImage != oldValue { videoMarkImageView?.image = videoMarkImage videoMarkImageView?.sizeToFit() } } } /// videoMarkImageView 的 margin,定位从每个 cell(即每张图片)的左下角开始计算 var videoMarkImageViewMargins: UIEdgeInsets = QMUIImagePickerCollectionViewCellDefaultVideoMarkImageViewMargins /// videoDurationLabel 的字号 var videoDurationLabelFont: UIFont = UIFontMake(12) { didSet { if videoDurationLabelFont != oldValue { videoDurationLabel?.font = videoDurationLabelFont videoDurationLabel?.qmui_calculateHeightAfterSetAppearance() } } } /// videoDurationLabel 的字体颜色 var videoDurationLabelTextColor: UIColor = UIColorWhite { didSet { if videoDurationLabelTextColor != oldValue { videoDurationLabel?.textColor = videoDurationLabelTextColor } } } /// videoDurationLabel 布局是对齐右下角再做 margins 偏移 var videoDurationLabelMargins: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 6, right: 6) private(set) var contentImageView: UIImageView! private(set) var checkboxButton: UIButton! private var _videoMarkImageView: UIImageView? var videoMarkImageView: UIImageView? { initVideoRelatedViewsIfNeeded() return _videoMarkImageView } private var _videoDurationLabel: UILabel? var videoDurationLabel: UILabel? { initVideoRelatedViewsIfNeeded() return _videoDurationLabel } private var _videoBottomShadowLayer: CAGradientLayer? var videoBottomShadowLayer: CAGradientLayer? { initVideoRelatedViewsIfNeeded() return _videoBottomShadowLayer } var isSelectable: Bool = false { didSet { if downloadStatus == .succeed { checkboxButton.isHidden = !isSelectable } } } var isChecked: Bool = false { didSet { if isSelectable { checkboxButton.isSelected = isChecked QMUIImagePickerHelper.removeSpringAnimationOfImageChecked(with: checkboxButton) if isChecked { QMUIImagePickerHelper.springAnimationOfImageChecked(with: checkboxButton) } } } } // Cell 中对应资源的下载状态,这个值的变动会相应地调整 UI 表现 var downloadStatus: QMUIAssetDownloadStatus = .succeed { didSet { if isSelectable { checkboxButton.isHidden = !isSelectable } } } var assetIdentifier: String? // 当前这个 cell 正在展示的 QMUIAsset 的 identifier override init(frame: CGRect) { super.init(frame: frame) initImagePickerCollectionViewCellUI() } private func initImagePickerCollectionViewCellUI() { contentImageView = UIImageView() contentImageView.contentMode = .scaleAspectFill contentImageView.clipsToBounds = true contentView.addSubview(contentImageView) checkboxButton = QMUIButton() checkboxButton.qmui_automaticallyAdjustTouchHighlightedInScrollView = true checkboxButton.qmui_outsideEdge = UIEdgeInsets(top: -6, left: -6, bottom: -6, right: -6) checkboxButton.isHidden = true contentView.addSubview(checkboxButton) checkboxImage = QMUIHelper.image(name: "QMUI_pickerImage_checkbox") checkboxCheckedImage = QMUIHelper.image(name: "QMUI_pickerImage_checkbox_checked") } private func initVideoBottomShadowLayerIfNeeded() { if _videoBottomShadowLayer == nil { _videoBottomShadowLayer = CAGradientLayer() _videoBottomShadowLayer!.qmui_removeDefaultAnimations() _videoBottomShadowLayer!.colors = [ UIColor(r: 0, g: 0, b: 0).cgColor, UIColor(r: 0, g: 0, b: 0, a: 0.6).cgColor, ] contentView.layer.addSublayer(_videoBottomShadowLayer!) setNeedsLayout() } } private func initVideoMarkImageViewIfNeed() { if _videoMarkImageView != nil { return } _videoMarkImageView = UIImageView() _videoMarkImageView?.image = videoMarkImage _videoMarkImageView?.sizeToFit() contentView.addSubview(_videoMarkImageView!) setNeedsLayout() } private func initVideoDurationLabelIfNeed() { if _videoDurationLabel != nil { return } _videoDurationLabel = UILabel() _videoDurationLabel?.font = videoDurationLabelFont _videoDurationLabel?.textColor = videoDurationLabelTextColor contentView.addSubview(_videoDurationLabel!) setNeedsLayout() } private func initVideoRelatedViewsIfNeeded() { initVideoBottomShadowLayerIfNeeded() initVideoMarkImageViewIfNeed() initVideoDurationLabelIfNeed() } override func layoutSubviews() { super.layoutSubviews() contentImageView.frame = contentView.bounds if isSelectable { checkboxButton.frame = checkboxButton.frame.setXY(contentView.bounds.width - checkboxButtonMargins.right - checkboxButton.frame.width, checkboxButtonMargins.top) } if let videoBottomShadowLayer = _videoBottomShadowLayer, let videoMarkImageView = _videoMarkImageView, let videoDurationLabel = _videoDurationLabel { videoMarkImageView.frame = videoMarkImageView.frame.setXY(videoMarkImageViewMargins.left, contentView.bounds.height - videoMarkImageView.bounds.height - videoMarkImageViewMargins.bottom) videoDurationLabel.sizeToFit() let minX = contentView.bounds.width - videoDurationLabelMargins.right - videoDurationLabel.bounds.width let minY = contentView.bounds.height - videoDurationLabelMargins.bottom - videoDurationLabel.bounds.height videoDurationLabel.frame = videoDurationLabel.frame.setXY(minX, minY) let videoBottomShadowLayerHeight = contentView.bounds.height - videoMarkImageView.frame.minY + videoMarkImageViewMargins.bottom // 背景阴影遮罩的高度取决于(视频 icon 的高度 + 上下 margin) videoBottomShadowLayer.frame = CGRectFlat(0, contentView.bounds.height - videoBottomShadowLayerHeight, contentView.bounds.width, videoBottomShadowLayerHeight) } } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } }
f133d054269a4791aabe86eb65b7d167
35.785388
198
0.65926
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat/Controllers/Preferences/Profile/EditProfileTableViewController.swift
mit
1
// // EditProfileTableViewController.swift // Rocket.Chat // // Created by Filipe Alvarenga on 27/02/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit import MBProgressHUD import SwiftyJSON // swiftlint:disable file_length type_body_length final class EditProfileTableViewController: BaseTableViewController, MediaPicker { static let identifier = String(describing: EditProfileTableViewController.self) @IBOutlet weak var statusValueLabel: UILabel! @IBOutlet weak var statusLabel: UILabel! { didSet { statusLabel.text = viewModel.statusTitle } } @IBOutlet weak var name: UITextField! { didSet { name.placeholder = viewModel.namePlaceholder } } @IBOutlet weak var username: UITextField! { didSet { username.placeholder = viewModel.usernamePlaceholder } } @IBOutlet weak var email: UITextField! { didSet { email.placeholder = viewModel.emailPlaceholder } } @IBOutlet weak var changeYourPassword: UILabel! { didSet { changeYourPassword.text = viewModel.changeYourPasswordTitle } } @IBOutlet weak var avatarButton: UIButton! { didSet { avatarButton.accessibilityLabel = avatarButtonAccessibilityLabel } } var avatarView: AvatarView = { let avatarView = AvatarView() avatarView.isUserInteractionEnabled = false avatarView.translatesAutoresizingMaskIntoConstraints = false avatarView.layer.cornerRadius = 15 avatarView.layer.masksToBounds = true return avatarView }() lazy var activityIndicator: UIActivityIndicatorView = { let activityIndicator = UIActivityIndicatorView(style: .gray) activityIndicator.startAnimating() return activityIndicator }() let editingAvatarImage = UIImage(named: "Camera")?.imageWithTint(.RCEditingAvatarColor()) var editButton: UIBarButtonItem? var saveButton: UIBarButtonItem? var cancelButton: UIBarButtonItem? let api = API.current() var avatarFile: FileUpload? var authSettings: AuthSettings? { return AuthSettingsManager.shared.settings } var numberOfSections: Int { guard !isLoading else { return 0 } guard let authSettings = authSettings else { return 2 } return !authSettings.isAllowedToEditProfile || !authSettings.isAllowedToEditPassword ? 2 : 3 } var canEditAnyInfo: Bool { guard authSettings?.isAllowedToEditProfile ?? false, authSettings?.isAllowedToEditAvatar ?? false || authSettings?.isAllowedToEditName ?? false || authSettings?.isAllowedToEditUsername ?? false || authSettings?.isAllowedToEditEmail ?? false else { return false } return true } var isUpdatingUser = false var isUploadingAvatar = false var isLoading = true var currentPassword: String? var user: User? = User() { didSet { bindUserData() } } private let viewModel = EditProfileViewModel() // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard)) tapGesture.cancelsTouchesInView = false tableView.addGestureRecognizer(tapGesture) editButton = UIBarButtonItem(title: viewModel.editButtonTitle, style: .plain, target: self, action: #selector(beginEditing)) saveButton = UIBarButtonItem(title: viewModel.saveButtonTitle, style: .done, target: self, action: #selector(saveProfile(_:))) cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(didPressCancelEditingButton)) navigationItem.title = viewModel.title disableUserInteraction() setupAvatarButton() fetchUserData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateUserStatus() } // MARK: Setup func setupAvatarButton() { avatarButton.addSubview(avatarView) avatarView.topAnchor.constraint(equalTo: avatarButton.topAnchor).isActive = true avatarView.bottomAnchor.constraint(equalTo: avatarButton.bottomAnchor).isActive = true avatarView.leadingAnchor.constraint(equalTo: avatarButton.leadingAnchor).isActive = true avatarView.trailingAnchor.constraint(equalTo: avatarButton.trailingAnchor).isActive = true if let imageView = avatarButton.imageView { avatarButton.bringSubviewToFront(imageView) } } func fetchUserData() { avatarButton.isHidden = true let fetchUserLoader = MBProgressHUD.showAdded(to: self.view, animated: true) fetchUserLoader.mode = .indeterminate let stopLoading = { self.avatarButton.isHidden = false fetchUserLoader.hide(animated: true) } let meRequest = MeRequest() api?.fetch(meRequest) { [weak self] response in stopLoading() switch response { case .resource(let resource): if let errorMessage = resource.errorMessage { Alert(key: "alert.load_profile_error").withMessage(errorMessage).present(handler: { _ in self?.navigationController?.popViewController(animated: true) }) } else { self?.user = resource.user self?.isLoading = false if self?.canEditAnyInfo ?? false { self?.navigationItem.rightBarButtonItem = self?.editButton } self?.tableView.reloadData() } case .error: Alert(key: "alert.load_profile_error").present(handler: { _ in self?.navigationController?.popViewController(animated: true) }) } } } func bindUserData() { avatarView.username = user?.username name.text = user?.name username.text = user?.username email.text = user?.emails.first?.email updateUserStatus() } func updateUserStatus() { statusValueLabel.text = viewModel.userStatus } // MARK: State Management var isEditingProfile = false { didSet { applyTheme() } } @objc func beginEditing() { isEditingProfile = true navigationItem.title = viewModel.editingTitle navigationItem.rightBarButtonItem = saveButton navigationItem.hidesBackButton = true navigationItem.leftBarButtonItem = cancelButton if authSettings?.isAllowedToEditAvatar ?? false { avatarButton.setImage(editingAvatarImage, for: .normal) avatarButton.accessibilityLabel = avatarEditingButtonAccessibilityLabel } enableUserInteraction() } @objc func endEditing() { isEditingProfile = false bindUserData() navigationItem.title = viewModel.title navigationItem.hidesBackButton = false navigationItem.leftBarButtonItem = nil navigationItem.rightBarButtonItem = editButton if authSettings?.isAllowedToEditAvatar ?? false { avatarButton.setImage(nil, for: .normal) avatarButton.accessibilityLabel = avatarButtonAccessibilityLabel } disableUserInteraction() } func enableUserInteraction() { avatarButton.isEnabled = authSettings?.isAllowedToEditAvatar ?? false if authSettings?.isAllowedToEditName ?? false { name.isEnabled = true } else { name.isEnabled = false } if authSettings?.isAllowedToEditUsername ?? false { username.isEnabled = true } else { username.isEnabled = false } if authSettings?.isAllowedToEditEmail ?? false { email.isEnabled = true } else { email.isEnabled = false } if authSettings?.isAllowedToEditName ?? false { name.becomeFirstResponder() } else if authSettings?.isAllowedToEditUsername ?? false { username.becomeFirstResponder() } else if authSettings?.isAllowedToEditEmail ?? false { email.becomeFirstResponder() } } func disableUserInteraction() { hideKeyboard() avatarButton.isEnabled = false name.isEnabled = false username.isEnabled = false email.isEnabled = false } // MARK: Accessibility var avatarButtonAccessibilityLabel: String? = VOLocalizedString("preferences.profile.edit.label") var avatarEditingButtonAccessibilityLabel: String? = VOLocalizedString("preferences.profile.editing.label") // MARK: Actions @IBAction func saveProfile(_ sender: UIBarButtonItem) { hideKeyboard() guard let name = name.text, let username = username.text, let email = email.text, !name.isEmpty, !username.isEmpty, !email.isEmpty else { Alert(key: "alert.update_profile_empty_fields").present() return } guard email.isValidEmail else { Alert(key: "alert.update_profile_invalid_email").present() return } var userRaw = JSON([:]) if name != self.user?.name { userRaw["name"].string = name } if username != self.user?.username { userRaw["username"].string = username } if email != self.user?.emails.first?.email { userRaw["emails"] = [["address": email]] } let shouldUpdateUser = name != self.user?.name || username != self.user?.username || email != self.user?.emails.first?.email if !shouldUpdateUser { update(user: nil) return } let user = User() user.map(userRaw, realm: nil) if !(self.user?.emails.first?.email == email) { requestPasswordToUpdate(user: user) } else { update(user: user) } } fileprivate func requestPasswordToUpdate(user: User) { let alert = UIAlertController( title: localized("myaccount.settings.profile.password_required.title"), message: localized("myaccount.settings.profile.password_required.message"), preferredStyle: .alert ) let updateUserAction = UIAlertAction(title: localized("myaccount.settings.profile.actions.save"), style: .default, handler: { _ in self.currentPassword = alert.textFields?.first?.text self.update(user: user) }) updateUserAction.isEnabled = false alert.addTextField(configurationHandler: { textField in textField.placeholder = localized("myaccount.settings.profile.password_required.placeholder") textField.textContentType = .password textField.isSecureTextEntry = true _ = NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main) { _ in updateUserAction.isEnabled = !(textField.text?.isEmpty ?? false) } }) alert.addAction(UIAlertAction(title: localized("global.cancel"), style: .cancel, handler: nil)) alert.addAction(updateUserAction) present(alert, animated: true) } /** This method will only update the avatar image of the user. */ fileprivate func updateAvatar() { guard let avatarFile = avatarFile else { return } startLoading() isUploadingAvatar = true let client = API.current()?.client(UploadClient.self) client?.uploadAvatar(data: avatarFile.data, filename: avatarFile.name, mimetype: avatarFile.type, completion: { [weak self] _ in guard let self = self else { return } if !self.isUpdatingUser { self.alertSuccess(title: localized("alert.update_profile_success.title")) } self.isUploadingAvatar = false self.avatarView.avatarPlaceholder = UIImage(data: avatarFile.data) self.avatarView.refreshCurrentAvatar(withCachedData: avatarFile.data, completion: { self.stopLoading() }) self.avatarFile = nil }) } /** This method will only update the user information. */ fileprivate func updateUserInformation(user: User) { isUpdatingUser = true if !isUploadingAvatar { startLoading() } let stopLoading: (_ shouldEndEditing: Bool) -> Void = { [weak self] shouldEndEditing in self?.isUpdatingUser = false self?.stopLoading(shouldEndEditing: shouldEndEditing) } let updateUserRequest = UpdateUserRequest(user: user, currentPassword: currentPassword) api?.fetch(updateUserRequest) { [weak self] response in guard let self = self else { return } switch response { case .resource(let resource): if let errorMessage = resource.errorMessage { stopLoading(false) Alert(key: "alert.update_profile_error").withMessage(errorMessage).present() return } self.user = resource.user stopLoading(true) if !self.isUploadingAvatar { self.alertSuccess(title: localized("alert.update_profile_success.title")) } case .error: stopLoading(false) Alert(key: "alert.update_profile_error").present() } } } /** This method will check if there's an new avatar to be updated and if there's any information on the user to be updated as well. They're both different API calls that need to be made. */ fileprivate func update(user: User?) { if avatarFile != nil { updateAvatar() } guard let user = user else { if !isUploadingAvatar { endEditing() } return } updateUserInformation(user: user) } @IBAction func didPressAvatarButton(_ sender: UIButton) { hideKeyboard() let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) if UIImagePickerController.isSourceTypeAvailable(.camera) { alert.addAction(UIAlertAction(title: localized("chat.upload.take_photo"), style: .default, handler: { (_) in self.openCamera() })) } alert.addAction(UIAlertAction(title: localized("chat.upload.choose_from_library"), style: .default, handler: { (_) in self.openPhotosLibrary() })) alert.addAction(UIAlertAction(title: localized("global.cancel"), style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } @objc func didPressCancelEditingButton() { avatarView.avatarPlaceholder = nil avatarView.imageView.image = nil endEditing() } @objc func hideKeyboard() { view.endEditing(true) } func startLoading() { view.isUserInteractionEnabled = false navigationItem.leftBarButtonItem?.isEnabled = false navigationItem.rightBarButtonItem = UIBarButtonItem(customView: activityIndicator) } func stopLoading(shouldEndEditing: Bool = true, shouldRefreshAvatar: Bool = false) { if !isUpdatingUser, !isUploadingAvatar { view.isUserInteractionEnabled = true navigationItem.leftBarButtonItem?.isEnabled = true if shouldEndEditing { endEditing() } else { navigationItem.rightBarButtonItem = saveButton } } } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let newPassword = segue.destination as? NewPasswordTableViewController { newPassword.passwordUpdated = { [weak self] newPasswordViewController in newPasswordViewController?.navigationController?.popViewControler(animated: true, completion: { self?.alertSuccess(title: localized("alert.update_password_success.title")) }) } } } // MARK: UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return numberOfSections } // MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 1: return viewModel.profileSectionTitle default: return "" } } } extension EditProfileTableViewController: UINavigationControllerDelegate {} extension EditProfileTableViewController: UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { let filename = String.random() var file: FileUpload? if let image = info[.editedImage] as? UIImage { file = UploadHelper.file( for: image.compressedForUpload, name: "\(filename.components(separatedBy: ".").first ?? "image").jpeg", mimeType: "image/jpeg" ) avatarView.imageView.image = image } avatarFile = file dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } } extension EditProfileTableViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { switch textField { case name: username.becomeFirstResponder() case username: email.becomeFirstResponder() case email: hideKeyboard() default: break } return true } } extension EditProfileTableViewController { override func applyTheme() { super.applyTheme() guard let theme = view.theme else { return } switch isEditingProfile { case false: name.textColor = theme.titleText username.textColor = theme.titleText email.textColor = theme.titleText case true: name.textColor = (authSettings?.isAllowedToEditName ?? false) ? theme.titleText : theme.auxiliaryText username.textColor = (authSettings?.isAllowedToEditName ?? false) ? theme.titleText : theme.auxiliaryText email.textColor = (authSettings?.isAllowedToEditName ?? false) ? theme.titleText : theme.auxiliaryText } } }
e68fcd4b1d882066c8c1262c66d155b2
31.458404
156
0.624124
false
false
false
false
darina/omim
refs/heads/master
iphone/Maps/Bookmarks/BookmarksTabViewController.swift
apache-2.0
4
@objc(MWMBookmarksTabViewController) final class BookmarksTabViewController: TabViewController { @objc enum ActiveTab: Int { case user = 0 case catalog } private static let selectedIndexKey = "BookmarksTabViewController_selectedIndexKey" @objc public var activeTab: ActiveTab = ActiveTab(rawValue: UserDefaults.standard.integer(forKey: BookmarksTabViewController.selectedIndexKey)) ?? .user { didSet { UserDefaults.standard.set(activeTab.rawValue, forKey: BookmarksTabViewController.selectedIndexKey) } } private weak var coordinator: BookmarksCoordinator? @objc init(coordinator: BookmarksCoordinator?) { super.init(nibName: nil, bundle: nil) self.coordinator = coordinator } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let bookmarks = BMCViewController(coordinator: coordinator) let catalog = DownloadedBookmarksViewController(coordinator: coordinator) bookmarks.title = L("bookmarks") catalog.title = L("guides") viewControllers = [bookmarks, catalog] title = L("bookmarks_guides"); tabView.selectedIndex = activeTab.rawValue tabView.delegate = self } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) activeTab = ActiveTab(rawValue: tabView.selectedIndex ?? 0) ?? .user } } extension BookmarksTabViewController: TabViewDelegate { func tabView(_ tabView: TabView, didSelectTabAt index: Int) { let selectedTab = index == 0 ? "my" : "downloaded" Statistics.logEvent("Bookmarks_Tab_click", withParameters: [kStatValue : selectedTab]) } }
46dbbc7af9a725a49cb288e7ad65a3b5
31.018868
104
0.735415
false
false
false
false
nkirby/Humber
refs/heads/master
Humber/_src/Theming/ThemeElements.swift
mit
1
// ======================================================= // Humber // Nathaniel Kirby // ======================================================= import UIKit internal enum ColorType { case PrimaryTextColor case SecondaryTextColor case DisabledTextColor case TintColor case ViewBackgroundColor case CellBackgroundColor case DividerColor } internal enum FontType { case Bold(CGFloat) case Regular(CGFloat) case Italic(CGFloat) } internal protocol Themable { var name: String { get } func color(type type: ColorType) -> UIColor func font(type type: FontType) -> UIFont }
9009b41d5e8579cd94856f57fcac34bb
20.758621
58
0.575277
false
false
false
false
Ryce/flickrpickr
refs/heads/master
Carthage/Checkouts/flickrpickr-sdk/Carthage/Checkouts/judokit/Source/DateInputField.swift
mit
2
// // DateTextField.swift // JudoKit // // Copyright (c) 2016 Alternative Payments Ltd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit 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 } } fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l <= r default: return !(rhs < lhs) } } /** The DateTextField allows two different modes of input. - Picker: Use a custom UIPickerView with month and year fields - Text: Use a common Numpad Keyboard as text input method */ public enum DateInputType { /// DateInputTypePicker using a UIPicker as an input method case picker /// DateInputTypeText using a Keyboard as an input method case text } /** The DateInputField is an input field configured to detect, validate and dates that are set to define a start or end date of various types of credit cards. */ open class DateInputField: JudoPayInputField { /// The datePicker showing months and years to pick from for expiry or start date input let datePicker = UIPickerView() /// The date formatter that shows the date in the same way it is written on a credit card fileprivate let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "MM/yy" return formatter }() /// The current year on a Gregorian calendar fileprivate let currentYear = (Calendar.current as NSCalendar).component(.year, from: Date()) /// The current month on a Gregorian calendar fileprivate let currentMonth = (Calendar.current as NSCalendar).component(.month, from: Date()) /// Boolean stating whether input field should identify as a start or end date open var isStartDate: Bool = false { didSet { self.textField.attributedPlaceholder = NSAttributedString(string: self.title(), attributes: [NSForegroundColorAttributeName:self.theme.getPlaceholderTextColor()]) } } /// Boolean stating whether input field should identify as a start or end date open var isVisible: Bool = false /// Variable defining the input type (text or picker) open var dateInputType: DateInputType = .text { didSet { switch dateInputType { case .picker: self.textField.inputView = self.datePicker let month = NSString(format: "%02i", currentMonth) let year = NSString(format: "%02i", currentYear - 2000) // FIXME: not quite happy with this, must be a better way self.textField.text = "\(month)/\(year)" self.datePicker.selectRow(currentMonth - 1, inComponent: 0, animated: false) break case .text: self.textField.inputView = nil self.textField.keyboardType = .numberPad } } } // MARK: Initializers /** Setup the view */ override func setupView() { super.setupView() // Input method should be via date picker self.datePicker.delegate = self self.datePicker.dataSource = self if self.dateInputType == .picker { self.textField.inputView = self.datePicker let month = NSString(format: "%02i", currentMonth) let year = NSString(format: "%02i", currentYear - 2000) self.textField.text = "\(month)/\(year)" self.datePicker.selectRow(currentMonth - 1, inComponent: 0, animated: false) } } // MARK: UITextFieldDelegate /** Delegate method implementation - parameter textField: Text field - parameter range: Range - parameter string: String - returns: boolean to change characters in given range for a textfield */ open func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // Only handle calls if textinput is selected guard self.dateInputType == .text else { return true } // Only handle delegate calls for own textfield guard textField == self.textField else { return false } // Get old and new text let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string) if newString.characters.count == 0 { return true } else if newString.characters.count == 1 { return newString == "0" || newString == "1" } else if newString.characters.count == 2 { // if deletion is handled and user is trying to delete the month no slash should be added guard string.characters.count > 0 else { return true } guard Int(newString) > 0 && Int(newString) <= 12 else { return false } self.textField.text = newString + "/" return false } else if newString.characters.count == 3 { return newString.characters.last == "/" } else if newString.characters.count == 4 { // FIXME: need to make sure that number is numeric let deciYear = Int((Double((Calendar.current as NSCalendar).component(.year, from: Date()) - 2000) / 10.0)) let lastChar = Int(String(newString.characters.last!)) if self.isStartDate { return lastChar == deciYear || lastChar == deciYear - 1 } else { return lastChar == deciYear || lastChar == deciYear + 1 } } else if newString.characters.count == 5 { return true } else { self.delegate?.dateInput(self, error: JudoError(.inputLengthMismatchError)) return false } } // MARK: Custom methods /** Check if this inputField is valid - returns: true if valid input */ open override func isValid() -> Bool { guard let dateString = textField.text , dateString.characters.count == 5, let beginningOfMonthDate = self.dateFormatter.date(from: dateString) else { return false } if self.isStartDate { let minimumDate = Date().dateByAddingYears(-10) return beginningOfMonthDate.compare(Date()) == .orderedAscending && beginningOfMonthDate.compare(minimumDate!) == .orderedDescending } else { let endOfMonthDate = beginningOfMonthDate.dateAtTheEndOfMonth() let maximumDate = Date().dateByAddingYears(10) return endOfMonthDate.compare(Date()) == .orderedDescending && endOfMonthDate.compare(maximumDate!) == .orderedAscending } } /** Subclassed method that is called when textField content was changed - parameter textField: the textfield of which the content has changed */ open override func textFieldDidChangeValue(_ textField: UITextField) { super.textFieldDidChangeValue(textField) self.didChangeInputText() guard let text = textField.text , text.characters.count == 5 else { return } if self.dateFormatter.date(from: text) == nil { return } if self.isValid() { self.delegate?.dateInput(self, didFindValidDate: textField.text!) } else { var errorMessage = "Check expiry date" if self.isStartDate { errorMessage = "Check start date" } self.delegate?.dateInput(self, error: JudoError(.invalidEntry, errorMessage)) } } /** The placeholder string for the current inputField - returns: an Attributed String that is the placeholder of the receiver */ open override func placeholder() -> NSAttributedString? { return NSAttributedString(string: self.title(), attributes: [NSForegroundColorAttributeName:self.theme.getPlaceholderTextColor()]) } /** Title of the receiver inputField - returns: a string that is the title of the receiver */ open override func title() -> String { return isStartDate ? "Start date" : "Expiry date" } /** Hint label text - returns: string that is shown as a hint when user resides in a inputField for more than 5 seconds */ open override func hintLabelText() -> String { return "MM/YY" } } // MARK: UIPickerViewDataSource extension DateInputField: UIPickerViewDataSource { /** Datasource method for datePickerView - parameter pickerView: PickerView that calls its delegate - returns: The number of components in the pickerView */ public func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } /** Datasource method for datePickerView - parameter pickerView: PickerView that calls its delegate - parameter component: A given component - returns: number of rows in component */ public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return component == 0 ? 12 : 11 } } // MARK: UIPickerViewDelegate extension DateInputField: UIPickerViewDelegate { /** Delegate method for datePickerView - parameter pickerView: The caller - parameter row: The row - parameter component: The component - returns: content of a given component and row */ public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { switch component { case 0: return NSString(format: "%02i", row + 1) as String case 1: return NSString(format: "%02i", (self.isStartDate ? currentYear - row : currentYear + row) - 2000) as String default: return nil } } /** Delegate method for datePickerView that had a given row in a component selected - parameter pickerView: The caller - parameter row: The row - parameter component: The component */ public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { // Need to use NSString because Precision String Format Specifier is easier this way if component == 0 { let month = NSString(format: "%02i", row + 1) let oldDateString = self.textField.text! let year = oldDateString.substring(from: oldDateString.characters.index(oldDateString.endIndex, offsetBy: -2)) self.textField.text = "\(month)/\(year)" } else if component == 1 { let oldDateString = self.textField.text! let month = oldDateString.substring(to: oldDateString.characters.index(oldDateString.startIndex, offsetBy: 2)) let year = NSString(format: "%02i", (self.isStartDate ? currentYear - row : currentYear + row) - 2000) self.textField.text = "\(month)/\(year)" } } }
6a1fc24279b65502a48bcbc6645e8c73
33.538462
174
0.624324
false
false
false
false
kArTeL/tispr-card-stack
refs/heads/master
TisprCardStack/TisprCardStack/TisprCardStackViewLayout.swift
apache-2.0
2
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ // // TisprCardStackViewLayout.swift // // Created by Andrei Pitsko on 07/12/15. // Copyright (c) 2015 BuddyHopp Inc. All rights reserved. // import UIKit public class TisprCardStackViewLayout: UICollectionViewLayout, UIGestureRecognizerDelegate { // MARK: - Properties /// The index of the card that is currently on top of the stack. The index 0 represents the oldest card of the stack. var index: Int = 0 { didSet { //workaround for zIndex draggedCellPath = oldValue > index ? NSIndexPath(forItem: index, inSection: 0) : NSIndexPath(forItem: oldValue, inSection: 0) collectionView?.performBatchUpdates({ let x: Void = self.invalidateLayout() }, completion: nil) delegate?.cardDidChangeState(oldValue) } } var delegate: TisprCardStackViewControllerDelegate? /// The maximum number of cards displayed on the top stack. This value includes the currently visible card. @IBInspectable public var topStackMaximumSize: Int = 3 /// The maximum number of cards displayed on the bottom stack. @IBInspectable public var bottomStackMaximumSize: Int = 3 /// The visible height of the card of the bottom stack. @IBInspectable public var bottomStackCardHeight: CGFloat = 50 /// The size of a card in the stack layout. @IBInspectable var cardSize: CGSize = CGSizeMake(280, 380) // The inset or outset margins for the rectangle around the card. @IBInspectable public var cardInsets: UIEdgeInsets = UIEdgeInsetsZero /// A Boolean value indicating whether the pan and swipe gestures on cards are enabled. var gesturesEnabled: Bool = false { didSet { if (gesturesEnabled) { let recognizer = UIPanGestureRecognizer(target: self, action: Selector("handlePan:")) collectionView?.addGestureRecognizer(recognizer) panGestureRecognizer = recognizer panGestureRecognizer!.delegate = self swipeRecognizerDown = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:")) swipeRecognizerDown!.direction = UISwipeGestureRecognizerDirection.Down swipeRecognizerDown!.delegate = self collectionView?.addGestureRecognizer(swipeRecognizerDown!) swipeRecognizerDown!.requireGestureRecognizerToFail(panGestureRecognizer!) swipeRecognizerUp = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:")) swipeRecognizerUp!.direction = UISwipeGestureRecognizerDirection.Up swipeRecognizerUp!.delegate = self collectionView?.addGestureRecognizer(swipeRecognizerUp!) swipeRecognizerUp!.requireGestureRecognizerToFail(panGestureRecognizer!) } else { if let recognizer = panGestureRecognizer { collectionView?.removeGestureRecognizer(recognizer) } if let swipeDownRecog = swipeRecognizerDown { collectionView?.removeGestureRecognizer(swipeDownRecog) } if let swipeUpRecog = swipeRecognizerUp { collectionView?.removeGestureRecognizer(swipeUpRecog) } } } } // Index path of dragged cell private var draggedCellPath: NSIndexPath? // The initial center of the cell being dragged. private var initialCellCenter: CGPoint? // The rotation values of the bottom stack cards. private var bottomStackRotations = [Int: Double]() // Is the animation for new cards in progress? private var newCardAnimationInProgress: Bool = false /// Cards from bottom stack will be rotated with angle = coefficientOfRotation * hade. private let coefficientOfRotation: Double = 0.25 private let angleOfRotationForNewCardAnimation: CGFloat = 0.25 private let verticalOffsetBetweenCardsInTopStack = 10 private let centralCardYPosition = 70 private var panGestureRecognizer: UIPanGestureRecognizer? private var swipeRecognizerDown: UISwipeGestureRecognizer? private var swipeRecognizerUp: UISwipeGestureRecognizer? private let minimumXPanDistanceToSwipe: CGFloat = 100 private let minimumYPanDistanceToSwipe: CGFloat = 60 // MARK: - Getting the Collection View Information override public func collectionViewContentSize() -> CGSize { return collectionView!.frame.size } // MARK: - Providing Layout Attributes override public func initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { var result :UICollectionViewLayoutAttributes? if itemIndexPath.item == collectionView!.numberOfItemsInSection(0) - 1 && newCardAnimationInProgress { result = UICollectionViewLayoutAttributes(forCellWithIndexPath: itemIndexPath) let yPosition = collectionViewContentSize().height - cardSize.height //Random direction let directionFromRight = arc4random() % 2 == 0 let xPosition = directionFromRight ? collectionViewContentSize().width : -cardSize.width let cardFrame = CGRectMake(CGFloat(xPosition), yPosition, cardSize.width, cardSize.height) result!.frame = cardFrame result!.zIndex = 1000 - itemIndexPath.item result!.hidden = false result!.transform3D = CATransform3DMakeRotation(directionFromRight ?angleOfRotationForNewCardAnimation : -angleOfRotationForNewCardAnimation, 0, 0, 1) } return result } public override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { let indexPaths = indexPathsForElementsInRect(rect) let layoutAttributes = indexPaths.map { self.layoutAttributesForItemAtIndexPath($0) } return layoutAttributes } public override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { var result = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) if (indexPath.item >= index) { result = layoutAttributesForTopStackItemWithInitialAttributes(result) //we have to hide invisible cards in top stask due perfomance issues due shadows result.hidden = (result.indexPath.item >= index + topStackMaximumSize) } else { result = layoutAttributesForBottomStackItemWithInitialAttributes(result) //we have to hide invisible cards in bottom stask due perfomance issues due shadows result.hidden = (result.indexPath.item < (index - bottomStackMaximumSize)) } if indexPath.item == draggedCellPath?.item { //workaround for zIndex result.zIndex = 100000 } else { result.zIndex = (indexPath.item >= index) ? (1000 - indexPath.item) : (1000 + indexPath.item) } return result } // MARK: - Implementation private func indexPathsForElementsInRect(rect: CGRect) -> [NSIndexPath] { var result = [NSIndexPath]() let count = collectionView!.numberOfItemsInSection(0) let topStackCount = min(count - (index + 1), topStackMaximumSize - 1) let bottomStackCount = min(index, bottomStackMaximumSize) let start = index - bottomStackCount let end = (index + 1) + topStackCount for i in start..<end { result.append(NSIndexPath(forItem: i, inSection: 0)) } return result } private func layoutAttributesForTopStackItemWithInitialAttributes(attributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { //we should not change position for card which will be hidden for good animation let minYPosition = centralCardYPosition - verticalOffsetBetweenCardsInTopStack*(topStackMaximumSize - 1) var yPosition = centralCardYPosition - verticalOffsetBetweenCardsInTopStack*(attributes.indexPath.row - index) yPosition = max(yPosition,minYPosition) //right position for new card if attributes.indexPath.item == collectionView!.numberOfItemsInSection(0) - 1 && newCardAnimationInProgress { //New card has to be displayed if there are no topStackMaximumSize cards in the top stack if attributes.indexPath.item >= index && attributes.indexPath.item < index + topStackMaximumSize { yPosition = centralCardYPosition - verticalOffsetBetweenCardsInTopStack*(attributes.indexPath.row - index) } else { attributes.hidden = true yPosition = centralCardYPosition } } let xPosition = (collectionView!.frame.size.width - cardSize.width)/2 let cardFrame = CGRectMake(xPosition, CGFloat(yPosition), cardSize.width, cardSize.height) attributes.frame = cardFrame return attributes } private func layoutAttributesForBottomStackItemWithInitialAttributes(attributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { let yPosition = collectionView!.frame.size.height - bottomStackCardHeight let xPosition = (collectionView!.frame.size.width - cardSize.width)/2 let frame = CGRectMake(xPosition, CGFloat(yPosition), cardSize.width, cardSize.height) attributes.frame = frame if let angle = bottomStackRotations[attributes.indexPath.item] { attributes.transform3D = CATransform3DMakeRotation(CGFloat(angle), 0, 0, 1) } return attributes } // MARK: - Handling the Swipe and Pan Gesture internal func handleSwipe(sender: UISwipeGestureRecognizer) { switch sender.direction { case UISwipeGestureRecognizerDirection.Up: // Take the card at the current index // and process the swipe up only if it occurs below it // var temIndex = index // if temIndex >= collectionView!.numberOfItemsInSection(0) { // temIndex-- // } // let currentCard = collectionView!.cellForItemAtIndexPath(NSIndexPath(forItem: temIndex , inSection: 0))! // let point = sender.locationInView(collectionView) // if (point.y > CGRectGetMaxY(currentCard.frame) && index > 0) { index-- // } case UISwipeGestureRecognizerDirection.Down: if index + 1 < collectionView!.numberOfItemsInSection(0) { index++ } default: break } } internal func handlePan(sender: UIPanGestureRecognizer) { if (sender.state == .Began) { let initialPanPoint = sender.locationInView(collectionView) findDraggingCellByCoordinate(initialPanPoint) } else if (sender.state == .Changed) { let newCenter = sender.translationInView(collectionView!) updateCenterPositionOfDraggingCell(newCenter) } else { if let indexPath = draggedCellPath { finishedDragging(collectionView!.cellForItemAtIndexPath(indexPath)!) } } } //Define what card should we drag private func findDraggingCellByCoordinate(touchCoordinate: CGPoint) { if let indexPath = collectionView?.indexPathForItemAtPoint(touchCoordinate) { if indexPath.item >= index { //top stack draggedCellPath = NSIndexPath(forItem: index, inSection: 0) initialCellCenter = collectionView?.cellForItemAtIndexPath(draggedCellPath!)?.center } else { //bottomStack if (index > 0 ) { draggedCellPath = NSIndexPath(forItem: index - 1, inSection: 0) } initialCellCenter = collectionView?.cellForItemAtIndexPath(draggedCellPath!)?.center } //workaround for fix issue with zIndex let cell = collectionView!.cellForItemAtIndexPath(draggedCellPath!) collectionView?.bringSubviewToFront(cell!) } } //Change position of dragged card private func updateCenterPositionOfDraggingCell(touchCoordinate:CGPoint) { if let strongDraggedCellPath = draggedCellPath { if let cell = collectionView?.cellForItemAtIndexPath(strongDraggedCellPath) { let newCenterX = (initialCellCenter!.x + touchCoordinate.x) let newCenterY = (initialCellCenter!.y + touchCoordinate.y) cell.center = CGPoint(x: newCenterX, y:newCenterY) cell.transform = CGAffineTransformMakeRotation(CGFloat(storeAngleOfRotation())) } } } private func finishedDragging(cell: UICollectionViewCell) { let deltaX = abs(cell.center.x - initialCellCenter!.x) let deltaY = abs(cell.center.y - initialCellCenter!.y) let shouldSnapBack = (deltaX < minimumXPanDistanceToSwipe && deltaY < minimumYPanDistanceToSwipe) if shouldSnapBack { UIView.setAnimationsEnabled(false) collectionView!.reloadItemsAtIndexPaths([self.draggedCellPath!]) UIView.setAnimationsEnabled(true) } else { storeAngleOfRotation() if draggedCellPath?.item == index { index++ } else { index-- } initialCellCenter = CGPointZero draggedCellPath = nil } } //Compute and Store angle of rotation private func storeAngleOfRotation() -> Double { var result:Double = 0 if let strongDraggedCellPath = draggedCellPath { if let cell = collectionView?.cellForItemAtIndexPath(strongDraggedCellPath) { let centerYIncidence = collectionView!.frame.size.height + cardSize.height - bottomStackCardHeight let gamma:Double = Double((cell.center.x - collectionView!.bounds.size.width/2)/(centerYIncidence - cell.center.y)) result = atan(gamma) bottomStackRotations[strongDraggedCellPath.item] = atan(gamma)*coefficientOfRotation } } return result } // MARK: - appearance of new card func newCardDidAdd(newCardIndex:Int) { collectionView?.performBatchUpdates({ [weak self] _ in self?.newCardAnimationInProgress = true self?.collectionView?.insertItemsAtIndexPaths([NSIndexPath(forItem: newCardIndex, inSection: 0)]) }, completion: {[weak self] _ in let void: ()? = self?.newCardAnimationInProgress = false }) } //MARK: - UIGestureRecognizerDelegate public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { var result:Bool = true if let panGesture = gestureRecognizer as? UIPanGestureRecognizer { let velocity = panGesture.velocityInView(collectionView) result = abs(Int(velocity.y)) < 250 } return result } }
070a14dc9d013b4583cc624937fcb49f
43.961326
162
0.656119
false
false
false
false
justin999/gitap
refs/heads/master
gitap/GitHubAPIError.swift
mit
1
struct GitHubAPIError : JSONDecodable, Error { struct FieldError : JSONDecodable { let resource: String let field: String let code: String init(json: Any) throws { guard let dictionary = json as? [String : Any] else { throw JSONDecodeError.invalidFormat(json: json) } guard let resource = dictionary["resource"] as? String else { throw JSONDecodeError.missingValue(key: "resource", actualValue: dictionary["resource"]) } guard let field = dictionary["field"] as? String else { throw JSONDecodeError.missingValue(key: "field", actualValue: dictionary["field"]) } guard let code = dictionary["code"] as? String else { throw JSONDecodeError.missingValue(key: "code", actualValue: dictionary["code"]) } self.resource = resource self.field = field self.code = code } } let message: String let fieldErrors: [FieldError] init(json: Any) throws { guard let dictionary = json as? [String : Any] else { throw JSONDecodeError.invalidFormat(json: json) } guard let message = dictionary["message"] as? String else { throw JSONDecodeError.missingValue(key: "message", actualValue: dictionary["message"]) } let fieldErrorObjects = dictionary["errors"] as? [Any] ?? [] let fieldErrors = try fieldErrorObjects.map { return try FieldError(json: $0) } self.message = message self.fieldErrors = fieldErrors } }
9023596e8cc11d9a9ea4be3e9feeb0dc
33.74
104
0.560161
false
false
false
false
sameertotey/LimoService
refs/heads/master
LimoService/PreviousLocationLookupViewController.swift
mit
1
// // PreviousLocationLookupViewController.swift // LimoService // // Created by Sameer Totey on 4/1/15. // Copyright (c) 2015 Sameer Totey. All rights reserved. // import UIKit class PreviousLocationLookupViewController: PFQueryTableViewController { weak var currentUser: PFUser! var selectedLocation: LimoUserLocation? override init(style: UITableViewStyle, className: String!) { super.init(style: style, className: className) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.parseClassName = "LimoUserLocation" // self.textKey = "address" self.pullToRefreshEnabled = true self.objectsPerPage = 20 } private func alert(message : String) { let alert = UIAlertController(title: "Oops something went wrong.", message: message, preferredStyle: UIAlertControllerStyle.Alert) let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil) let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) let settings = UIAlertAction(title: "Settings", style: UIAlertActionStyle.Default) { (action) -> Void in UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) return } alert.addAction(settings) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() self.tableView.estimatedRowHeight = 60 self.tableView.rowHeight = UITableViewAutomaticDimension } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func queryForTable() -> PFQuery { if let query = LimoUserLocation.query() { query.whereKey("owner", equalTo: currentUser) // expect currentUser to be set here query.orderByDescending("createdAt") query.limit = 200; return query } else { let query = PFQuery(className: "LimoUserLocation") query.whereKey("owner", equalTo: currentUser) // expect currentUser to be set here query.orderByDescending("createdAt") query.limit = 200; return query } } override func objectAtIndexPath(indexPath: NSIndexPath!) -> PFObject? { var obj : PFObject? = nil if let allObjects = self.objects { if indexPath.row < allObjects.count { obj = allObjects[indexPath.row] as? PFObject } } return obj } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject!) -> PFTableViewCell? { let cell = tableView.dequeueReusableCellWithIdentifier("LocationCell", forIndexPath: indexPath) as! LocationLookupTableViewCell cell.nameLabel.text = object.valueForKey("name") as? String cell.addressLabel.text = object.valueForKey("address") as? String return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "return the Location"){ } } // MARK: - TableViewDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let selectedObject = objectAtIndexPath(indexPath) { if selectedObject is LimoUserLocation { selectedLocation = (selectedObject as! LimoUserLocation) performSegueWithIdentifier("Return Selection", sender: nil) } else { println("The type of the object \(selectedObject) is not LimoUserLocation it is ..") } } } }
512b4175a61f38ce259df5aa20000f99
35.775701
138
0.640152
false
false
false
false
tkareine/MiniFuture
refs/heads/master
Source/Try.swift
mit
1
import Foundation public enum Try<T> { case success(T) case failure(Error) public func flatMap<U>(_ f: (T) throws -> Try<U>) -> Try<U> { switch self { case .success(let value): do { return try f(value) } catch { return .failure(error) } case .failure(let error): return .failure(error) } } public func map<U>(_ f: (T) throws -> U) -> Try<U> { return flatMap { e in do { return .success(try f(e)) } catch { return .failure(error) } } } public func value() throws -> T { switch self { case .success(let value): return value case .failure(let error): throw error } } public var isSuccess: Bool { switch self { case .success: return true case .failure: return false } } public var isFailure: Bool { return !isSuccess } } extension Try: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { switch self { case .success(let value): return "Try.success(\(value))" case .failure(let error): return "Try.failure(\(error))" } } public var debugDescription: String { switch self { case .success(let value): return "Try.success(\(String(reflecting: value)))" case .failure(let error): return "Try.failure(\(String(reflecting: error)))" } } } /** * Try enumeration does not adopt Equatable protocol, because that would limit * the allowed values of generic type T. Instead, we provide `==` operator. */ public func ==<T: Equatable>(lhs: Try<T>, rhs: Try<T>) -> Bool { switch (lhs, rhs) { case (.success(let lhs), .success(let rhs)): return lhs == rhs case (.failure(let lhs as NSError), .failure(let rhs as NSError)): return lhs.domain == rhs.domain && lhs.code == rhs.code default: return false } } public func !=<T: Equatable>(lhs: Try<T>, rhs: Try<T>) -> Bool { return !(lhs == rhs) }
01407a90edfe2e25c132d0cc1fd42fed
20.989011
78
0.591204
false
false
false
false
superk589/CGSSGuide
refs/heads/master
DereGuide/Live/Model/CGSSBeatmapNote.swift
mit
2
// // CGSSBeatmapNote.swift // DereGuide // // Created by zzk on 21/10/2017. // Copyright © 2017 zzk. All rights reserved. // import Foundation import UIKit class CGSSBeatmapNote { // 判定范围类型(用于计算得分, 并非按键类型) enum RangeType: Int { case click case flick case slide static let hold = RangeType.click } // note 类型 enum Style { enum FlickDirection { case left case right } case click case flick(FlickDirection) case slide case hold case wideClick case wideFlick(FlickDirection) case wideSlide var isWide: Bool { switch self { case .click, .flick, .hold, .slide: return false default: return true } } } var width: Int { switch style { case .click, .flick, .hold, .slide: return 1 default: return status } } var id: Int! var sec: Float! var type: Int! var startPos: Int! var finishPos: Int! var status: Int! var sync: Int! var groupId: Int! // 0 no press, 1 start, 2 end var longPressType = 0 // used in shifting bpm var offset: Float = 0 // from 1 to max combo var comboIndex: Int = 1 // context free note information, so each long press slide and filck note need to know the related note weak var previous: CGSSBeatmapNote? weak var next: CGSSBeatmapNote? weak var along: CGSSBeatmapNote? } extension CGSSBeatmapNote { func append(_ anotherNote: CGSSBeatmapNote) { self.next = anotherNote anotherNote.previous = self } func intervalTo(_ anotherNote: CGSSBeatmapNote) -> Float { return anotherNote.sec - sec } var offsetSecond: Float { return sec + offset } } extension CGSSBeatmapNote { var rangeType: RangeType { switch (status, type) { case (1, _), (2, _): return .flick case (_, 3): return .slide case (_, 2): return .hold default: return .click } } var style: Style { switch (status, type) { case (1, 1): return .flick(.left) case (2, 1): return .flick(.right) case (_, 2): return .hold case (_, 3): return .slide case (_, 4): return .wideClick case (_, 5): return .wideSlide case (_, 6): return .wideFlick(.left) case (_, 7): return .wideFlick(.right) default: return .click } } }
73c3ac209eac914113e4c8a4522fb161
20.412214
107
0.504456
false
false
false
false
jegumhon/URWeatherView
refs/heads/master
URWeatherView/SpriteAssets/URRainGroundEmitterNode.swift
mit
1
// // URRainGroundEmitterNode.swift // URWeatherView // // Created by DongSoo Lee on 2017. 6. 15.. // Copyright © 2017년 zigbang. All rights reserved. // import SpriteKit open class URRainGroundEmitterNode: SKEmitterNode { public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init() { super.init() let bundle = Bundle(for: URRainGroundEmitterNode.self) let particleImage = UIImage(named: "spark", in: bundle, compatibleWith: nil)! self.particleTexture = SKTexture(image: particleImage) self.particleBirthRate = 100.0 // self.particleBirthRateMax? self.particleLifetime = 0.1 self.particleLifetimeRange = 0.0 self.particlePositionRange = CGVector(dx: 363.44, dy: 0.0) self.zPosition = 0.0 self.emissionAngle = CGFloat(269.863 * .pi / 180.0) self.emissionAngleRange = CGFloat(22.918 * .pi / 180.0) self.particleSpeed = 5.0 self.particleSpeedRange = 5.0 self.xAcceleration = 0.0 self.yAcceleration = 0.0 self.particleAlpha = 0.8 self.particleAlphaRange = 0.2 self.particleAlphaSpeed = 0.0 self.particleScale = 0.0 self.particleScaleRange = 0.15 self.particleScaleSpeed = 0.0 self.particleRotation = 0.0 self.particleRotationRange = 0.0 self.particleRotationSpeed = 0.0 self.particleColorBlendFactor = 1.0 self.particleColorBlendFactorRange = 0.0 self.particleColorBlendFactorSpeed = 0.0 self.particleColorSequence = SKKeyframeSequence(keyframeValues: [UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 1.0, alpha: 1.0), UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 1.0, alpha: 1.0)], times: [0.0, 1.0]) self.particleBlendMode = .alpha } }
b123c49723b4106fb104b6ad956e32a2
36.897959
232
0.650512
false
false
false
false
iSame7/Glassy
refs/heads/master
Glassy/Glassy/GlassyScrollView.swift
mit
1
// // GlassyScrollView.swift // Glassy // // Created by Sameh Mabrouk on 6/27/15. // Copyright (c) 2015 smapps. All rights reserved. // import UIKit //Default Blur Settings. let blurRadious:CGFloat = 14.0 let blurTintColor:UIColor = UIColor(white: 0, alpha: 0.3) let blurDeltaFactor:CGFloat = 1.4 //How much the background move when scrolling. let maxBackgroundMovementVerticle:CGFloat = 30 let maxBackgroundMovementHorizontal:CGFloat = 150 //the value of the fading space on the top between the view and navigation bar let topFadingHeightHalf:CGFloat = 10 @objc protocol GlassyScrollViewDelegate:NSObjectProtocol{ optional func floraView(floraView: AnyObject, numberOfRowsInSection section: Int) -> Int //use this to configure your foregroundView when the frame of the whole view changed optional func glassyScrollView(glassyScrollView: GlassyScrollView, didChangedToFrame fram: CGRect) //make custom blur without messing with default settings optional func glassyScrollView(glassyScrollView: GlassyScrollView, blurForImage image: UIImage) -> UIImage } class GlassyScrollView: UIView, UIScrollViewDelegate { private var backgroundImage: UIImage! //Default blurred is provided. private var blurredBackgroundImage: UIImage! //The view that will contain all the info private var foregroundView: UIView! //Shadow layers. private var topShadowLayer:CALayer! private var botShadowLayer:CALayer! //Masking private var foregroundContainerView:UIView! private var topMaskImageView:UIImageView! private var backgroundScrollView:UIScrollView! var foregroundScrollView:UIScrollView! //How much view is showed up from the bottom. var viewDistanceFromBottom:CGFloat! //set this only when using navigation bar of sorts. let topLayoutGuideLength:CGFloat = 0.0 var constraitView:UIView! var backgroundImageView:UIImageView! var blurredBackgroundImageView:UIImageView! //delegate. var delegate:GlassyScrollViewDelegate! // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(frame: CGRect, backgroundImage:UIImage, blurredImage:UIImage?, viewDistanceFromBottom:CGFloat, foregroundView:UIView) { super.init(frame: frame) self.backgroundImage = backgroundImage if blurredImage != NSNull(){ // self.blurredBackgroundImage = blurredImage self.blurredBackgroundImage = backgroundImage.applyBlurWithRadius(blurRadious, tintColor: blurTintColor, saturationDeltaFactor: blurDeltaFactor, maskImage: nil) } else{ //Check if delegate conform to protocol or not. if self.delegate.respondsToSelector(Selector("glassyScrollView:blurForImage:")){ self.blurredBackgroundImage = self.delegate.glassyScrollView!(self, blurForImage: self.backgroundImage) } else{ //implement live blurring effect. self.blurredBackgroundImage = backgroundImage.applyBlurWithRadius(blurRadious, tintColor: blurTintColor, saturationDeltaFactor: blurDeltaFactor, maskImage: nil) } } self.viewDistanceFromBottom = viewDistanceFromBottom self.foregroundView = foregroundView //Autoresize self.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth //Create Views self.createBackgroundView() self.createForegroundView() // self.createTopShadow() self.createBottomShadow() } func initWithFrame(){ } // MARK: - Public Methods func scrollHorizontalRatio(ratio:CGFloat){ // when the view scroll horizontally, this works the parallax magic backgroundScrollView.contentOffset = CGPointMake(maxBackgroundMovementHorizontal+ratio*maxBackgroundMovementHorizontal, backgroundScrollView.contentOffset.y) } func scrollVerticallyToOffset(offsetY:CGFloat){ foregroundScrollView.contentOffset=CGPointMake(foregroundScrollView.contentOffset.x, offsetY) } // MARK: - Setters func setViewFrame(frame:CGRect){ super.frame = frame //work background let bounds:CGRect = CGRectOffset(frame, -frame.origin.x, -frame.origin.y) backgroundScrollView.frame=bounds backgroundScrollView.contentSize = CGSizeMake(bounds.size.width + 2*maxBackgroundMovementHorizontal, self.bounds.size.height+maxBackgroundMovementVerticle) backgroundScrollView.contentOffset=CGPointMake(maxBackgroundMovementHorizontal, 0) constraitView.frame = CGRectMake(0, 0, bounds.size.width + 2*maxBackgroundMovementHorizontal, bounds.size.height+maxBackgroundMovementVerticle) //foreground foregroundContainerView.frame = bounds foregroundScrollView.frame=bounds foregroundView.frame = CGRectOffset(foregroundView.bounds, (foregroundScrollView.frame.size.width - foregroundView.bounds.size.width)/2, foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) foregroundScrollView.contentSize=CGSizeMake(bounds.size.width, foregroundView.frame.origin.y + foregroundView.bounds.size.height) //Shadows // topShadowLayer.frame=CGRectMake(0, 0, bounds.size.width, foregroundScrollView.contentInset.top + topFadingHeightHalf) botShadowLayer.frame=CGRectMake(0, bounds.size.height - viewDistanceFromBottom, bounds.size.width, bounds.size.height) // if self.delegate.respondsToSelector(Selector("glassyScrollView:didChangedToFrame:")){ // delegate.glassyScrollView!(self, didChangedToFrame: frame) // } } func setTopLayoutGuideLength(topLayoutGuideLength:CGFloat){ if topLayoutGuideLength==0 { return } //set inset foregroundScrollView.contentInset = UIEdgeInsetsMake(topLayoutGuideLength, 0, 0, 0) //reposition foregroundView.frame = CGRectOffset(foregroundView.bounds, (foregroundScrollView.frame.size.width - foregroundView.bounds.size.width)/2, foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) //resize contentSize foregroundScrollView.contentSize = CGSizeMake(self.frame.size.width, foregroundView.frame.origin.y + foregroundView.frame.size.height) //reset the offset if foregroundScrollView.contentOffset.y == 0{ foregroundScrollView.contentOffset = CGPointMake(0, -foregroundScrollView.contentInset.top) } //adding new mask foregroundContainerView.layer.mask = createTopMaskWithSize(CGSizeMake(foregroundContainerView.frame.size.width, foregroundContainerView.frame.size.height), startFadAtTop: foregroundScrollView.contentInset.top - topFadingHeightHalf, endAtBottom: foregroundScrollView.contentInset.top + topFadingHeightHalf, topColor: UIColor(white: 1.0, alpha: 0.0), botColor: UIColor(white: 1.0, alpha: 1.0)) //recreate shadow createTopShadow() } func setViewDistanceFromBottom(vDistanceFromBottom:CGFloat){ viewDistanceFromBottom = vDistanceFromBottom foregroundView.frame = CGRectOffset(foregroundView.bounds, (foregroundScrollView.frame.size.width - foregroundView.bounds.size.width)/2, foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) foregroundScrollView.contentSize = CGSizeMake(self.frame.size.width, foregroundView.frame.origin.y + foregroundView.frame.size.height) //shadows botShadowLayer.frame = CGRectOffset(botShadowLayer.bounds, 0, self.frame.size.height - viewDistanceFromBottom) } func setBackgroundImage(backgroundImg:UIImage, overWriteBlur:Bool, animated:Bool, interval:NSTimeInterval){ backgroundImage = backgroundImg if overWriteBlur{ blurredBackgroundImage = backgroundImg.applyBlurWithRadius(blurRadious, tintColor: blurTintColor, saturationDeltaFactor: blurDeltaFactor, maskImage: nil) } if animated{ let previousBackgroundImageView:UIImageView = backgroundImageView let previousBlurredBackgroundImageView:UIImageView = blurredBackgroundImageView createBackgroundImageView() backgroundImageView.alpha = 0 blurredBackgroundImageView.alpha=0 // blur needs to get animated first if the background is blurred if previousBlurredBackgroundImageView.alpha == 1{ UIView.animateWithDuration(interval, animations: { () -> Void in self.blurredBackgroundImageView.alpha=previousBlurredBackgroundImageView.alpha }, completion: { (Bool) -> Void in self.backgroundImageView.alpha=previousBackgroundImageView.alpha previousBackgroundImageView.removeFromSuperview() previousBlurredBackgroundImageView.removeFromSuperview() }) } else{ UIView.animateWithDuration(interval, animations: { () -> Void in self.backgroundImageView.alpha=self.backgroundImageView.alpha self.blurredBackgroundImageView.alpha=previousBlurredBackgroundImageView.alpha }, completion: { (Bool) -> Void in previousBackgroundImageView.removeFromSuperview() previousBlurredBackgroundImageView.removeFromSuperview() }) } } else{ backgroundImageView.image=backgroundImage blurredBackgroundImageView.image=blurredBackgroundImage } } func blurBackground(shouldBlur:Bool){ if shouldBlur{ blurredBackgroundImageView.alpha = 1 } else{ blurredBackgroundImageView.alpha = 0 } } // MARK: - Views creation // MARK: - ScrollViews func createBackgroundView(){ self.backgroundScrollView = UIScrollView(frame: self.frame) self.backgroundScrollView.userInteractionEnabled=true self.backgroundScrollView.contentSize = CGSize(width: self.frame.size.width + (2*maxBackgroundMovementHorizontal), height: self.frame.size.height+maxBackgroundMovementVerticle) self.backgroundScrollView.contentOffset = CGPointMake(maxBackgroundMovementHorizontal, 0) self.addSubview(self.backgroundScrollView) self.constraitView = UIView(frame: CGRectMake(0, 0, self.frame.size.width + (2*maxBackgroundMovementHorizontal), self.frame.size.height+maxBackgroundMovementVerticle)) self.backgroundScrollView.addSubview(self.constraitView) self.createBackgroundImageView() } func createBackgroundImageView(){ self.backgroundImageView = UIImageView(image: self.backgroundImage) self.backgroundImageView.setTranslatesAutoresizingMaskIntoConstraints(false) self.backgroundImageView.contentMode = UIViewContentMode.ScaleAspectFill self.constraitView.addSubview(self.backgroundImageView) self.blurredBackgroundImageView = UIImageView(image: self.blurredBackgroundImage) self.blurredBackgroundImageView.setTranslatesAutoresizingMaskIntoConstraints(false) self.blurredBackgroundImageView.contentMode = UIViewContentMode.ScaleAspectFill self.blurredBackgroundImageView.alpha=0 self.constraitView.addSubview(self.blurredBackgroundImageView) var viewBindingsDict: NSMutableDictionary = NSMutableDictionary() viewBindingsDict.setValue(backgroundImageView, forKey: "backgroundImageView") self.constraitView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[backgroundImageView]|", options: nil, metrics: nil, views: viewBindingsDict as [NSObject : AnyObject])) self.constraitView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[backgroundImageView]|", options: nil, metrics: nil, views: viewBindingsDict as [NSObject : AnyObject])) var blurredViewBindingsDict: NSMutableDictionary = NSMutableDictionary() blurredViewBindingsDict.setValue(blurredBackgroundImageView, forKey: "blurredBackgroundImageView") self.constraitView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[blurredBackgroundImageView]|", options: nil, metrics: nil, views: blurredViewBindingsDict as [NSObject : AnyObject])) self.constraitView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[blurredBackgroundImageView]|", options: nil, metrics: nil, views: blurredViewBindingsDict as [NSObject : AnyObject])) } func createForegroundView(){ self.foregroundContainerView = UIView(frame: self.frame) self.addSubview(self.foregroundContainerView) self.foregroundScrollView=UIScrollView(frame: self.frame) self.foregroundScrollView.delegate=self self.foregroundScrollView.showsVerticalScrollIndicator=false self.foregroundScrollView.showsHorizontalScrollIndicator=false self.foregroundContainerView.addSubview(self.foregroundScrollView) let tapRecognizer:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("foregroundTapped:")) foregroundScrollView.addGestureRecognizer(tapRecognizer) foregroundView.frame = CGRectOffset(foregroundView.bounds, (foregroundScrollView.frame.size.width - foregroundView.frame.size.width)/2, foregroundScrollView.frame.size.height - viewDistanceFromBottom) foregroundScrollView.addSubview(foregroundView) foregroundScrollView.contentSize = CGSizeMake(self.frame.size.width, foregroundView.frame.origin.y + foregroundView.frame.size.height) } // MARK: - Shadow and mask layer func createTopMaskWithSize(size:CGSize, startFadAtTop:CGFloat, endAtBottom:CGFloat, topColor:UIColor, botColor:UIColor) -> CALayer{ let top = startFadAtTop / size.height let bottom = endAtBottom / size.height let maskLayer:CAGradientLayer = CAGradientLayer() maskLayer.anchorPoint = CGPointZero maskLayer.startPoint = CGPointMake(0.5, 0.0) maskLayer.endPoint = CGPointMake(0.5, 1.0) maskLayer.colors = NSArray(arrayLiteral: topColor.CGColor, topColor.CGColor, botColor.CGColor, botColor.CGColor) as [AnyObject] maskLayer.locations = NSArray(arrayLiteral: 0.0, top, bottom, 1.0) as [AnyObject] maskLayer.frame = CGRectMake(0, 0, size.width, size.height) return maskLayer } func createTopShadow(){ topShadowLayer = self.createTopMaskWithSize(CGSizeMake(foregroundContainerView.frame.size.width, foregroundScrollView.contentInset.top + topFadingHeightHalf), startFadAtTop:foregroundScrollView.contentInset.top + topFadingHeightHalf , endAtBottom: foregroundScrollView.contentInset.top + topFadingHeightHalf, topColor: UIColor(white: 0, alpha: 0.15), botColor: UIColor(white: 0, alpha: 0)) self.layer.insertSublayer(topShadowLayer, below: foregroundContainerView.layer) } func createBottomShadow(){ botShadowLayer = self.createTopMaskWithSize(CGSizeMake(self.frame.size.width, viewDistanceFromBottom), startFadAtTop:0 , endAtBottom: viewDistanceFromBottom, topColor: UIColor(white: 0, alpha: 0), botColor: UIColor(white: 0, alpha: 0.8)) self.layer.insertSublayer(botShadowLayer, below: foregroundContainerView.layer) } // MARK: - foregroundScrollView Tap Action func foregroundTapped(tapRecognizer:UITapGestureRecognizer){ let tappedPoint:CGPoint = tapRecognizer.locationInView(foregroundScrollView) if tappedPoint.y < foregroundScrollView.frame.size.height{ var ratio:CGFloat! if foregroundScrollView.contentOffset.y == foregroundScrollView.contentInset.top{ ratio=1 } else{ ratio=0 } foregroundScrollView.setContentOffset(CGPointMake(0, ratio * foregroundView.frame.origin.y - foregroundScrollView.contentInset.top), animated: true) } } // MARK: - Delegate // MARK: - UIScrollView func scrollViewDidScroll(scrollView: UIScrollView) { //translate into ratio to height var ratio:CGFloat = (scrollView.contentOffset.y + foregroundScrollView.contentInset.top)/(foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) if ratio < 0{ ratio = 0 } if ratio > 1{ ratio=1 } //set background scroll backgroundScrollView.contentOffset = CGPointMake(maxBackgroundMovementHorizontal, ratio * maxBackgroundMovementVerticle) //set alpha blurredBackgroundImageView.alpha = ratio } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { var ratio = (targetContentOffset.memory.y + foregroundScrollView.contentInset.top) / (foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) if ratio > 0 && ratio < 1{ if velocity.y == 0{ if ratio>0.5{ratio=1} else{ratio=0} } else if velocity.y > 0 { if ratio>0.1{ratio=1} else{ratio=0} } else { if ratio>0.9{ratio=1} else{ratio=0} } targetContentOffset.memory.y=ratio * foregroundView.frame.origin.y - foregroundScrollView.contentInset.top } } }
77b70b9fa2e533d753da4ef8f2a09955
40.196796
399
0.716992
false
false
false
false
LonelyRun/VAKit
refs/heads/master
Demo/VAKit/ViewController.swift
mit
1
// // ViewController.swift // VAKit // // Created by admin on 2017/4/21. // Copyright © 2017年 admin. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let label = VAImageLabelView(imageName: "https://img6.bdstatic.com/img/image/smallpic/h2.jpg", title: "4就开了", type: .DefaultType) label.layer.borderWidth = 1 label.layer.borderColor = UIColor.black.cgColor label.spacingLength = 10 label.leftTopMargin = 0 label.rightBottomMargin = -10 view.addSubview(label) label.snp.makeConstraints { (make) in make.top.equalTo(60) make.centerX.equalTo(view) } label.label.text = "123" } }
c7f8abca73f4fb6b90c130355e081d21
24.548387
137
0.623737
false
false
false
false
netsells/NSUtils
refs/heads/master
NSUtils/Classes/Views/ProgressBarView.swift
mit
1
// // ProgressBarView.swift // NSUtils // // Created by Jack Colley on 01/02/2018. // Copyright © 2018 Netsells. All rights reserved. // import Foundation import UIKit open class ProgressBarView: UIView { @IBInspectable public var startColour: UIColor = UIColor.white @IBInspectable public var endColour: UIColor = UIColor.blue @IBInspectable public var completionPercentage: CGFloat = 0.0 // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override open func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() let colours: [CGColor] = [startColour.cgColor, endColour.cgColor] // Should almost always be RGB - We don't really want to use CMYK let colourSpace = CGColorSpaceCreateDeviceRGB() let colourLocations: [CGFloat] = [0.0, 1.0] let gradient = CGGradient(colorsSpace: colourSpace, colors: colours as CFArray, locations: colourLocations) let startPoint = CGPoint(x: 0, y: self.frame.height) let endPoint = CGPoint(x: self.frame.width * completionPercentage, y: self.frame.height) context!.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0)) } }
335dd32532ade029c25217e0335a551b
35.611111
128
0.711684
false
false
false
false
Johennes/firefox-ios
refs/heads/master
Utils/Extensions/SetExtensions.swift
mpl-2.0
4
/* 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 extension SetGenerator { mutating func take(n: Int) -> [Element]? { precondition(n >= 0) if n == 0 { return [] } var count: Int = 0 var out: [Element] = [] while count < n { count += 1 guard let val = self.next() else { if out.isEmpty { return nil } return out } out.append(val) } return out } } public extension Set { func withSubsetsOfSize(n: Int, f: Set<Generator.Element> -> ()) { precondition(n > 0) if self.isEmpty { return } if n > self.count { f(self) return } if n == 1 { self.forEach { f(Set([$0])) } return } var generator = self.generate() while let next = generator.take(n) { if !next.isEmpty { f(Set(next)) } } } func subsetsOfSize(n: Int) -> [Set<Generator.Element>] { precondition(n > 0) if self.isEmpty { return [] } if n > self.count { return [self] } if n == 1 { // Special case. return self.map({ Set([$0]) }) } var generator = self.generate() var out: [Set<Generator.Element>] = [] out.reserveCapacity(self.count / n) while let next = generator.take(n) { if !next.isEmpty { out.append(Set(next)) } } return out } }
5a7b0b994e9cc5fd531c7a8a1385f253
21.25
70
0.449143
false
false
false
false
kevintulod/CascadeKit-iOS
refs/heads/master
CascadeKit/CascadeKit/Cascade Controller/CascadeController.swift
mit
1
// // CascadeController.swift // CascadeKit // // Created by Kevin Tulod on 1/7/17. // Copyright © 2017 Kevin Tulod. All rights reserved. // import UIKit public class CascadeController: UIViewController { @IBOutlet weak var leftViewContainer: UIView! @IBOutlet weak var rightViewContainer: UIView! @IBOutlet weak var dividerView: CascadeDividerView! @IBOutlet weak var dividerViewWidthConstraint: NSLayoutConstraint! @IBOutlet weak var dividerViewPositionConstraint: NSLayoutConstraint! internal var controllers = [UINavigationController]() internal weak var leftController: UINavigationController? { didSet { guard let leftController = leftController else { return } addChildViewController(leftController) leftViewContainer.fill(with: leftController.view) leftController.rootViewController?.navigationItem.leftBarButtonItem = nil } } internal weak var rightController: UINavigationController? { didSet { guard let rightController = rightController else { return } addChildViewController(rightController) rightViewContainer.fill(with: rightController.view) if controllers.count > 0 { rightController.rootViewController?.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Close", style: .plain, target: self, action: #selector(CascadeController.popLastViewController)) } } } /// Minimum size for left and right views public var minimumViewSize = CGFloat(250) /// Duration of cascade animations in seconds public var animationDuration = TimeInterval(0.25) // MARK: - Creation private static let storyboardName = "Cascade" private static let storyboardIdentifier = "CascadeController" public static func create() -> CascadeController { let storyboard = UIStoryboard(name: storyboardName, bundle: Bundle(for: CascadeController.self)) guard let controller = storyboard.instantiateViewController(withIdentifier: storyboardIdentifier) as? CascadeController else { fatalError("`Cascade` storyboard is missing required reference to `CascadeController`") } let _ = controller.view return controller } public override func viewDidLoad() { super.viewDidLoad() dividerView.delegate = self setupStyling() } public override func addChildViewController(_ childController: UIViewController) { super.addChildViewController(childController) } /// Sets up the cascade controller with the initial view controllers public func setup(first: UINavigationController, second: UINavigationController) { leftController = first rightController = second } /// Cascades the view controller to the top of the stack public func cascade(viewController cascadeController: UINavigationController, sender: UINavigationController? = nil) { if sender === leftController { // If the provided sender is the second-to-last in the stack, replace the last controller popLastController() addControllerToStack(cascadeController) rightController = cascadeController } else { // All other cases, push the controller to the end animate(withForwardCascadeController: cascadeController, preAnimation: { Void in self.addControllerToStack(self.leftController) self.leftController = self.rightController }, postAnimation: { Void in self.rightController = cascadeController }, completion: nil) } } /// Pops the last controller off the top of the stack public func popLastViewController() { guard let poppedController = popLastController() else { NSLog("No controller in stack to pop.") return } let newRightController = self.leftController let dismissingController = self.rightController animate(withBackwardCascadeController: poppedController, preAnimation: { Void in self.rightController = newRightController }, postAnimation: { Void in self.leftController = poppedController }, completion: { Void in dismissingController?.view.removeFromSuperview() dismissingController?.removeFromParentViewController() }) } internal func addControllerToStack(_ controller: UINavigationController?) { if let controller = controller { controllers.append(controller) } } @discardableResult internal func popLastController() -> UINavigationController? { return controllers.popLast() } } extension CascadeController: CascadeDividerDelegate { func divider(_ divider: CascadeDividerView, shouldTranslateToCenter center: CGPoint) -> Bool { // Only allow the divider to translate if the minimum view sizes are met on the left and right return center.x >= minimumViewSize && center.x <= view.frame.width-minimumViewSize } func divider(_ divider: CascadeDividerView, didTranslateToCenter center: CGPoint) { dividerViewPositionConstraint.constant = center.x } } // MARK: - Styling extension CascadeController { func setupStyling() { leftViewContainer.backgroundColor = .white rightViewContainer.backgroundColor = .white dividerViewWidthConstraint.constant = UIScreen.main.onePx } }
0423828a4b8a253609d1b5c77a9bc399
35.2625
207
0.660634
false
false
false
false
lieonCX/Uber
refs/heads/master
UberRider/UberRider/View/SignIn/SignInViewController.swift
mit
1
// // SignInViewController.swift // UberRider // // Created by lieon on 2017/3/22. // Copyright © 2017年 ChangHongCloudTechService. All rights reserved. // import UIKit class SignInViewController: UIViewController { @IBOutlet weak var containerView: UIView! fileprivate var maxYContainerView: CGFloat = 0.0 @IBOutlet weak var verticalCons: NSLayoutConstraint! fileprivate var originalTopDistance: CGFloat = 0 @IBOutlet fileprivate weak var emailTextField: UITextField! @IBOutlet fileprivate weak var passwordTextField: UITextField! fileprivate var signinVM: AuthViewModel = AuthViewModel() @IBAction func loginAction(_ sender: Any) { if let email = emailTextField.text, let password = passwordTextField.text, email.isValidEmail() { signinVM.login(with: email, password: password) { [unowned self] message in if let message = message, !message.isEmpty { self.show(title: "Problem in Authentication", message: message) } else { self.emailTextField.text = "" self.passwordTextField.text = "" RiderViewModel.riderAccount = email self.showRiderVC() } } } else { self.show(title: "Email or Password required", message: "Please enter correct email or password in textfield") } } @IBAction func signUpAction(_ sender: Any) { if let email = emailTextField.text, let password = passwordTextField.text, email.isValidEmail() { signinVM.signup(with: email, password: password) { [unowned self] message in if let message = message, !message.isEmpty { self.show(title: "Problem in Authentication", message: message) } else { self.emailTextField.text = "" self.passwordTextField.text = "" RiderViewModel.riderAccount = email self.showRiderVC() } } } else { return self.show(title: "Email or Password required", message: "Please enter email or password in textfield") } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) originalTopDistance = verticalCons.constant maxYContainerView = UIScreen.main.bounds.height - self.containerView.frame.maxY NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShowAction), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHideAction), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) verticalCons.constant = originalTopDistance NotificationCenter.default.removeObserver(self) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } } extension SignInViewController { static private var distance: CGFloat = 0 @objc fileprivate func keyboardWillShowAction(noti: Notification) { guard let userInfo = noti.userInfo, let keyboardSize = userInfo[UIKeyboardFrameBeginUserInfoKey] as? CGRect else { return } let keyboardHeight = keyboardSize.height UIView.animate(withDuration: 0.25) { self.verticalCons.constant = self.originalTopDistance self.verticalCons.constant = self.originalTopDistance - (keyboardHeight - self.maxYContainerView) self.view.layoutIfNeeded() } } @objc fileprivate func keyboardWillHideAction() { UIView.animate(withDuration: 0.25) { self.verticalCons.constant = self.originalTopDistance self.view.layoutIfNeeded() } } fileprivate func showRiderVC() { self.performSegue(withIdentifier: "RiderHome", sender: nil) } }
b66b5e69d35f28e741fdb34276b0bc75
40.918367
161
0.647517
false
false
false
false
brentdax/swift
refs/heads/master
stdlib/public/core/CString.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 // //===----------------------------------------------------------------------===// // String interop with C //===----------------------------------------------------------------------===// import SwiftShims extension String { /// Creates a new string by copying the null-terminated UTF-8 data referenced /// by the given pointer. /// /// If `cString` contains ill-formed UTF-8 code unit sequences, this /// initializer replaces them with the Unicode replacement character /// (`"\u{FFFD}"`). /// /// The following example calls this initializer with pointers to the /// contents of two different `CChar` arrays---the first with well-formed /// UTF-8 code unit sequences and the second with an ill-formed sequence at /// the end. /// /// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String(cString: ptr.baseAddress!) /// print(s) /// } /// // Prints "Café" /// /// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String(cString: ptr.baseAddress!) /// print(s) /// } /// // Prints "Caf�" /// /// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence. public init(cString: UnsafePointer<CChar>) { self = _decodeValidCString(cString, repair: true) } /// Creates a new string by copying the null-terminated UTF-8 data referenced /// by the given pointer. /// /// This is identical to init(cString: UnsafePointer<CChar> but operates on an /// unsigned sequence of bytes. public init(cString: UnsafePointer<UInt8>) { self = _decodeValidCString(cString, repair: true) } /// Creates a new string by copying and validating the null-terminated UTF-8 /// data referenced by the given pointer. /// /// This initializer does not try to repair ill-formed UTF-8 code unit /// sequences. If any are found, the result of the initializer is `nil`. /// /// The following example calls this initializer with pointers to the /// contents of two different `CChar` arrays---the first with well-formed /// UTF-8 code unit sequences and the second with an ill-formed sequence at /// the end. /// /// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String(validatingUTF8: ptr.baseAddress!) /// print(s) /// } /// // Prints "Optional(Café)" /// /// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String(validatingUTF8: ptr.baseAddress!) /// print(s) /// } /// // Prints "nil" /// /// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence. public init?(validatingUTF8 cString: UnsafePointer<CChar>) { guard let str = _decodeCString(cString, repair: false) else { return nil } self = str } /// Creates a new string by copying the null-terminated data referenced by /// the given pointer using the specified encoding. /// /// When you pass `true` as `isRepairing`, this method replaces ill-formed /// sequences with the Unicode replacement character (`"\u{FFFD}"`); /// otherwise, an ill-formed sequence causes this method to stop decoding /// and return `nil`. /// /// The following example calls this method with pointers to the contents of /// two different `CChar` arrays---the first with well-formed UTF-8 code /// unit sequences and the second with an ill-formed sequence at the end. /// /// let validUTF8: [UInt8] = [67, 97, 102, 195, 169, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String.decodeCString(ptr.baseAddress, /// as: UTF8.self, /// repairingInvalidCodeUnits: true) /// print(s) /// } /// // Prints "Optional((Café, false))" /// /// let invalidUTF8: [UInt8] = [67, 97, 102, 195, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String.decodeCString(ptr.baseAddress, /// as: UTF8.self, /// repairingInvalidCodeUnits: true) /// print(s) /// } /// // Prints "Optional((Caf�, true))" /// /// - Parameters: /// - cString: A pointer to a null-terminated code sequence encoded in /// `encoding`. /// - encoding: The Unicode encoding of the data referenced by `cString`. /// - isRepairing: Pass `true` to create a new string, even when the data /// referenced by `cString` contains ill-formed sequences. Ill-formed /// sequences are replaced with the Unicode replacement character /// (`"\u{FFFD}"`). Pass `false` to interrupt the creation of the new /// string if an ill-formed sequence is detected. /// - Returns: A tuple with the new string and a Boolean value that indicates /// whether any repairs were made. If `isRepairing` is `false` and an /// ill-formed sequence is detected, this method returns `nil`. @_specialize(where Encoding == Unicode.UTF8) @_specialize(where Encoding == Unicode.UTF16) public static func decodeCString<Encoding : _UnicodeEncoding>( _ cString: UnsafePointer<Encoding.CodeUnit>?, as encoding: Encoding.Type, repairingInvalidCodeUnits isRepairing: Bool = true) -> (result: String, repairsMade: Bool)? { guard let cString = cString else { return nil } var end = cString while end.pointee != 0 { end += 1 } let len = end - cString return _decodeCString( cString, as: encoding, length: len, repairingInvalidCodeUnits: isRepairing) } } /// From a non-`nil` `UnsafePointer` to a null-terminated string /// with possibly-transient lifetime, create a null-terminated array of 'C' char. /// Returns `nil` if passed a null pointer. public func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? { guard let s = p else { return nil } let count = Int(_swift_stdlib_strlen(s)) var result = [CChar](repeating: 0, count: count + 1) for i in 0..<count { result[i] = s[i] } return result } internal func _decodeValidCString( _ cString: UnsafePointer<Int8>, repair: Bool ) -> String { let len = UTF8._nullCodeUnitOffset(in: cString) return cString.withMemoryRebound(to: UInt8.self, capacity: len) { (ptr: UnsafePointer<UInt8>) -> String in let bufPtr = UnsafeBufferPointer(start: ptr, count: len) return String._fromWellFormedUTF8(bufPtr, repair: repair) } } internal func _decodeValidCString( _ cString: UnsafePointer<UInt8>, repair: Bool ) -> String { let len = UTF8._nullCodeUnitOffset(in: cString) let bufPtr = UnsafeBufferPointer(start: cString, count: len) return String._fromWellFormedUTF8(bufPtr, repair: repair) } internal func _decodeCString( _ cString: UnsafePointer<Int8>, repair: Bool ) -> String? { let len = UTF8._nullCodeUnitOffset(in: cString) return cString.withMemoryRebound(to: UInt8.self, capacity: len) { (ptr: UnsafePointer<UInt8>) -> String? in let bufPtr = UnsafeBufferPointer(start: ptr, count: len) return String._fromUTF8(bufPtr, repair: repair) } } internal func _decodeCString( _ cString: UnsafePointer<UInt8>, repair: Bool ) -> String? { let len = UTF8._nullCodeUnitOffset(in: cString) let bufPtr = UnsafeBufferPointer(start: cString, count: len) return String._fromUTF8(bufPtr, repair: repair) } /// Creates a new string by copying the null-terminated data referenced by /// the given pointer using the specified encoding. /// /// This internal helper takes the string length as an argument. internal func _decodeCString<Encoding : _UnicodeEncoding>( _ cString: UnsafePointer<Encoding.CodeUnit>, as encoding: Encoding.Type, length: Int, repairingInvalidCodeUnits isRepairing: Bool = true) -> (result: String, repairsMade: Bool)? { let buffer = UnsafeBufferPointer<Encoding.CodeUnit>( start: cString, count: length) let (guts, hadError) = _StringGuts.fromCodeUnits( buffer, encoding: encoding, repairIllFormedSequences: isRepairing) return guts.map { (result: String($0), repairsMade: hadError) } }
78b07589053985d023fe328078d64ab1
38.191964
81
0.634924
false
false
false
false
googlearchive/science-journal-ios
refs/heads/master
ScienceJournal/UI/MaterialFloatingSpinner.swift
apache-2.0
1
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import third_party_objective_c_material_components_ios_components_ShadowLayer_ShadowLayer // swiftlint:disable line_length import third_party_objective_c_material_components_ios_components_ActivityIndicator_ActivityIndicator // swiftlint:enable line_length /// A circular spinner contained in a shadowed, circular view. Best placed on top of cells or views /// to indicate loading after user interaction. class MaterialFloatingSpinner: UIView { enum Metrics { static let spinnerDimension: CGFloat = 32.0 static let spinnerPadding: CGFloat = 6.0 static let spinnerBackgroundDimenion = Metrics.spinnerDimension + Metrics.spinnerPadding } // MARK: - Properties override var intrinsicContentSize: CGSize { return CGSize(width: Metrics.spinnerBackgroundDimenion, height: Metrics.spinnerBackgroundDimenion) } /// The mode of the spinner. var indicatorMode: MDCActivityIndicatorMode { set { spinner.indicatorMode = newValue } get { return spinner.indicatorMode } } /// The progress for the spinner, when in determinate mode. The range is 0.0 to 1.0. var progress: Float { set { spinner.progress = newValue } get { return spinner.progress } } let spinner = MDCActivityIndicator() private let spinnerBackground = ShadowedView() // MARK: - Public override init(frame: CGRect) { super.init(frame: frame) configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } func startAnimating() { self.spinner.startAnimating() self.spinnerBackground.alpha = 1 } func stopAnimating() { self.spinnerBackground.alpha = 0 self.spinner.stopAnimating() } // MARK: - Private private func configureView() { addSubview(spinnerBackground) spinnerBackground.backgroundColor = .white spinnerBackground.translatesAutoresizingMaskIntoConstraints = false spinnerBackground.widthAnchor.constraint( equalToConstant: Metrics.spinnerBackgroundDimenion).isActive = true spinnerBackground.heightAnchor.constraint( equalToConstant: Metrics.spinnerBackgroundDimenion).isActive = true spinnerBackground.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true spinnerBackground.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true spinnerBackground.layer.cornerRadius = 19.0 spinnerBackground.setElevation(points: ShadowElevation.refresh.rawValue) spinnerBackground.alpha = 0 // Hidden by default. spinnerBackground.addSubview(spinner) spinner.indicatorMode = .indeterminate spinner.translatesAutoresizingMaskIntoConstraints = false spinner.widthAnchor.constraint(equalToConstant: Metrics.spinnerDimension).isActive = true spinner.heightAnchor.constraint(equalToConstant: Metrics.spinnerDimension).isActive = true spinner.centerXAnchor.constraint(equalTo: spinnerBackground.centerXAnchor).isActive = true spinner.centerYAnchor.constraint(equalTo: spinnerBackground.centerYAnchor).isActive = true } }
0207e4292e117f54c84047847a097ada
32.366071
101
0.746588
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/UIViewController+Push.swift
mit
1
import Foundation extension UIViewController { @objc(wmf_pushViewController:animated:) func push(_ viewController: UIViewController, animated: Bool = true) { if let navigationController = navigationController { navigationController.pushViewController(viewController, animated: true) } else if let presentingViewController = presentingViewController { presentingViewController.dismiss(animated: true) { presentingViewController.push(viewController, animated: animated) } } else if let parent = parent { parent.push(viewController, animated: animated) } else if let navigationController = self as? UINavigationController { navigationController.pushViewController(viewController, animated: animated) } } }
338f66ddaa76386190a1f831dfca7665
45.222222
87
0.698317
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Platform/Sources/PlatformUIKit/Components/AssetPieChartView/PieChartData+Conveniences.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Charts extension PieChartData { public convenience init(with values: [AssetPieChart.Value.Interaction]) { let values = values.map { AssetPieChart.Value.Presentation(value: $0) } let entries = values.map { PieChartDataEntry(value: $0.percentage.doubleValue, label: $0.debugDescription) } let set = PieChartDataSet(entries: entries, label: "") set.drawIconsEnabled = false set.drawValuesEnabled = false set.selectionShift = 0 set.sliceSpace = 3 set.colors = values.map(\.color) self.init(dataSet: set) } /// Returns an `empty` grayish pie chart data public static var empty: PieChartData { let set = PieChartDataSet(entries: [PieChartDataEntry(value: 100)], label: "") set.drawIconsEnabled = false set.drawValuesEnabled = false set.selectionShift = 0 set.colors = [Color.clear] return PieChartData(dataSet: set) } }
2645fa12e3c96f45f1231fef43a079a9
37.037037
116
0.661149
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Insurance
refs/heads/master
PerchReadyApp/apps/Perch/iphone/native/Perch/DataSources/AlertHistoryDataManager.swift
epl-1.0
1
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /** Class for handling backend Worklight queries for data about all the notifications that have been generated for a given asset. */ public class AlertHistoryDataManager: NSObject { let currentUser = CurrentUser.sharedInstance var alerts: [Alert] = [] var callback: ((Bool)->())! var lastLoadedAlertHistory = "" public class var sharedInstance: AlertHistoryDataManager { struct Singleton { static let instance = AlertHistoryDataManager() } return Singleton.instance } /** Method to kick off worklight call to grab all alert history data - parameter callback: method to call when complete */ public func getAlertHistory(callback: ((Bool)->())!) { self.callback = callback let adapterName = "PerchAdapter" let procedureName = "getAllNotifications" let caller = WLProcedureCaller(adapterName: adapterName, procedureName: procedureName) var params: [String] // if let to get currDevId if let currDevId = CurrentSensorDataManager.sharedInstance.lastSelectedAsset { self.lastLoadedAlertHistory = currDevId params = [currentUser.userPin, currDevId] } else { params = [currentUser.userPin, ""] } caller.invokeWithResponse(self, params: params) } /** Method to parse json dictionary received from backend - parameter worklightResponseJson: json dictionary - returns: an array of SensorData objects */ func parseAlertHistoryResponse(worklightResponseJson: NSDictionary) -> [Alert] { var alertArray: [Alert] = [] if let serverAlerts = worklightResponseJson["result"] as? NSArray { for alert in serverAlerts { if let alertDictionary = alert as? NSDictionary { var alertObject: Alert! // This auto parsing into the object's properties is done through the JsonObject library alertObject = Alert(dictionary: alertDictionary, shouldValidate: false) // Since our timestamp info was not passed in a human readable format, we need to call this method to set the format alertObject.computeOptionalProperties() alertArray.append(alertObject) } } } return alertArray } } extension AlertHistoryDataManager: WLDataDelegate { /** Delgate method for WorkLight. Called when connection and return is successful - parameter response: Response from WorkLight */ public func onSuccess(response: WLResponse!) { MQALogger.log("Alert History Fetch Success Response: \(response.responseText)", withLevel: MQALogLevelInfo) let responseJson = response.getResponseJson() as NSDictionary alerts = parseAlertHistoryResponse(responseJson) callback(true) } /** Delgate method for WorkLight. Called when connection or return is unsuccessful - parameter response: Response from WorkLight */ public func onFailure(response: WLFailResponse!) { MQALogger.log("Alert History Fetch Failure Response: \(response.responseText)", withLevel: MQALogLevelInfo) if (response.errorCode.rawValue == 0) && (response.errorMsg != nil) { MQALogger.log("Response Failure with error: \(response.errorMsg)", withLevel: MQALogLevelInfo) } callback(false) } /** Delgate method for WorkLight. Task to do before executing a call. */ public func onPreExecute() { } /** Delgate method for WorkLight. Task to do after executing a call. */ public func onPostExecute() { } }
4aacf41acb75641762ec02a88bac2a15
32.965812
136
0.635128
false
false
false
false
zjjzmw1/SwiftCodeFragments
refs/heads/master
SwiftCodeFragments/Frameworks/MRPullToRefreshLoadMore/MRPullToRefreshLoadMore.swift
mit
2
import UIKit @objc public protocol MRPullToRefreshLoadMoreDelegate { func viewShouldRefresh(scrollView:UIScrollView) func viewShouldLoadMore(scrollView:UIScrollView) } public class MRPullToRefreshLoadMore:NSObject { public var scrollView:UIScrollView? public var pullToRefreshLoadMoreDelegate:MRPullToRefreshLoadMoreDelegate? public var enabled:Bool = true public var startingContentInset:UIEdgeInsets? public var pullToRefreshViewState:ViewState = ViewState.Normal public var loadMoreViewState:ViewState = ViewState.Normal public var arrowImage: CALayer? public var activityView: UIActivityIndicatorView? public var indicatorPullToRefresh = IndicatorView() public var indicatorLoadMore = IndicatorView() public var indicatorTintColor: UIColor? { didSet { indicatorLoadMore.indicatorTintColor = (indicatorTintColor ?? UIColor.red) indicatorPullToRefresh.indicatorTintColor = (indicatorTintColor ?? UIColor.red) } } var indicatorSize: CGSize = CGSize.init(width: 30.0, height: 30.0) public var textColor:UIColor = UIColor.red public enum ViewState { case Normal case LoadingHorizontal case LoadingVertical case ReadyHorizontal case ReadyVertical } public enum Drag { case Left case Top case Right case Bottom case None } public func initWithScrollView(scrollView:UIScrollView) { scrollView.addSubview(indicatorPullToRefresh) scrollView.addSubview(indicatorLoadMore) self.scrollView = scrollView scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil) startingContentInset = scrollView.contentInset //print(startingContentInset) self.enabled = true setPullState(state: ViewState.Normal) setLoadMoreState(state: ViewState.Normal) } public func setLoadMoreState(state:ViewState) { loadMoreViewState = state switch (state) { case ViewState.ReadyVertical, ViewState.ReadyHorizontal: scrollView!.contentInset = self.startingContentInset! indicatorLoadMore.setAnimating(animating: false) case ViewState.Normal: indicatorLoadMore.setAnimating(animating: false) UIView.animate(withDuration: 0.2, animations: { self.scrollView!.contentInset = self.startingContentInset! }) case ViewState.LoadingVertical: indicatorLoadMore.setAnimating(animating: true) scrollView!.contentInset = UIEdgeInsetsMake(0.0, 0.0, 60.0, 0.0) case ViewState.LoadingHorizontal: indicatorLoadMore.setAnimating(animating: true) scrollView!.contentInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 60.0) } } public func setPullState(state:ViewState) { pullToRefreshViewState = state switch (state) { case ViewState.ReadyHorizontal, ViewState.ReadyVertical: scrollView!.contentInset = self.startingContentInset! indicatorPullToRefresh.setAnimating(animating: false) case ViewState.Normal: indicatorPullToRefresh.setAnimating(animating: false) UIView.animate(withDuration: 0.2, animations: { self.scrollView!.contentInset = self.startingContentInset! }) case ViewState.LoadingHorizontal: indicatorPullToRefresh.setAnimating(animating: true) scrollView!.contentInset = UIEdgeInsetsMake(0.0, 60.0, 0.0, 0.0) case ViewState.LoadingVertical: indicatorPullToRefresh.setAnimating(animating: true) scrollView!.contentInset = UIEdgeInsetsMake(60.0, 0.0, 0.0, 0.0) } } override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { //} //override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { switch (keyPath) { case .some("contentOffset"): if (enabled) { // HORIZONTAL SCROLL let diff_x_end = scrollView!.contentOffset.x + scrollView!.bounds.width - scrollView!.contentSize.width let diff_x_start = 0 - scrollView!.contentOffset.x let diff_y_end = scrollView!.contentOffset.y + scrollView!.bounds.height - scrollView!.contentSize.height let diff_y_start = 0 - scrollView!.contentOffset.y var drag:Drag = .None // pull to refresh if diff_x_start > 0.0 { drag = .Left } else if diff_y_start > 0.0 { drag = .Top } else if diff_x_end > 0.0 { drag = .Right } else if diff_y_end > 0.0 { drag = .Bottom } switch(drag) { case .Top: indicatorPullToRefresh.frame = CGRect.init(x: scrollView!.bounds.width/2 - indicatorSize.width/2, y: -scrollView!.bounds.origin.y - 45 + scrollView!.contentOffset.y, width: indicatorSize.width, height: indicatorSize.height) case .Left: indicatorPullToRefresh.frame = CGRect.init(x: -45, y: scrollView!.bounds.height/2-15, width: indicatorSize.width, height: indicatorSize.height) case .Bottom: //indicatorLoadMore.frame = CGRectMake(scrollView!.bounds.width/2 - indicatorSize.width/2, 15 + scrollView!.contentSize.height, indicatorSize.width, indicatorSize.height) indicatorLoadMore.frame = CGRect.init(x: scrollView!.bounds.width/2 - indicatorSize.width/2, y: 15 + scrollView!.contentSize.height, width: indicatorSize.width, height: indicatorSize.height) case .Right: //indicatorLoadMore.frame = CGRectMake(scrollView!.contentSize.width + 15, scrollView!.bounds.height/2 - 15, indicatorSize.width, indicatorSize.height) indicatorLoadMore.frame = CGRect.init(x: scrollView!.contentSize.width + 15, y: scrollView!.bounds.height/2-15, width: indicatorSize.width, height: indicatorSize.height) default: break } if (scrollView!.isDragging) { switch(drag) { case .Top: switch(pullToRefreshViewState) { case ViewState.ReadyVertical: indicatorPullToRefresh.interactiveProgress = diff_y_start / 130.0 if (diff_y_start < 65.0) { setPullState(state: ViewState.Normal) } case ViewState.Normal: indicatorPullToRefresh.interactiveProgress = diff_y_start / 130.0 if (diff_y_start > 65.0) { setPullState(state: ViewState.ReadyVertical) } default: break } case .Left: switch(pullToRefreshViewState) { case ViewState.ReadyHorizontal: indicatorPullToRefresh.interactiveProgress = diff_x_start / 130.0 if (diff_x_start < 65.0) { setPullState(state: ViewState.Normal) } case ViewState.Normal: indicatorPullToRefresh.interactiveProgress = diff_x_start / 130.0 if (diff_x_start > 65.0) { setPullState(state: ViewState.ReadyHorizontal) } default: break } case .Bottom: switch(loadMoreViewState) { case ViewState.ReadyVertical: indicatorLoadMore.interactiveProgress = diff_y_end / 130.0 if (diff_y_end < 65.0) { setLoadMoreState(state: ViewState.Normal) } case ViewState.Normal: indicatorLoadMore.interactiveProgress = diff_y_end / 130.0 if (diff_y_end > 65.0) { setLoadMoreState(state: ViewState.ReadyVertical) } default: break } case .Right: switch(loadMoreViewState) { case ViewState.ReadyHorizontal: indicatorLoadMore.interactiveProgress = diff_x_end / 130.0 if (diff_x_end < 65.0) { setLoadMoreState(state: ViewState.Normal) } case ViewState.Normal: indicatorLoadMore.interactiveProgress = diff_x_end / 130.0 if (diff_x_end > 65.0) { setLoadMoreState(state: ViewState.ReadyHorizontal) } default: break } default: break } } else { // pull to refresh if (pullToRefreshViewState == ViewState.ReadyHorizontal || pullToRefreshViewState == ViewState.ReadyVertical) { UIView.animate(withDuration: 0.2, animations: { if self.pullToRefreshViewState == ViewState.ReadyHorizontal { self.setPullState(state: ViewState.LoadingHorizontal) } else { self.setPullState(state: ViewState.LoadingVertical) } }) if let pullToRefreshLoadMoreDelegate = pullToRefreshLoadMoreDelegate { pullToRefreshLoadMoreDelegate.viewShouldRefresh(scrollView: scrollView!) } } // load more if (loadMoreViewState == ViewState.ReadyHorizontal || loadMoreViewState == ViewState.ReadyVertical) { UIView.animate(withDuration: 0.2, animations: { if self.loadMoreViewState == ViewState.ReadyHorizontal { self.setLoadMoreState(state: ViewState.LoadingHorizontal) } else { self.setLoadMoreState(state: ViewState.LoadingVertical) } }) if let pullToRefreshLoadMoreDelegate = pullToRefreshLoadMoreDelegate { pullToRefreshLoadMoreDelegate.viewShouldLoadMore(scrollView: scrollView!) } } } //print(loadMoreViewState) } default: break } } } public class MRTableView:UITableView { public var pullToRefresh:MRPullToRefreshLoadMore = MRPullToRefreshLoadMore() required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) pullToRefresh.initWithScrollView(scrollView: self) } override public init(frame: CGRect, style: UITableViewStyle) { super.init(frame:frame, style:style) pullToRefresh.initWithScrollView(scrollView: self) } } public class MRCollectionView:UICollectionView { public var pullToRefresh:MRPullToRefreshLoadMore = MRPullToRefreshLoadMore() required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) pullToRefresh.initWithScrollView(scrollView: self) } override public init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame:frame, collectionViewLayout:layout) pullToRefresh.initWithScrollView(scrollView: self) } }
e5b23f66f27eedc6c93cc03e813825d8
44.37234
243
0.549433
false
false
false
false
sayanee/ios-learning
refs/heads/master
Smashtag/Smashtag/TweetTableViewCell.swift
mit
1
// // TweetTableViewCell.swift // Smashtag // // Created by Sayanee Basu on 14/1/16. // Copyright © 2016 Sayanee Basu. All rights reserved. // import UIKit class TweetTableViewCell: UITableViewCell { var tweet: Tweet? { didSet { updateUI() } } @IBOutlet weak var tweetProfileImageView: UIImageView! @IBOutlet weak var tweetScreenNameLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! func updateUI() { tweetTextLabel?.attributedText = nil tweetScreenNameLabel?.text = nil tweetProfileImageView?.image = nil // tweetCreatedLabel?.text = nil if let tweet = self.tweet { tweetTextLabel?.text = tweet.text if tweetTextLabel?.text != nil { for _ in tweet.media { tweetTextLabel.text! += " 📷" } } tweetScreenNameLabel?.text = "\(tweet.user)" if let profileImageURL = tweet.user.profileImageURL { if let imageData = NSData(contentsOfURL: profileImageURL) { // blocks main thread! tweetProfileImageView?.image = UIImage(data: imageData) } } // let formatter = NSDateFormatter() // if NSDate().timeIntervalSinceDate(tweet.created) > 24*60*60 { // formatter.dateStyle = NSDateFormatterStyle.ShortStyle // } else { // formatter.timeStyle = NSDateFormatterStyle.ShortStyle // } // // tweetCreatedLabel?.text = formatter.stringFromDate(tweet.created) } } }
5fc276250ae119392e5df9c668fb5ca6
29.607143
79
0.549592
false
false
false
false
andrebng/Food-Diary
refs/heads/master
Food Snap/View Controllers/New Meal View Controller/View Models/NewMealViewViewModel.swift
mit
1
// // NewMealViewViewModel.swift // Food Snap // // Created by Andre Nguyen on 9/21/17. // Copyright © 2017 Idiots. All rights reserved. // import UIKit enum ViewModelState { case isEmpty case isMissingValue case notEmpty } @available(iOS 11.0, *) class NewMealViewViewModel { // MARK: - Properties var name: String = "" { didSet { didUpdateName?(name) } } var calories: Float = 0 { didSet { caloriesAsString = String(format: "%.0f kcal", calories) } } var caloriesAsString: String = "" { didSet { didUpdateCaloriesString?(caloriesAsString) } } var fat: Float = 0 { didSet { fatAsString = String(format: "%.0f g", fat) } } var fatAsString: String = "" { didSet { didUpdateFatString?(fatAsString) } } // MARK: - var image: UIImage = UIImage() { didSet { performImageRecognition(image: image) } } // MARK: - Public Interface var didUpdateName: ((String) -> ())? var didUpdateCaloriesString: ((String) -> ())? var didUpdateFatString: ((String) -> ())? // MARK: - var queryingDidChange: ((Bool) -> ())? var didRecognizeImages: (([Meal]) -> ())? // MARK: - Private private lazy var mlManager = MLManager() private lazy var nutritionixAPI = NutritionixAPI() private var querying: Bool = false { didSet { queryingDidChange?(querying) } } // MARK - Public Methods func toMeal() -> Meal? { if (self.state() == .isEmpty || self.state() == .isMissingValue) { return nil } return Meal(name: name, calories: calories, fat: fat) } func state() -> ViewModelState { let hasNameValue = (name.isEmpty && name != "Name of Food / Dish") ? false : true let hasCaloriesValue = caloriesAsString.isEmpty ? false : true let hasFatValue = fatAsString.isEmpty ? false : true if (!hasNameValue && !hasCaloriesValue && !hasFatValue) { return .isEmpty } else if (hasNameValue && hasCaloriesValue && hasFatValue) { return .notEmpty } return .isMissingValue } // MARK - Helper Methods func performImageRecognition(image: UIImage?) { guard let image = image else { return } querying = true let prediction = mlManager.predictionForImage(image: image) if let meal = prediction { nutritionixAPI.nutritionInfo(foodName: meal) { [weak self] (meals, error) in if let error = error { print("Error forwarding meals (\(error)") } else { self?.querying = false if let meals = meals { self?.didRecognizeImages?(meals) } } } } } }
7805be4fa03cdf46737355c01eaac772
23.294574
89
0.513082
false
false
false
false
natestedman/PrettyOkayKit
refs/heads/master
PrettyOkayKit/WantEndpoint.swift
isc
1
// Copyright (c) 2016, Nate Stedman <[email protected]> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. import Endpoint import Foundation import Result // MARK: - Wanting /// An endpoint for wanting a product. internal struct WantEndpoint: CSRFTokenEndpointType { // MARK: - Initialization /** Initializes a want endpoint. - parameter identifier: The identifier of the product to want. */ init(username: String, identifier: ModelIdentifier, CSRFToken: String) { self.username = username self.identifier = identifier self.CSRFToken = CSRFToken } // MARK: - Data /// The username of the user wanting the product. let username: String /// The identifier of the product to want. let identifier: ModelIdentifier /// The CSRF token for the request. let CSRFToken: String } extension WantEndpoint: Encoding { var encoded: [String : AnyObject] { return ["product_id": identifier] } } extension WantEndpoint: BaseURLEndpointType, BodyProviderType, HeaderFieldsProviderType, MethodProviderType, RelativeURLStringProviderType { var method: Endpoint.Method { return .Post } var relativeURLString: String { return "users/\(username.pathEscaped)/goods" } } extension WantEndpoint: ProcessingType { func resultForInput(input: AnyObject) -> Result<String?, NSError> { return .Success( (input as? [String:AnyObject]) .flatMap({ $0["_links"] as? [String:AnyObject] }) .flatMap({ $0["self"] as? [String:AnyObject] }) .flatMap({ $0["href"] as? String }) .map({ $0.removeLeadingCharacter }) ) } } // MARK: - Unwanting /// An endpoint for unwanting a product. internal struct UnwantEndpoint: CSRFTokenEndpointType { // MARK: - Initialization /// Initializes an unwant endpoint /// /// - parameter goodDeletePath: The URL path to use. /// - parameter CSRFToken: The CSRF token to use. init(goodDeletePath: String, CSRFToken: String) { self.goodDeletePath = goodDeletePath self.CSRFToken = CSRFToken } // MARK: - Data /// The URL path to request. let goodDeletePath: String /// A CSRF token. let CSRFToken: String } extension UnwantEndpoint: BaseURLEndpointType, HeaderFieldsProviderType, MethodProviderType, RelativeURLStringProviderType { var method: Endpoint.Method { return .Delete } var relativeURLString: String { return goodDeletePath } var headerFields: [String : String] { return ["Csrf-Token": CSRFToken] } } extension UnwantEndpoint: ProcessingType { func resultForInput(input: AnyObject) -> Result<String?, NSError> { return .Success(nil) } } /// A protocol for endpoints that require a CSRF token. protocol CSRFTokenEndpointType { /// The CSRF token. var CSRFToken: String { get } } // MARK: - Encodable Endpoint Extension extension Encoding where Self: BodyProviderType, Self: HeaderFieldsProviderType, Self: CSRFTokenEndpointType { var body: BodyType? { return try? NSJSONSerialization.dataWithJSONObject(encoded, options: []) } var headerFields: [String: String] { return [ "Content-Type": "application/json;charset=UTF-8", "Csrf-Token": CSRFToken, "Origin": "https://verygoods.co", "X-Requested-With": "XMLHttpRequest", "Referer": "https://verygoods.co" ] } }
aaa18e7f3b40f8d834a88f0ecf1eca2d
27.986755
108
0.648846
false
false
false
false
anitaleung/codepath-tip-pal
refs/heads/master
tips/ViewController.swift
mit
2
// // ViewController.swift // tips // // Created by Anita on 12/4/15. // Copyright © 2015 Anita. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var beneathBillField: UITextField! let defaults = NSUserDefaults.standardUserDefaults() override func viewDidLoad() { super.viewDidLoad() tipControl.selectedSegmentIndex = 1 billField.text = defaults.stringForKey("lastAmount")! tipLabel.text = "$0.00" totalLabel.text = "$0.00" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) doCalculations() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Do calculations for total price func doCalculations() { let defaultTipPercent = defaults.stringForKey("defaultTip") var tipPercent = 20.0 if (defaultTipPercent != nil) { tipPercent = Double(defaultTipPercent!)! } var tipPercentages = [tipPercent - 2, tipPercent, tipPercent + 2] let tipPercentage = tipPercentages[tipControl.selectedSegmentIndex] / 100 for i in 0...2 { tipControl.setTitle(String(format: "%.f%%", tipPercentages[i]), forSegmentAtIndex: i) if (tipPercent == 0) { tipControl.setTitle("0%", forSegmentAtIndex: i) } } let billAmount = NSString(string: billField.text!).doubleValue let tip = abs(billAmount * tipPercentage) let total = billAmount + tip defaults.setObject(billField.text, forKey: "lastAmount") defaults.synchronize() tipLabel.text = "$\(tip)" totalLabel.text = "$\(total)" tipLabel.text = String(format: "$%.2f", tip) totalLabel.text = String(format: "$%.2f", total) } @IBAction func onEditingChanged(sender: AnyObject) { doCalculations() } // Close keyboard when user taps elsewhere @IBAction func onTap(sender: AnyObject) { view.endEditing(true) } // Animations }
d74041dcbdd2ec046ca7a0ee8e8af504
27.337209
97
0.613049
false
false
false
false
TheDarkCode/Example-Swift-Apps
refs/heads/master
Exercises and Basic Principles/seques-basics/seques-basics/ViewController.swift
mit
1
// // ViewController.swift // seques-basics // // Created by Mark Hamilton on 2/19/16. // Copyright © 2016 dryverless. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func loadBlue(sender: AnyObject!) { // Use SENDER to Pass Any Data let sendString: String = "Just came from Yellow View!" performSegueWithIdentifier("goToBlue", sender: sendString) } @IBAction func loadRed(sender: AnyObject!) { performSegueWithIdentifier("goToRed", sender: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Do any work before view loads. // Other View controller has already been initialized, just not in view. if segue.identifier == "goToBlue" { if let blueVC = segue.destinationViewController as? BlueViewController { if let sentStr = sender as? String { blueVC.transferText = sentStr } } } } }
7bc21dd6f93597c0ee250ec122325cb8
23.66
84
0.559611
false
false
false
false
damicreabox/Git2Swift
refs/heads/master
Sources/Git2Swift/authentication/KeyAuthentication.swift
apache-2.0
1
// // KeyAuthentication.swift // Git2Swift // // Created by Damien Giron on 11/09/2016. // Copyright © 2016 Creabox. All rights reserved. // import Foundation import CLibgit2 public protocol SshKeyData { /// Find user name var username : String? { get } /// Find public key URL var publicKey : URL { get } /// Find private key URL var privateKey : URL { get } /// Key pass phrase (may be nil) var passphrase : String? { get } } public struct RawSshKeyData : SshKeyData { public let username : String? public let publicKey : URL public let privateKey : URL public let passphrase : String? public init(username : String?, publicKey : URL, privateKey : URL, passphrase : String? = nil) { self.username = username self.publicKey = publicKey self.privateKey = privateKey self.passphrase = passphrase } } /// Ssh key delegate public protocol SshKeyDelegate { /// Get ssh key data /// /// - parameter username: username /// - parameter url: url /// /// - returns: Password data func get(username: String?, url: URL?) -> SshKeyData } /// SSh authentication public class SshKeyHandler : AuthenticationHandler { /// Delegate to access SSH key private let sshKeyDelegate: SshKeyDelegate public init(sshKeyDelegate: SshKeyDelegate) { self.sshKeyDelegate = sshKeyDelegate } /// Authentication /// /// - parameter out: Git credential /// - parameter url: url /// - parameter username: username /// /// - returns: 0 on ok public func authenticate(out: UnsafeMutablePointer<UnsafeMutablePointer<git_cred>?>?, url: String?, username: String?) -> Int32 { // Find ssh key data let sshKeyData = sshKeyDelegate.get(username: username, url: url == nil ? nil : URL(string: url!)) // Public key let publicKey = sshKeyData.publicKey.path if (FileManager.default.fileExists(atPath: publicKey) == false) { return 1 } // Private key let privateKey = sshKeyData.privateKey.path if (FileManager.default.fileExists(atPath: privateKey) == false) { return 2 } // User name let optionalUsername = sshKeyData.username let optionalPassPhrase = sshKeyData.passphrase return git_cred_ssh_key_new(out, optionalUsername == nil ? "": optionalUsername!, publicKey, privateKey, optionalPassPhrase == nil ? "": optionalPassPhrase!) } }
68bf976dee21c3e2d11916df71c3b4b3
25.564815
106
0.560823
false
false
false
false
chenzhe555/core-ios-swift
refs/heads/master
core-ios-swift/AppDelegate.swift
mit
1
// // AppDelegate.swift // core-ios-swift // // Created by 陈哲#[email protected] on 16/2/17. // Copyright © 2016年 陈哲是个好孩子. All rights reserved. // import UIKit import Alamofire typealias funcBlock = () -> String @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, BaseHttpServiceDelegate_s { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let dic1: NSMutableDictionary = ["key1":"1111","key2":"2222","key1":"333","key6": ["key1":"66","key2": "xxxx"]]; let dic2: NSMutableDictionary = ["key1":"1111","key2":"2222","key1":"333","key6": ["key1":"66","key2": "xxxx"]]; // BaseHttpEncryption.encrytionParameterMethod1(dic1, andKeyArray: MCHttpEncryption.setParametersArray()); do{ try BaseHttpEncryption_s.encrytionParameterMethod1(dic2, keyArray: MCHttpEncryption_s.setParametersArray()); } catch BaseHttpErrorType_s.NotOverrideMethod_setParamater { print("------------------"); } catch { } // Alamofire.request(.GET, "http://www.test.com").responseJSON { (response) -> Void in // print("回来了呢\(response.result)"); // }; // // // // // Alamofire.request(.GET, "http://localhost/launchadconfig/getimg", parameters: ["account": "chenzhe","password": "111"], encoding: .URL, headers: ["Content-Type": "application/json"]).responseJSON { (response) -> Void in // print(response.result); // }; // Alamofire.request(.GET, "http://localhost/launchadconfig/getimg").responseJSON { (response) -> Void in // print(response.result.value); // }"core-ios-swift/Framework_swift/Service/*.{h,swift}" // MCLog("陈哲是个好孩子"); let service = MCHttpService(); service.delegate = self; // service.login("chenzhe", password: "111", requsetObj: HttpAppendParamaters_s.init(needToken: true, alertType: MCHttpAlertType_s.MCHttpAlertTypeNone_s)); service.login("chenzhe", password: "111", condition: BaseHttpAppendCondition_s()); let v1: UIViewController = ViewController(); let v2: UIViewController = ViewController(); let v3: UIViewController = ViewController(); let v4: UIViewController = ViewController(); let nav1: UINavigationController = UINavigationController(rootViewController: v1); let nav2: UINavigationController = UINavigationController(rootViewController: v2); let nav3: UINavigationController = UINavigationController(rootViewController: v3); let nav4: UINavigationController = UINavigationController(rootViewController: v4); let tabbar: BaseTabbar_s = BaseTabbar_s(); tabbar.setDataArray(["1111","2222","333","4"], normalArray: [UIImage(named: "icon_my_normal")!,UIImage(named: "icon_allGoods_normal")!,UIImage(named: "icon_home_normal")!,UIImage(named: "icon_shopCart_normal")!], selectedArray: [UIImage(named: "icon_my_selected")!,UIImage(named: "icon_allGoods_selected")!,UIImage(named: "icon_home_selected")!,UIImage(named: "icon_shopCart_selected")!]); tabbar.viewControllers = [nav1,nav2,nav3,nav4]; tabbar.createTabbar(); self.window?.rootViewController = tabbar; return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func requesetSuccess(response: BaseHttpResponse_s) { print("打印出来是---\(response.object)"); } func requestFail(response: BaseHttpResponse_s) { print("失败打印出来是---\(response.object)"); } }
c870c92416a7c5e46cefac10cbbfff2a
46.025862
397
0.672411
false
false
false
false
zvonicek/ImageSlideshow
refs/heads/master
ImageSlideshow/Classes/Core/ActivityIndicator.swift
mit
1
// // ActivityIndicator.swift // ImageSlideshow // // Created by Petr Zvoníček on 01.05.17. // import UIKit /// Cusotm Activity Indicator can be used by implementing this protocol public protocol ActivityIndicatorView { /// View of the activity indicator var view: UIView { get } /// Show activity indicator func show() /// Hide activity indicator func hide() } /// Factory protocol to create new ActivityIndicatorViews. Meant to be implemented when creating custom activity indicator. public protocol ActivityIndicatorFactory { func create() -> ActivityIndicatorView } /// Default ActivityIndicatorView implementation for UIActivityIndicatorView extension UIActivityIndicatorView: ActivityIndicatorView { public var view: UIView { return self } public func show() { startAnimating() } public func hide() { stopAnimating() } } /// Default activity indicator factory creating UIActivityIndicatorView instances @objcMembers open class DefaultActivityIndicator: ActivityIndicatorFactory { /// activity indicator style open var style: UIActivityIndicatorViewStyle /// activity indicator color open var color: UIColor? /// Create a new ActivityIndicator for UIActivityIndicatorView /// /// - style: activity indicator style /// - color: activity indicator color public init(style: UIActivityIndicatorViewStyle = .gray, color: UIColor? = nil) { self.style = style self.color = color } /// create ActivityIndicatorView instance open func create() -> ActivityIndicatorView { #if swift(>=4.2) let activityIndicator = UIActivityIndicatorView(style: style) #else let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: style) #endif activityIndicator.color = color activityIndicator.hidesWhenStopped = true return activityIndicator } }
527d3ca7878f0a668498857ef11c9317
26.291667
123
0.703817
false
false
false
false
shinobicontrols/iOS8-LevellingUp
refs/heads/master
LevellingUp/NotificationAuthorisationViewController.swift
apache-2.0
1
// // Copyright 2015 Scott Logic // // 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 class NotificationAuthorisationViewController: UIViewController { let red = UIColor.redColor() let green = UIColor.greenColor() @IBOutlet weak var badgesLabel: UILabel! @IBOutlet weak var soundsLabel: UILabel! @IBOutlet weak var alertsLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() title = "Notification Authorisation" // Register to get updates on notification authorisation status NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateLabelsWithCurrentStatus", name: userNotificationSettingsKey, object: nil) // Do any additional setup after loading the view. updateLabelsWithCurrentStatus() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK:- Actions @IBAction func handleRequestAction(sender: AnyObject) { let requestedTypes: UIUserNotificationType = .Alert | .Sound | .Badge requestNotificationsForTypes(requestedTypes) } @IBAction func handleJumpToSettings(sender: AnyObject) { let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString) UIApplication.sharedApplication().openURL(settingsUrl!) } // MARK:- Utils func updateLabelsWithCurrentStatus() { let types = UIApplication.sharedApplication().currentUserNotificationSettings().types badgesLabel.backgroundColor = (types & UIUserNotificationType.Badge == nil) ? red : green alertsLabel.backgroundColor = (types & UIUserNotificationType.Alert == nil) ? red : green soundsLabel.backgroundColor = (types & UIUserNotificationType.Sound == nil) ? red : green } private func requestNotificationsForTypes(types: UIUserNotificationType) { let settingsRequest = UIUserNotificationSettings(forTypes: types, categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settingsRequest) } }
5dd020703ca7059077a5376ea1c61213
33.438356
93
0.743835
false
false
false
false
archagon/tasty-imitation-keyboard
refs/heads/master
Keyboard/Catboard.swift
bsd-3-clause
1
// // Catboard.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 9/24/14. // Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved. // import UIKit /* This is the demo keyboard. If you're implementing your own keyboard, simply follow the example here and then set the name of your KeyboardViewController subclass in the Info.plist file. */ let kCatTypeEnabled = "kCatTypeEnabled" class Catboard: KeyboardViewController { let takeDebugScreenshot: Bool = false override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { UserDefaults.standard.register(defaults: [kCatTypeEnabled: true]) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func keyPressed(_ key: Key) { let textDocumentProxy = self.textDocumentProxy let keyOutput = key.outputForCase(self.shiftState.uppercase()) if !UserDefaults.standard.bool(forKey: kCatTypeEnabled) { textDocumentProxy.insertText(keyOutput) return } if key.type == .character || key.type == .specialCharacter { if let context = textDocumentProxy.documentContextBeforeInput { if context.characters.count < 2 { textDocumentProxy.insertText(keyOutput) return } var index = context.endIndex index = context.index(before: index) if context[index] != " " { textDocumentProxy.insertText(keyOutput) return } index = context.index(before: index) if context[index] == " " { textDocumentProxy.insertText(keyOutput) return } textDocumentProxy.insertText("\(randomCat())") textDocumentProxy.insertText(" ") textDocumentProxy.insertText(keyOutput) return } else { textDocumentProxy.insertText(keyOutput) return } } else { textDocumentProxy.insertText(keyOutput) return } } override func setupKeys() { super.setupKeys() if takeDebugScreenshot { if self.layout == nil { return } for page in keyboard.pages { for rowKeys in page.rows { for key in rowKeys { if let keyView = self.layout!.viewForKey(key) { keyView.addTarget(self, action: #selector(Catboard.takeScreenshotDelay), for: .touchDown) } } } } } } override func createBanner() -> ExtraView? { return CatboardBanner(globalColors: type(of: self).globalColors, darkMode: false, solidColorMode: self.solidColorMode()) } func takeScreenshotDelay() { Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(Catboard.takeScreenshot), userInfo: nil, repeats: false) } func takeScreenshot() { if !self.view.bounds.isEmpty { UIDevice.current.beginGeneratingDeviceOrientationNotifications() let oldViewColor = self.view.backgroundColor self.view.backgroundColor = UIColor(hue: (216/360.0), saturation: 0.05, brightness: 0.86, alpha: 1) let rect = self.view.bounds UIGraphicsBeginImageContextWithOptions(rect.size, true, 0) self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: true) let capturedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // AB: consider re-enabling this when interfaceOrientation actually breaks //// HACK: Detecting orientation manually //let screenSize: CGSize = UIScreen.main.bounds.size //let orientation: UIInterfaceOrientation = screenSize.width < screenSize.height ? .portrait : .landscapeLeft //let name = (orientation.isPortrait ? "Screenshot-Portrait" : "Screenshot-Landscape") let name = (self.interfaceOrientation.isPortrait ? "Screenshot-Portrait" : "Screenshot-Landscape") let imagePath = "/Users/archagon/Documents/Programming/OSX/RussianPhoneticKeyboard/External/tasty-imitation-keyboard/\(name).png" if let pngRep = UIImagePNGRepresentation(capturedImage!) { try? pngRep.write(to: URL(fileURLWithPath: imagePath), options: [.atomic]) } self.view.backgroundColor = oldViewColor } } } func randomCat() -> String { let cats = "🐱😺😸😹😽😻😿😾😼🙀" let numCats = cats.characters.count let randomCat = arc4random() % UInt32(numCats) let index = cats.characters.index(cats.startIndex, offsetBy: Int(randomCat)) let character = cats[index] return String(character) }
261018cc6dff96b1f7ab6b6f0d59d13d
35.387755
141
0.581417
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat/Models/Subscription/Subscription.swift
mit
1
// // Subscription.swift // Rocket.Chat // // Created by Rafael K. Streit on 7/9/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import Foundation import RealmSwift import SwiftyJSON enum SubscriptionType: String, Equatable { case directMessage = "d" case channel = "c" case group = "p" } enum SubscriptionNotificationsStatus: String, CaseIterable { case `default` case nothing case all case mentions } enum SubscriptionNotificationsAudioValue: String, CaseIterable { case none case `default` case beep case chelle case ding case droplet case highbell case seasons } typealias RoomType = SubscriptionType final class Subscription: BaseModel { @objc dynamic var auth: Auth? @objc internal dynamic var privateType = SubscriptionType.channel.rawValue var type: SubscriptionType { get { return SubscriptionType(rawValue: privateType) ?? SubscriptionType.group } set { privateType = newValue.rawValue } } @objc dynamic var rid = "" @objc dynamic var prid = "" // Name of the subscription @objc dynamic var name = "" // Full name of the user, in the case of // using the full user name setting // Setting: UI_Use_Real_Name @objc dynamic var fname = "" @objc dynamic var unread = 0 @objc dynamic var userMentions = 0 @objc dynamic var groupMentions = 0 @objc dynamic var open = false @objc dynamic var alert = false @objc dynamic var favorite = false @objc dynamic var createdAt: Date? @objc dynamic var lastSeen: Date? @objc dynamic var usersCount = 0 @objc dynamic var roomTopic: String? @objc dynamic var roomDescription: String? @objc dynamic var roomAnnouncement: String? @objc dynamic var roomReadOnly = false @objc dynamic var roomUpdatedAt: Date? @objc dynamic var roomLastMessage: Message? @objc dynamic var roomLastMessageText: String? @objc dynamic var roomLastMessageDate: Date? @objc dynamic var roomBroadcast = false let roomMuted = List<String>() @objc dynamic var roomOwnerId: String? @objc dynamic var otherUserId: String? @objc dynamic var disableNotifications = false @objc dynamic var hideUnreadStatus = false @objc dynamic var desktopNotificationDuration = 0 @objc internal dynamic var privateDesktopNotifications = SubscriptionNotificationsStatus.default.rawValue @objc internal dynamic var privateEmailNotifications = SubscriptionNotificationsStatus.default.rawValue @objc internal dynamic var privateMobilePushNotifications = SubscriptionNotificationsStatus.default.rawValue @objc internal dynamic var privateAudioNotifications = SubscriptionNotificationsStatus.default.rawValue @objc internal dynamic var privateAudioNotificationsValue = SubscriptionNotificationsAudioValue.default.rawValue var desktopNotifications: SubscriptionNotificationsStatus { get { return SubscriptionNotificationsStatus(rawValue: privateDesktopNotifications) ?? .default } set { privateDesktopNotifications = newValue.rawValue } } var emailNotifications: SubscriptionNotificationsStatus { get { return SubscriptionNotificationsStatus(rawValue: privateEmailNotifications) ?? .default } set { privateEmailNotifications = newValue.rawValue } } var mobilePushNotifications: SubscriptionNotificationsStatus { get { return SubscriptionNotificationsStatus(rawValue: privateMobilePushNotifications) ?? .default } set { privateMobilePushNotifications = newValue.rawValue } } var audioNotifications: SubscriptionNotificationsStatus { get { return SubscriptionNotificationsStatus(rawValue: privateAudioNotifications) ?? .default } set { privateAudioNotifications = newValue.rawValue } } var audioNotificationValue: SubscriptionNotificationsAudioValue { get { return SubscriptionNotificationsAudioValue(rawValue: privateAudioNotificationsValue) ?? .default } set { privateAudioNotificationsValue = newValue.rawValue } } let usersRoles = List<RoomRoles>() // MARK: Internal @objc dynamic var privateOtherUserStatus: String? var otherUserStatus: UserStatus? { if let privateOtherUserStatus = privateOtherUserStatus { return UserStatus(rawValue: privateOtherUserStatus) } else { return nil } } var messages: Results<Message>? { return Realm.current?.objects(Message.self).filter("rid == '\(rid)'") } var isDiscussion: Bool { return !prid.isEmpty } static func find(rid: String, realm: Realm? = Realm.current) -> Subscription? { return realm?.objects(Subscription.self).filter("rid == '\(rid)'").first } static func find(name: String, realm: Realm? = Realm.current) -> Subscription? { return realm?.objects(Subscription.self).filter("name == '\(name)'").first } } final class RoomRoles: Object { @objc dynamic var user: User? var roles = List<String>() } // MARK: Avatar extension Subscription { static func avatarURL(for name: String, auth: Auth? = nil) -> URL? { guard let auth = auth ?? AuthManager.isAuthenticated(), let baseURL = auth.baseURL(), let userId = auth.userId, let token = auth.token, let encodedName = name.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { return nil } return URL(string: "\(baseURL)/avatar/%22\(encodedName)?format=jpeg&rc_uid=\(userId)&rc_token=\(token)") } } // MARK: Display Name extension Subscription { func displayName() -> String { guard let settings = AuthSettingsManager.settings else { return name } if type != .directMessage { if !prid.isEmpty { return !fname.isEmpty ? fname : name } return settings.allowSpecialCharsOnRoomNames && !fname.isEmpty ? fname : name } return settings.useUserRealName && !fname.isEmpty ? fname : name } } // MARK: Unmanaged Object extension Subscription: UnmanagedConvertible { typealias UnmanagedType = UnmanagedSubscription var unmanaged: UnmanagedSubscription? { return UnmanagedSubscription(self) } }
756cf281ae372f482132a63673879dbb
31.426396
116
0.694114
false
false
false
false
enisinanaj/1-and-1.workouts
refs/heads/master
1and1.workout/Controllers/CounterViewController.swift
mit
1
// // CounterViewController.swift // 1and1.workout // // Created by Eni Sinanaj on 17/08/2017. // Copyright © 2017 Eni Sinanaj. All rights reserved. // import UIKit import AVFoundation import AudioToolbox class CounterViewController: UIViewController { var parentController: MainPageViewController? var minutes = 0 var seconds = 0 var timer: Timer! var sets: Int = 1 var timeKeeper: Double = 0.0 var startSeconds: Double = 0.0 var sectionSeconds: Double = 0.0 var differenceInSecconds: Double = 0.0 var restMinuteConsumed: Bool = false var player: AVAudioPlayer? @IBOutlet weak var counterBaseView: UIView! @IBOutlet weak var restLabel: UILabel! @IBOutlet weak var setLabel: UILabel! @IBOutlet weak var secondHand: UILabel! @IBOutlet weak var minuteHand: UILabel! var running: Bool! @IBOutlet weak var baseWindowView: UIView! override func viewDidLoad() { super.viewDidLoad() baseWindowView.layer.cornerRadius = 5 // baseWindowView.frame.origin.y = baseWindowView.frame.origin.y + 10 counterBaseView.layer.shadowColor = UIColor.black.cgColor counterBaseView.layer.shadowOffset = counterBaseView.frame.size counterBaseView.layer.shadowRadius = 100 counterBaseView.layer.shadowPath = UIBezierPath(rect: counterBaseView.bounds).cgPath counterBaseView.layer.shouldRasterize = true restLabel.isHidden = true } @IBAction func restartNewSet(_ sender: Any) { if running { return } sets = sets + 1 setLabel.text = "Set " + String(sets) restLabel.isHidden = true restMinuteConsumed = false self.timeKeeper = 0 startTime(self) } @IBAction func stopTimerAction(_ sender: Any) { let wasRunning = running parentController?.completeExercise(wasRunning!) stopTime() self.dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func startTime(_ sender: AnyObject) { running = true self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.update), userInfo: nil, repeats: true) self.timeKeeper = 0 self.startSeconds = CACurrentMediaTime() self.differenceInSecconds = 0.0 self.resetTimerCounters() } func stopTime() { timer.invalidate() running = false restLabel.isHidden = true self.resetTimerCounters() sectionSeconds = (parentController?.exercise?.duration)! * Double(sets) } func resetTimerCounters() { minutes = 0 seconds = 0 minuteHand.text = "00" secondHand.text = "00" } func startRestMinute() { stopTime() restMinuteConsumed = true startTime(self) restLabel.isHidden = false } @objc func update() { if parentController?.exercise?.duration == self.timeKeeper && !self.restMinuteConsumed { playSound() startRestMinute() } else if parentController?.exercise?.restDuration == self.timeKeeper && self.restMinuteConsumed { stopTime() } else { self.timeKeeper += 1 incrementSeconds() minuteHand.text = getAsString(timePart: minutes) secondHand.text = getAsString(timePart: seconds) } } func playSound() { let url = Bundle.main.url(forResource: "doneBell.mp3", withExtension: nil)! do { player = try AVAudioPlayer(contentsOf: url) guard let player = player else {return} player.prepareToPlay() player.play(); } catch let error as NSError { print(error.description) } } func getIntervalFromStartTime() -> Double { return CACurrentMediaTime() - startSeconds } func incrementMinutes() { if (minutes == 59) { minutes = 0 if (seconds == 59) { seconds = 0 resetTimerCounters() } } else { minutes += 1 } } func incrementSeconds() { if (seconds == 59) { seconds = 0 incrementMinutes() } else { seconds += 1 } } func reloadTimer(notification: Notification) { differenceInSecconds = CACurrentMediaTime() - self.startSeconds let divisorForMinutes = differenceInSecconds.truncatingRemainder(dividingBy: (60.0 * 60.0)) let minutesD = floor(divisorForMinutes / 60.0) let divisorForSeconds = divisorForMinutes.truncatingRemainder(dividingBy: 60.0) let secondsD = ceil(divisorForSeconds) if self.startSeconds > 0.0 { self.seconds = Int(secondsD) self.minutes = minutesD > 1 ? Int(minutesD) : self.minutes } } func secondsToTimeString(_ seconds: NSInteger) -> (minutes: NSInteger, seconds: NSInteger) { let minutes = seconds / 60 let seconds = seconds % 60 return (minutes: minutes, seconds: seconds) } func getAsString(timePart: NSInteger) -> String { if (timePart == 0) { return "00" } else if (timePart > 0 && timePart < 10) { return "0" + String(timePart) } else { return String(timePart) } } }
1b187801c1df7d9f9d2c19e5fa59b928
27.688442
136
0.583815
false
false
false
false
StachkaConf/ios-app
refs/heads/develop
StachkaIOS/StachkaIOS/Classes/Helpers/FilterFactory/FilterFactoryImplementation.swift
mit
1
// // FilterFactoryImplementation.swift // StachkaIOS // // Created by m.rakhmanov on 31.03.17. // Copyright © 2017 m.rakhmanov. All rights reserved. // import Foundation class FilterFactoryImplementation: FilterFactory { private var categoryNames = ["Разработка", "Digital-маркетинг", "Бизнес", "Образование и карьера"] private var placeNames = ["БОЛЬШОЙ ЗАЛ", "КИНОБАР", "АРХИВ", "ПРЕСС-ЦЕНТР", "ФОЙЕ ОПЦ", "КИНОЗАЛ МУЗЕЯ", "ОКТЯБРЬСКИЙ", "ЗАЛ МУЗЕЯ №16", "ФОЙЕ МУЗЕЯ", "СОВЕТСКАЯ ШКОЛА"] private var sectionNames = ["Разработка": ["Информационная безопасность", "Менеджмент", "HighLoad", "Виртуальная реальность", "DevOps", "FrontEnd", "BackEnd", "Мобильная", "Database", "Тестирование", "Управление требованиями", "Машинное обучение"], "Digital-маркетинг": ["Digital", "SEO", "Web-аналитика", "Графический продакшен", "Лидогенерация"], "Бизнес": ["Бизнес-инструменты", "Электронная коммерция"], "Образование и карьера": ["Подготовка ИТ профессионалов", "Студентам", "Управленцам, HR-ам", "IT-сообщества"]] func createFilters() -> [Filter] { return [createAllPlacesFilter()] + createCategoryFilters() } private func createCategoryFilters() -> [CategoryFilter] { return categoryNames.map { let categotyFilter = CategoryFilter() categotyFilter.title = $0 categotyFilter.selected = true let objects = createSectionFilter(withCategory: $0) // FIXME: почему-то синтаксис с append(objectsIn:) не заработал objects.forEach { categotyFilter.sectionFilters.append($0) } return categotyFilter } } private func createAllPlacesFilter() -> AllPlacesFilter { let allPlacesFilter = AllPlacesFilter() allPlacesFilter.title = "Залы" allPlacesFilter.selected = true placeNames.forEach { let placeFilter = PlaceFilter() placeFilter.title = $0 placeFilter.selected = true allPlacesFilter.placeFilters.append(placeFilter) } return allPlacesFilter } private func createSectionFilter(withCategory category: String) -> [SectionFilter] { return sectionNames[category]?.map { let sectionFilter = SectionFilter() sectionFilter.selected = true sectionFilter.title = $0 return sectionFilter } ?? [] } }
03efbf453bafb995a946747eba5ce85e
40.333333
142
0.580279
false
false
false
false
frajaona/LiFXSwiftKit
refs/heads/master
Sources/LiFXCASSocket.swift
apache-2.0
1
/* * Copyright (C) 2016 Fred Rajaona * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import CocoaAsyncSocket class LiFXCASSocket: NSObject, LiFXSocket { var messageHandler: ((LiFXMessage, String) -> ())? var udpSocket: Socket? { return rawSocket } fileprivate var rawSocket: UdpCASSocket<LiFXMessage>? func openConnection() { let socket = UdpCASSocket<LiFXMessage>(destPort: LiFXCASSocket.UdpPort, shouldBroadcast: true, socketDelegate: self) rawSocket = socket if !socket.openConnection() { closeConnection() } else { } } func closeConnection() { rawSocket?.closeConnection() rawSocket = nil } func isConnected() -> Bool { return udpSocket != nil } } extension LiFXCASSocket: GCDAsyncUdpSocketDelegate { func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) { Log.debug("socked did send data with tag \(tag)") } func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) { Log.debug("socked did not send data with tag \(tag)") } func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) { Log.debug("Socket closed: \(error?.localizedDescription)") } func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) { Log.debug("\nReceive data from isIPv4=\(GCDAsyncUdpSocket.isIPv4Address(address)) address: \(GCDAsyncUdpSocket.host(fromAddress: address))") //Log.debug(data.description) let message = LiFXMessage(fromData: data) messageHandler?(message, GCDAsyncUdpSocket.host(fromAddress: address)!) } }
0c46df7019de932ee82573d70fe9075d
31.643836
148
0.668065
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
Client/Cliqz/Foundation/Extensions/UIDeviceExtension.swift
mpl-2.0
2
// // UIDeviceExtension.swift // Client // // Created by Mahmoud Adam on 11/16/15. // Copyright © 2015 Cliqz. All rights reserved. // import Foundation public extension UIDevice { var modelName: String { let identifierKey = "UIDevice.identifier" let storedIdentified = LocalDataStore.objectForKey(identifierKey) as? String guard storedIdentified == nil else { return storedIdentified! } var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } var deviceIdentifier: String switch identifier { case "iPod5,1": deviceIdentifier = "iPod Touch 5" case "iPod7,1": deviceIdentifier = "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": deviceIdentifier = "iPhone 4" case "iPhone4,1": deviceIdentifier = "iPhone 4s" case "iPhone5,1", "iPhone5,2": deviceIdentifier = "iPhone 5" case "iPhone5,3", "iPhone5,4": deviceIdentifier = "iPhone 5c" case "iPhone6,1", "iPhone6,2": deviceIdentifier = "iPhone 5s" case "iPhone7,2": deviceIdentifier = "iPhone 6" case "iPhone7,1": deviceIdentifier = "iPhone 6 Plus" case "iPhone8,1": deviceIdentifier = "iPhone 6s" case "iPhone8,2": deviceIdentifier = "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": deviceIdentifier = "iPhone 7" case "iPhone9,2", "iPhone9,4": deviceIdentifier = "iPhone 7 Plus" case "iPhone8,4": deviceIdentifier = "iPhone SE" case "iPhone10,1", "iPhone10,4": deviceIdentifier = "iPhone 8" case "iPhone10,2", "iPhone10,5": deviceIdentifier = "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": deviceIdentifier = "iPhone X" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":deviceIdentifier = "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": deviceIdentifier = "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": deviceIdentifier = "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": deviceIdentifier = "iPad Air" case "iPad5,3", "iPad5,4": deviceIdentifier = "iPad Air 2" case "iPad6,11", "iPad6,12": deviceIdentifier = "iPad 5" case "iPad2,5", "iPad2,6", "iPad2,7": deviceIdentifier = "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": deviceIdentifier = "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": deviceIdentifier = "iPad Mini 3" case "iPad5,1", "iPad5,2": deviceIdentifier = "iPad Mini 4" case "iPad6,3", "iPad6,4": deviceIdentifier = "iPad Pro 9.7 Inch" case "iPad6,7", "iPad6,8": deviceIdentifier = "iPad Pro 12.9 Inch" case "iPad7,1", "iPad7,2": deviceIdentifier = "iPad Pro 12.9 Inch 2. Generation" case "iPad7,3", "iPad7,4": deviceIdentifier = "iPad Pro 10.5 Inch" case "AppleTV5,3": deviceIdentifier = "Apple TV" case "i386", "x86_64": deviceIdentifier = "Simulator" default: deviceIdentifier = identifier } LocalDataStore.setObject(deviceIdentifier, forKey: identifierKey) return deviceIdentifier } // Find better name func isiPhoneXDevice() -> Bool { return modelName.startsWith("iPhone X") } // Find better name func isiPad() -> Bool { return modelName.startsWith("iPad") } func isSmallIphoneDevice() -> Bool { return modelName.startsWith("iPhone 4") || modelName.startsWith("iPhone 5") || modelName.startsWith("iPhone SE") } }
f0dda31de95d564c12595ed81f4aba53
51.130952
120
0.536195
false
false
false
false
breadwallet/breadwallet-ios
refs/heads/master
breadwallet/src/ViewModels/TxDetailViewModel.swift
mit
1
// // TxDetailViewModel.swift // breadwallet // // Created by Adrian Corscadden on 2017-12-20. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import UIKit /// View model of a transaction in detail view struct TxDetailViewModel: TxViewModel { // MARK: - let amount: String let fiatAmount: String let originalFiatAmount: String? let exchangeRate: String? let tx: Transaction // Ethereum-specific fields var gasPrice: String? var gasLimit: String? var fee: String? var total: String? var title: String { guard status != .invalid else { return S.TransactionDetails.titleFailed } switch direction { case .recovered: return S.TransactionDetails.titleInternal case .received: return status == .complete ? S.TransactionDetails.titleReceived : S.TransactionDetails.titleReceiving case .sent: return status == .complete ? S.TransactionDetails.titleSent : S.TransactionDetails.titleSending } } var timestampHeader: NSAttributedString { if status == .complete { let text = " " + S.TransactionDetails.completeTimestampHeader let attributedString = NSMutableAttributedString(string: text) let icon = NSTextAttachment() icon.image = #imageLiteral(resourceName: "CircleCheckSolid").withRenderingMode(.alwaysTemplate) icon.bounds = CGRect(x: 0, y: -2.0, width: 14.0, height: 14.0) let iconString = NSMutableAttributedString(string: S.Symbols.narrowSpace) // space required before an attachment to apply template color (UIKit bug) iconString.append(NSAttributedString(attachment: icon)) attributedString.insert(iconString, at: 0) attributedString.addAttributes([.foregroundColor: UIColor.receivedGreen, .font: UIFont.customBody(size: 0.0)], range: NSRange(location: 0, length: iconString.length)) return attributedString } else { return NSAttributedString(string: S.TransactionDetails.initializedTimestampHeader) } } var addressHeader: String { if direction == .sent { return S.TransactionDetails.addressToHeader } else { if tx.currency.isBitcoinCompatible { return S.TransactionDetails.addressViaHeader } else { return S.TransactionDetails.addressFromHeader } } } var extraAttribute: String? { return tx.extraAttribute } var extraAttributeHeader: String { if tx.currency.isXRP { return S.TransactionDetails.destinationTagHeader } if tx.currency.isHBAR { return S.TransactionDetails.memoTagHeader } return "" } var transactionHash: String { return currency.isEthereumCompatible ? tx.hash : tx.hash.removing(prefix: "0x") } } extension TxDetailViewModel { init(tx: Transaction) { let rate = tx.currency.state?.currentRate ?? Rate.empty amount = TxDetailViewModel.tokenAmount(tx: tx) ?? "" let fiatAmounts = TxDetailViewModel.fiatAmounts(tx: tx, currentRate: rate) fiatAmount = fiatAmounts.0 originalFiatAmount = fiatAmounts.1 exchangeRate = TxDetailViewModel.exchangeRateText(tx: tx) self.tx = tx if tx.direction == .sent { var feeAmount = tx.fee feeAmount.maximumFractionDigits = Amount.highPrecisionDigits fee = Store.state.showFiatAmounts ? feeAmount.fiatDescription : feeAmount.tokenDescription } //TODO:CRYPTO incoming token transfers have a feeBasis with 0 values if let feeBasis = tx.feeBasis, (currency.isEthereum || (currency.isEthereumCompatible && tx.direction == .sent)) { let gasFormatter = NumberFormatter() gasFormatter.numberStyle = .decimal gasFormatter.maximumFractionDigits = 0 self.gasLimit = gasFormatter.string(from: feeBasis.costFactor as NSNumber) let gasUnit = feeBasis.pricePerCostFactor.currency.unit(named: "gwei") ?? currency.defaultUnit gasPrice = feeBasis.pricePerCostFactor.tokenDescription(in: gasUnit) } // for outgoing txns for native tokens show the total amount sent including fee if tx.direction == .sent, tx.confirmations > 0, tx.amount.currency == tx.fee.currency { var totalWithFee = tx.amount + tx.fee totalWithFee.maximumFractionDigits = Amount.highPrecisionDigits total = Store.state.showFiatAmounts ? totalWithFee.fiatDescription : totalWithFee.tokenDescription } } /// The fiat exchange rate at the time of transaction /// Returns nil if no rate found or rate currency mismatches the current fiat currency private static func exchangeRateText(tx: Transaction) -> String? { guard let metaData = tx.metaData, let currentRate = tx.currency.state?.currentRate, !metaData.exchangeRate.isZero, (metaData.exchangeRateCurrency == currentRate.code || metaData.exchangeRateCurrency.isEmpty) else { return nil } let nf = NumberFormatter() nf.currencySymbol = currentRate.currencySymbol nf.numberStyle = .currency return nf.string(from: metaData.exchangeRate as NSNumber) ?? nil } private static func tokenAmount(tx: Transaction) -> String? { let amount = Amount(amount: tx.amount, rate: nil, maximumFractionDigits: Amount.highPrecisionDigits, negative: (tx.direction == .sent && !tx.amount.isZero)) return amount.description } /// Fiat amount at current exchange rate and at original rate at time of transaction (if available) /// Returns the token transfer description for token transfer originating transactions, as first return value. /// Returns (currentFiatAmount, originalFiatAmount) private static func fiatAmounts(tx: Transaction, currentRate: Rate) -> (String, String?) { let currentAmount = Amount(amount: tx.amount, rate: currentRate).description guard let metaData = tx.metaData else { return (currentAmount, nil) } guard metaData.tokenTransfer.isEmpty else { let tokenTransfer = String(format: S.Transaction.tokenTransfer, metaData.tokenTransfer.uppercased()) return (tokenTransfer, nil) } // no tx-time rate guard !metaData.exchangeRate.isZero, (metaData.exchangeRateCurrency == currentRate.code || metaData.exchangeRateCurrency.isEmpty) else { return (currentAmount, nil) } let originalRate = Rate(code: currentRate.code, name: currentRate.name, rate: metaData.exchangeRate, reciprocalCode: currentRate.reciprocalCode) let originalAmount = Amount(amount: tx.amount, rate: originalRate).description return (currentAmount, originalAmount) } }
bdc6ed76f61566110c51889d22a0cfa9
41.113636
160
0.630464
false
false
false
false
renrawnalon/AutoHeightTextView
refs/heads/master
AutoHeightTextView/ViewController.swift
mit
1
// // ViewController.swift // AutoHeightTextView // // Created by ノーランワーナー on 2015/10/21. // Copyright © 2015年 test. All rights reserved. // import UIKit class ViewController: UIViewController, UITextViewDelegate { let verticalInset = 20.0 let horizontalInset = 10.0 let backgroundColor = UIColor(white: 0.97, alpha: 1.0) let animationDuration = 0.2 @IBOutlet weak var textView: UITextView! @IBOutlet weak var textViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var imageViewWidthConstraint: NSLayoutConstraint! @IBOutlet weak var scrollViewBottomConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() textView.textAlignment = .Left textView.showsVerticalScrollIndicator = false textView.backgroundColor = backgroundColor imageViewWidthConstraint.constant = self.view.frame.size.width - 16 NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { let oldString: NSString = textView.text let newString: NSString = oldString.stringByReplacingCharactersInRange(range, withString: text) let size = CGSizeMake(textView.frame.size.width - CGFloat(horizontalInset), CGFloat(MAXFLOAT)) let rect = newString.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: textView.font!], context: nil) textViewHeightConstraint.constant = rect.height + CGFloat(verticalInset) self.view.animateLayout(animationDuration) return true } func keyboardWillChangeFrame(notification: NSNotification) { guard let keyboardRect = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() else { return; } guard let animationDuration = (notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue else { return; } print("\(animationDuration) and \(keyboardRect)") scrollViewBottomConstraint.constant = view.frame.size.height - keyboardRect.origin.y self.view.animateLayout(animationDuration) } } extension UIView { func animateLayout(duration: NSTimeInterval) { UIView.animateWithDuration(duration, animations: { [weak self] in self?.layoutIfNeeded() }) } }
87230bd126a415e26ce63e3f52a89aed
37.356164
176
0.705357
false
false
false
false
crewshin/GasLog
refs/heads/master
Pods/Material/Sources/MaterialPulseView.swift
mit
1
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit public class MaterialPulseView : MaterialView { /// A CAShapeLayer used in the pulse animation. public private(set) lazy var pulseLayer: CAShapeLayer = CAShapeLayer() /// Sets whether the scaling animation should be used. public lazy var pulseScale: Bool = true /// Enables and disables the spotlight effect. public var spotlight: Bool = false { didSet { if spotlight { pulseFill = false } } } /** Determines if the pulse animation should fill the entire view. */ public var pulseFill: Bool = false { didSet { if pulseFill { spotlight = false } } } /// The opcaity value for the pulse animation. public var pulseColorOpacity: CGFloat = 0.25 { didSet { updatePulseLayer() } } /// The color of the pulse effect. public var pulseColor: UIColor? { didSet { updatePulseLayer() } } /** A delegation method that is executed when the view has began a touch event. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) let point: CGPoint = layer.convertPoint(touches.first!.locationInView(self), fromLayer: layer) if true == layer.containsPoint(point) { let r: CGFloat = (width < height ? height : width) / 2 let f: CGFloat = 3 let v: CGFloat = r / f let d: CGFloat = 2 * f let s: CGFloat = 1.05 let t: CFTimeInterval = 0.25 if nil != pulseColor && 0 < pulseColorOpacity { MaterialAnimation.animationDisabled { self.pulseLayer.bounds = CGRectMake(0, 0, v, v) self.pulseLayer.position = point self.pulseLayer.cornerRadius = r / d self.pulseLayer.hidden = false } pulseLayer.addAnimation(MaterialAnimation.scale(pulseFill ? 3 * d : d, duration: t), forKey: nil) } if pulseScale { layer.addAnimation(MaterialAnimation.scale(s, duration: t), forKey: nil) } } } /** A delegation method that is executed when the view touch event is moving. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesMoved(touches, withEvent: event) if spotlight { let point: CGPoint = layer.convertPoint(touches.first!.locationInView(self), fromLayer: layer) if layer.containsPoint(point) { MaterialAnimation.animationDisabled { self.pulseLayer.position = point } } } } /** A delegation method that is executed when the view touch event has ended. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesEnded(touches, withEvent: event) shrinkAnimation() } /** A delegation method that is executed when the view touch event has been cancelled. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { super.touchesCancelled(touches, withEvent: event) shrinkAnimation() } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepareView method to initialize property values and other setup operations. The super.prepareView method should always be called immediately when subclassing. */ public override func prepareView() { super.prepareView() pulseColor = MaterialColor.white preparePulseLayer() } /// Prepares the pulseLayer property. internal func preparePulseLayer() { pulseLayer.hidden = true pulseLayer.zPosition = 1 visualLayer.addSublayer(pulseLayer) } /// Updates the pulseLayer when settings have changed. internal func updatePulseLayer() { pulseLayer.backgroundColor = pulseColor?.colorWithAlphaComponent(pulseColorOpacity).CGColor } /// Executes the shrink animation for the pulse effect. internal func shrinkAnimation() { let t: CFTimeInterval = 0.25 let s: CGFloat = 1 if nil != pulseColor && 0 < pulseColorOpacity { MaterialAnimation.animateWithDuration(t, animations: { self.pulseLayer.hidden = true }) pulseLayer.addAnimation(MaterialAnimation.scale(s, duration: t), forKey: nil) } if pulseScale { layer.addAnimation(MaterialAnimation.scale(s, duration: t), forKey: nil) } } }
fa276b6ffe70151624f1cfb8f3bc06b0
31.021164
101
0.73178
false
false
false
false
hejunbinlan/BFKit-Swift
refs/heads/master
Source/BFKit/BFSystemSound.swift
mit
3
// // BFSystemSound.swift // BFKit // // The MIT License (MIT) // // Copyright (c) 2015 Fabrizio Brancati. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import AudioToolbox /// This class adds some useful functions to play system sounds public class BFSystemSound { // MARK: - Enums - /** Audio IDs enum - http://iphonedevwiki.net/index.php/AudioServices - NewMail: New Mail - MailSent: Mail Sent - VoiceMail: Voice Mail - RecivedMessage: Recived Message - SentMessage: Sent Message - Alarm: Alarm - LowPower: Low Power - SMSReceived1: SMS Received 1 - SMSReceived2: SMS Received 2 - SMSReceived3: SMS Received 3 - SMSReceived4: SMS Received 4 - SMSReceived5: SMS Received 5 - SMSReceived6: SMS Received 6 - TweetSent: Tweet Sent - Anticipate: Anticipate - Bloom: Bloom - Calypso: Calypso - ChooChoo: Choo Choo - Descent: Descent - Fanfare: Fanfare - Ladder: Ladder - Minuet: Minuet - NewsFlash: News Flash - Noir: Noir - SherwoodForest: Sherwood Forest - Spell: Spell - Suspence: Suspence - Telegraph: Telegraph - Tiptoes: Tiptoes - Typewriters: Typewriters - Update: Update - USSDAlert: USSD Alert - SIMToolkitCallDropped: SIM Toolkit Call Dropped - SIMToolkitGeneralBeep: SIM Toolkit General Beep - SIMToolkitNegativeACK: SIM Toolkit Negative ACK - SIMToolkitPositiveACK: SIM Toolkit Positive ACK - SIMToolkitSMS: SIM Toolkit SMS - Tink: Tink - CTBusy: CT Busy - CTCongestion: CT Congestion - CTPathACK: CT Path ACK - CTError: CT Error - CTCallWaiting: CT Call Waiting - CTKeytone: CT Keytone - Lock: Lock - Unlock: Unlock - FailedUnlock: Failed Unlock - KeypressedTink: Keypressed Tink - KeypressedTock: Keypressed Tock - Tock: Tock - BeepBeep: Beep Beep - RingerCharged: Ringer Charged - PhotoShutter: Photo Shutter - Shake: Shake - JBLBegin: JBL Begin - JBLConfirm: JBL Confirm - JBLCancel: JBL Cancel - BeginRecording: Begin Recording - EndRecording: End Recording - JBLAmbiguous: JBL Ambiguous - JBLNoMatch: JBL No Match - BeginVideoRecord: Begin Video Record - EndVideoRecord: End Video Record - VCInvitationAccepted: VC Invitation Accepted - VCRinging: VC Ringing - VCEnded: VC Ended - VCCallWaiting: VC Call Waiting - VCCallUpgrade: VC Call Upgrade - TouchTone1: Touch Tone 1 - TouchTone2: Touch Tone 2 - TouchTone3: Touch Tone 3 - TouchTone4: Touch Tone 4 - TouchTone5: Touch Tone 5 - TouchTone6: Touch Tone 6 - TouchTone7: Touch Tone 7 - TouchTone8: Touch Tone 8 - TouchTone9: Touch Tone 9 - TouchTone10: Touch Tone 10 - TouchToneStar: Touch Tone Star - TouchTonePound: Touch Tone Pound - HeadsetStartCall: Headset Start Call - HeadsetRedial: Headset Redial - HeadsetAnswerCall: Headset Answer Call - HeadsetEndCall: Headset End Call - HeadsetCallWaitingActions: Headset Call Waiting Actions - HeadsetTransitionEnd: Headset Transition End - Voicemail: Voicemail - ReceivedMessage: Received Message - NewMail2: New Mail 2 - MailSent2: Mail Sent 2 - Alarm2: Alarm 2 - Lock2: Lock 2 - Tock2: Tock 2 - SMSReceived1_2: SMS Received 1_2 - SMSReceived2_2: SMS Received 2_2 - SMSReceived3_2: SMS Received 3_2 - SMSReceived4_2: SMS Received 4_2 - SMSReceivedVibrate: SMS Received Vibrate - SMSReceived1_3: SMS Received 1_3 - SMSReceived5_3: SMS Received 5_3 - SMSReceived6_3: SMS Received 6_3 - Voicemail2: Voicemail 2 - Anticipate2: Anticipate 2 - Bloom2: Bloom 2 - Calypso2: Calypso 2 - ChooChoo2: Choo Choo 2 - Descent2: Descent 2 - Fanfare2: Fanfare 2 - Ladder2: Ladder 2 - Minuet2: Minuet 2 - NewsFlash2: News Flash 2 - Noir2: Noir 2 - SherwoodForest2: Sherwood Forest 2 - Spell2: Spell 2 - Suspence2: Suspence 2 - Telegraph2: Telegraph 2 - Tiptoes2: Tiptoes 2 - Typewriters2: Typewriters 2 - Update2: Update 2 - RingerVibeChanged: Ringer Vibe Changed - SilentVibeChanged: Silent Vibe Changed - Vibrate: Vibrate */ public enum AudioID : Int { case NewMail = 1000 case MailSent = 1001 case VoiceMail = 1002 case RecivedMessage = 1003 case SentMessage = 1004 case Alarm = 1005 case LowPower = 1006 case SMSReceived1 = 1007 case SMSReceived2 = 1008 case SMSReceived3 = 1009 case SMSReceived4 = 1010 case SMSReceived5 = 1013 case SMSReceived6 = 1014 case TweetSent = 1016 case Anticipate = 1020 case Bloom = 1021 case Calypso = 1022 case ChooChoo = 1023 case Descent = 1024 case Fanfare = 1025 case Ladder = 1026 case Minuet = 1027 case NewsFlash = 1028 case Noir = 1029 case SherwoodForest = 1030 case Spell = 1031 case Suspence = 1032 case Telegraph = 1033 case Tiptoes = 1034 case Typewriters = 1035 case Update = 1036 case USSDAlert = 1050 case SIMToolkitCallDropped = 1051 case SIMToolkitGeneralBeep = 1052 case SIMToolkitNegativeACK = 1053 case SIMToolkitPositiveACK = 1054 case SIMToolkitSMS = 1055 case Tink = 1057 case CTBusy = 1070 case CTCongestion = 1071 case CTPathACK = 1072 case CTError = 1073 case CTCallWaiting = 1074 case CTKeytone = 1075 case Lock = 1100 case Unlock = 1101 case FailedUnlock = 1102 case KeypressedTink = 1103 case KeypressedTock = 1104 case Tock = 1105 case BeepBeep = 1106 case RingerCharged = 1107 case PhotoShutter = 1108 case Shake = 1109 case JBLBegin = 1110 case JBLConfirm = 1111 case JBLCancel = 1112 case BeginRecording = 1113 case EndRecording = 1114 case JBLAmbiguous = 1115 case JBLNoMatch = 1116 case BeginVideoRecord = 1117 case EndVideoRecord = 1118 case VCInvitationAccepted = 1150 case VCRinging = 1151 case VCEnded = 1152 case VCCallWaiting = 1153 case VCCallUpgrade = 1154 case TouchTone1 = 1200 case TouchTone2 = 1201 case TouchTone3 = 1202 case TouchTone4 = 1203 case TouchTone5 = 1204 case TouchTone6 = 1205 case TouchTone7 = 1206 case TouchTone8 = 1207 case TouchTone9 = 1208 case TouchTone10 = 1209 case TouchToneStar = 1210 case TouchTonePound = 1211 case HeadsetStartCall = 1254 case HeadsetRedial = 1255 case HeadsetAnswerCall = 1256 case HeadsetEndCall = 1257 case HeadsetCallWaitingActions = 1258 case HeadsetTransitionEnd = 1259 case Voicemail = 1300 case ReceivedMessage = 1301 case NewMail2 = 1302 case MailSent2 = 1303 case Alarm2 = 1304 case Lock2 = 1305 case Tock2 = 1306 case SMSReceived1_2 = 1307 case SMSReceived2_2 = 1308 case SMSReceived3_2 = 1309 case SMSReceived4_2 = 1310 case SMSReceivedVibrate = 1311 case SMSReceived1_3 = 1312 case SMSReceived5_3 = 1313 case SMSReceived6_3 = 1314 case Voicemail2 = 1315 case Anticipate2 = 1320 case Bloom2 = 1321 case Calypso2 = 1322 case ChooChoo2 = 1323 case Descent2 = 1324 case Fanfare2 = 1325 case Ladder2 = 1326 case Minuet2 = 1327 case NewsFlash2 = 1328 case Noir2 = 1329 case SherwoodForest2 = 1330 case Spell2 = 1331 case Suspence2 = 1332 case Telegraph2 = 1333 case Tiptoes2 = 1334 case Typewriters2 = 1335 case Update2 = 1336 case RingerVibeChanged = 1350 case SilentVibeChanged = 1351 case Vibrate = 4095 } // MARK: - Class functions - /** Play a system sound from the ID :param: audioID ID of system audio from the AudioID enum */ public static func playSystemSound(audioID: AudioID) { AudioServicesPlaySystemSound(SystemSoundID(audioID.rawValue)) } /** Play system sound vibrate */ public static func playSystemSoundVibrate() { AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) } /** Play custom sound with url :param: soundURL Sound URL :returns: Returns the SystemSoundID */ public static func playCustomSound(soundURL: NSURL) -> SystemSoundID { var soundID: SystemSoundID = 0 let error: OSStatus = AudioServicesCreateSystemSoundID(soundURL as CFURLRef, &soundID) if error != Int32(kAudioServicesNoError) { BFLog("Could not load \(soundURL)") } return soundID } /** Dispose custom sound :param: soundID SystemSoundID :returns: Returns true if has been disposed, otherwise false */ public static func disposeSound(soundID: SystemSoundID) -> Bool { let error: OSStatus = AudioServicesDisposeSystemSoundID(soundID) if error != Int32(kAudioServicesNoError) { BFLog("Error while disposing sound \(soundID)") return false } return true } }
2a513b5c5ce434c250a821049370c23e
35.355685
94
0.5498
false
false
false
false
toshiapp/toshi-ios-client
refs/heads/master
Toshi/Avatars/AvatarManager.swift
gpl-3.0
1
// Copyright (c) 2018 Token Browser, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import Foundation import Teapot import Haneke final class AvatarManager: NSObject { @objc static let shared = AvatarManager() private let cache = Shared.imageCache func refreshAvatar(at path: String) { cache.remove(key: path) } @objc func cleanCache() { cache.removeAll() } @objc func startDownloadContactsAvatars() { if let currentUserAvatarPath = Profile.current?.avatar { downloadAvatar(for: currentUserAvatarPath) } for path in SessionManager.shared.profilesManager.profilesAvatarPaths { downloadAvatar(for: path) } } private func baseURL(from url: URL) -> String? { if url.baseURL == nil { guard let scheme = url.scheme, let host = url.host else { return nil } return "\(scheme)://\(host)" } return url.baseURL?.absoluteString } func downloadAvatar(for key: String, completion: ((UIImage?, String?) -> Void)? = nil) { if key.hasAddressPrefix { cache.fetch(key: key).onSuccess { image in completion?(image, key) }.onFailure({ _ in IDAPIClient.shared.findContact(name: key) { [weak self] profile, _ in guard let avatarPath = profile?.avatar else { completion?(nil, key) return } UserDefaults.standard.set(avatarPath, forKey: key) self?.downloadAvatar(path: avatarPath, completion: completion) } }) } else { cache.fetch(key: key).onSuccess { image in completion?(image, key) return }.onFailure { [weak self] _ in guard let strongSelf = self else { return } strongSelf.downloadAvatar(path: key) } } } private func downloadAvatar(path: String, completion: ((UIImage?, String?) -> Void)? = nil) { cache.fetch(key: path).onSuccess { image in completion?(image, path) }.onFailure({ _ in guard let url = URL(string: path) else { DispatchQueue.main.async { completion?(nil, path) } return } URLSession.shared.dataTask(with: url, completionHandler: { [weak self] data, _, _ in guard let strongSelf = self else { return } guard let retrievedData = data else { return } guard let image = UIImage(data: retrievedData) else { return } strongSelf.cache.set(value: image, key: path) DispatchQueue.main.async { completion?(image, path) } }).resume() }) } /// Downloads or finds avatar for given key. /// /// - Parameters: /// - key: token_id/address or resource url path. /// - completion: The completion closure to fire when the request completes or image is found in cache. /// - image: Found in cache or fetched image. /// - path: Path for found in cache or fetched image. func avatar(for key: String, completion: @escaping ((UIImage?, String?) -> Void)) { if key.hasAddressPrefix { if let avatarPath = UserDefaults.standard.object(forKey: key) as? String { _avatar(for: avatarPath, completion: completion) } else { downloadAvatar(for: key, completion: completion) } } _avatar(for: key, completion: completion) } /// Downloads or finds avatar for the resource url path. /// /// - Parameters: /// - path: An resource url path. /// - completion: The completion closure to fire when the request completes or image is found in cache. /// - image: Found in cache or fetched image. /// - path: Path for found in cache or fetched image. private func _avatar(for path: String, completion: @escaping ((UIImage?, String?) -> Void)) { cache.fetch(key: path).onSuccess { image in completion(image, path) }.onFailure { [weak self] _ in guard let strongSelf = self else { return } strongSelf.downloadAvatar(path: path, completion: completion) } } /// Finds avatar for the given key. /// /// - Parameters: /// - key: token_id/address or resource url path. /// - Returns: /// - found image or nil if not present @objc func cachedAvatar(for key: String) -> UIImage? { guard !key.hasAddressPrefix else { guard let avatarPath = UserDefaults.standard.object(forKey: key) as? String else { return nil } return cachedAvatar(for: avatarPath) } var image: UIImage? cache.fetch(key: key).onSuccess { cachedImage in image = cachedImage } return image } }
0f85ff76b7bbf45ba53d7624c9f6acf6
33.529412
109
0.561499
false
false
false
false