repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
codercd/SwiftDemo | 001_SnapKitDemo/SnapKitDemo/ViewController.swift | 1 | 2054 | //
// ViewController.swift
// SnapKitDemo
//
// Created by LiChendi on 16/2/16.
// Copyright © 2016年 LiChendi. All rights reserved.
//
import UIKit
import SnapKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let tableView = UITableView()
let item = ["Label", "Image", "label", "label", "label", "", "label", "label"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self;
tableView.dataSource = self;
self.view.addSubview(tableView)
tableView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(self.view).offset(20)
make.left.right.bottom.equalTo(self.view)
}
self.tableView .registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return item.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")
cell!.textLabel?.text = item[indexPath.row]
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.row {
case 0:
let labelDemo = LabelViewController()
labelDemo.navigationItem.title = item[indexPath.row]
self.navigationController?.pushViewController(labelDemo, animated: true)
break
case 1:
let imageDemo = ImageViewController()
imageDemo.navigationItem.title = item[indexPath.row]
self.navigationController?.pushViewController(imageDemo, animated: true)
break
default:
break
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 46bf44c46d0f3e7d47dc003dd03205ac | 29.161765 | 109 | 0.638713 | 5.153266 | false | false | false | false |
kzaher/RxSwift | RxCocoa/iOS/UITableView+Rx.swift | 5 | 16882 | //
// UITableView+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 4/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import RxSwift
import UIKit
// Items
extension Reactive where Base: UITableView {
/**
Binds sequences of elements to table view rows.
- parameter source: Observable sequence of items.
- parameter cellFactory: Transform between sequence elements and view cells.
- returns: Disposable object that can be used to unbind.
Example:
let items = Observable.just([
"First Item",
"Second Item",
"Third Item"
])
items
.bind(to: tableView.rx.items) { (tableView, row, element) in
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = "\(element) @ row \(row)"
return cell
}
.disposed(by: disposeBag)
*/
public func items<Sequence: Swift.Sequence, Source: ObservableType>
(_ source: Source)
-> (_ cellFactory: @escaping (UITableView, Int, Sequence.Element) -> UITableViewCell)
-> Disposable
where Source.Element == Sequence {
return { cellFactory in
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<Sequence>(cellFactory: cellFactory)
return self.items(dataSource: dataSource)(source)
}
}
/**
Binds sequences of elements to table view rows.
- parameter cellIdentifier: Identifier used to dequeue cells.
- parameter source: Observable sequence of items.
- parameter configureCell: Transform between sequence elements and view cells.
- parameter cellType: Type of table view cell.
- returns: Disposable object that can be used to unbind.
Example:
let items = Observable.just([
"First Item",
"Second Item",
"Third Item"
])
items
.bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, element, cell) in
cell.textLabel?.text = "\(element) @ row \(row)"
}
.disposed(by: disposeBag)
*/
public func items<Sequence: Swift.Sequence, Cell: UITableViewCell, Source: ObservableType>
(cellIdentifier: String, cellType: Cell.Type = Cell.self)
-> (_ source: Source)
-> (_ configureCell: @escaping (Int, Sequence.Element, Cell) -> Void)
-> Disposable
where Source.Element == Sequence {
return { source in
return { configureCell in
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<Sequence> { tv, i, item in
let indexPath = IndexPath(item: i, section: 0)
let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! Cell
configureCell(i, item, cell)
return cell
}
return self.items(dataSource: dataSource)(source)
}
}
}
/**
Binds sequences of elements to table view rows using a custom reactive data used to perform the transformation.
This method will retain the data source for as long as the subscription isn't disposed (result `Disposable`
being disposed).
In case `source` observable sequence terminates successfully, the data source will present latest element
until the subscription isn't disposed.
- parameter dataSource: Data source used to transform elements to view cells.
- parameter source: Observable sequence of items.
- returns: Disposable object that can be used to unbind.
*/
public func items<
DataSource: RxTableViewDataSourceType & UITableViewDataSource,
Source: ObservableType>
(dataSource: DataSource)
-> (_ source: Source)
-> Disposable
where DataSource.Element == Source.Element {
return { source in
// This is called for sideeffects only, and to make sure delegate proxy is in place when
// data source is being bound.
// This is needed because theoretically the data source subscription itself might
// call `self.rx.delegate`. If that happens, it might cause weird side effects since
// setting data source will set delegate, and UITableView might get into a weird state.
// Therefore it's better to set delegate proxy first, just to be sure.
_ = self.delegate
// Strong reference is needed because data source is in use until result subscription is disposed
return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource as UITableViewDataSource, retainDataSource: true) { [weak tableView = self.base] (_: RxTableViewDataSourceProxy, event) -> Void in
guard let tableView = tableView else {
return
}
dataSource.tableView(tableView, observedEvent: event)
}
}
}
}
extension Reactive where Base: UITableView {
/**
Reactive wrapper for `dataSource`.
For more information take a look at `DelegateProxyType` protocol documentation.
*/
public var dataSource: DelegateProxy<UITableView, UITableViewDataSource> {
RxTableViewDataSourceProxy.proxy(for: base)
}
/**
Installs data source as forwarding delegate on `rx.dataSource`.
Data source won't be retained.
It enables using normal delegate mechanism with reactive delegate mechanism.
- parameter dataSource: Data source object.
- returns: Disposable object that can be used to unbind the data source.
*/
public func setDataSource(_ dataSource: UITableViewDataSource)
-> Disposable {
RxTableViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base)
}
// events
/**
Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`.
*/
public var itemSelected: ControlEvent<IndexPath> {
let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didSelectRowAt:)))
.map { a in
return try castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`.
*/
public var itemDeselected: ControlEvent<IndexPath> {
let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didDeselectRowAt:)))
.map { a in
return try castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didHighlightRowAt:`.
*/
public var itemHighlighted: ControlEvent<IndexPath> {
let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didHighlightRowAt:)))
.map { a in
return try castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didUnhighlightRowAt:`.
*/
public var itemUnhighlighted: ControlEvent<IndexPath> {
let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didUnhighlightRowAt:)))
.map { a in
return try castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:accessoryButtonTappedForRowWithIndexPath:`.
*/
public var itemAccessoryButtonTapped: ControlEvent<IndexPath> {
let source: Observable<IndexPath> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:accessoryButtonTappedForRowWith:)))
.map { a in
return try castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
*/
public var itemInserted: ControlEvent<IndexPath> {
let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:)))
.filter { a in
return UITableViewCell.EditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .insert
}
.map { a in
return (try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
*/
public var itemDeleted: ControlEvent<IndexPath> {
let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:)))
.filter { a in
return UITableViewCell.EditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .delete
}
.map { a in
return try castOrThrow(IndexPath.self, a[2])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:moveRowAtIndexPath:toIndexPath:`.
*/
public var itemMoved: ControlEvent<ItemMovedEvent> {
let source: Observable<ItemMovedEvent> = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:moveRowAt:to:)))
.map { a in
return (try castOrThrow(IndexPath.self, a[1]), try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:willDisplayCell:forRowAtIndexPath:`.
*/
public var willDisplayCell: ControlEvent<WillDisplayCellEvent> {
let source: Observable<WillDisplayCellEvent> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:willDisplay:forRowAt:)))
.map { a in
return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didEndDisplayingCell:forRowAtIndexPath:`.
*/
public var didEndDisplayingCell: ControlEvent<DidEndDisplayingCellEvent> {
let source: Observable<DidEndDisplayingCellEvent> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didEndDisplaying:forRowAt:)))
.map { a in
return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`.
It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence,
or any other data source conforming to `SectionedViewDataSourceType` protocol.
```
tableView.rx.modelSelected(MyModel.self)
.map { ...
```
*/
public func modelSelected<T>(_ modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = self.itemSelected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<T> in
guard let view = view else {
return Observable.empty()
}
return Observable.just(try view.rx.model(at: indexPath))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`.
It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence,
or any other data source conforming to `SectionedViewDataSourceType` protocol.
```
tableView.rx.modelDeselected(MyModel.self)
.map { ...
```
*/
public func modelDeselected<T>(_ modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = self.itemDeselected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<T> in
guard let view = view else {
return Observable.empty()
}
return Observable.just(try view.rx.model(at: indexPath))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence,
or any other data source conforming to `SectionedViewDataSourceType` protocol.
```
tableView.rx.modelDeleted(MyModel.self)
.map { ...
```
*/
public func modelDeleted<T>(_ modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = self.itemDeleted.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<T> in
guard let view = view else {
return Observable.empty()
}
return Observable.just(try view.rx.model(at: indexPath))
}
return ControlEvent(events: source)
}
/**
Synchronous helper method for retrieving a model at indexPath through a reactive data source.
*/
public func model<T>(at indexPath: IndexPath) throws -> T {
let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.items*` methods was used.")
let element = try dataSource.model(at: indexPath)
return castOrFatalError(element)
}
}
@available(iOS 10.0, tvOS 10.0, *)
extension Reactive where Base: UITableView {
/// Reactive wrapper for `prefetchDataSource`.
///
/// For more information take a look at `DelegateProxyType` protocol documentation.
public var prefetchDataSource: DelegateProxy<UITableView, UITableViewDataSourcePrefetching> {
RxTableViewDataSourcePrefetchingProxy.proxy(for: base)
}
/**
Installs prefetch data source as forwarding delegate on `rx.prefetchDataSource`.
Prefetch data source won't be retained.
It enables using normal delegate mechanism with reactive delegate mechanism.
- parameter prefetchDataSource: Prefetch data source object.
- returns: Disposable object that can be used to unbind the data source.
*/
public func setPrefetchDataSource(_ prefetchDataSource: UITableViewDataSourcePrefetching)
-> Disposable {
return RxTableViewDataSourcePrefetchingProxy.installForwardDelegate(prefetchDataSource, retainDelegate: false, onProxyForObject: self.base)
}
/// Reactive wrapper for `prefetchDataSource` message `tableView(_:prefetchRowsAt:)`.
public var prefetchRows: ControlEvent<[IndexPath]> {
let source = RxTableViewDataSourcePrefetchingProxy.proxy(for: base).prefetchRowsPublishSubject
return ControlEvent(events: source)
}
/// Reactive wrapper for `prefetchDataSource` message `tableView(_:cancelPrefetchingForRowsAt:)`.
public var cancelPrefetchingForRows: ControlEvent<[IndexPath]> {
let source = prefetchDataSource.methodInvoked(#selector(UITableViewDataSourcePrefetching.tableView(_:cancelPrefetchingForRowsAt:)))
.map { a in
return try castOrThrow(Array<IndexPath>.self, a[1])
}
return ControlEvent(events: source)
}
}
#endif
#if os(tvOS)
extension Reactive where Base: UITableView {
/**
Reactive wrapper for `delegate` message `tableView:didUpdateFocusInContext:withAnimationCoordinator:`.
*/
public var didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UITableViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> {
let source = delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didUpdateFocusIn:with:)))
.map { a -> (context: UITableViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in
let context = try castOrThrow(UITableViewFocusUpdateContext.self, a[1])
let animationCoordinator = try castOrThrow(UIFocusAnimationCoordinator.self, a[2])
return (context: context, animationCoordinator: animationCoordinator)
}
return ControlEvent(events: source)
}
}
#endif
| mit | 299618795af2fb5757850d8f81240baa | 38.34965 | 225 | 0.647651 | 5.384689 | false | false | false | false |
orkhanalizade/xmpp-messenger-ios | Example/xmpp-messenger-ios/ChatViewController.swift | 1 | 13072 | //
// ChatViewController.swift
// OneChat
//
// Created by Paul on 20/02/2015.
// Copyright (c) 2015 ProcessOne. All rights reserved.
//
// Bugs fixed by Orkhan Alizade
import UIKit
import xmpp_messenger_ios
import JSQMessagesViewController
import XMPPFramework
class ChatViewController: JSQMessagesViewController, OneMessageDelegate, ContactPickerDelegate {
let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
var messages = NSMutableArray()
var recipient: XMPPUserCoreDataStorageObject?
var firstTime = true
var userDetails = UIView?()
// Mark: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
OneMessage.sharedInstance.delegate = self
if OneChat.sharedInstance.isConnected() {
self.senderId = OneChat.sharedInstance.xmppStream?.myJID.bare()
self.senderDisplayName = OneChat.sharedInstance.xmppStream?.myJID.bare()
}
self.collectionView!.collectionViewLayout.springinessEnabled = false
self.inputToolbar!.contentView!.leftBarButtonItem!.hidden = true
}
override func viewWillAppear(animated: Bool) {
if let recipient = recipient {
self.navigationItem.rightBarButtonItems = []
navigationItem.title = recipient.displayName
// Mark: Adding LastActivity functionality to NavigationBar
OneLastActivity.sendLastActivityQueryToJID((recipient.jidStr), sender: OneChat.sharedInstance.xmppLastActivity) { (response, forJID, error) -> Void in
let lastActivityResponse = OneLastActivity.sharedInstance.getLastActivityFrom((response?.lastActivitySeconds())!)
self.userDetails = OneLastActivity.sharedInstance.addLastActivityLabelToNavigationBar(lastActivityResponse, displayName: recipient.displayName)
self.navigationController!.view.addSubview(self.userDetails!)
if (self.userDetails != nil) {
self.navigationItem.title = ""
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.messages = OneMessage.sharedInstance.loadArchivedMessagesFrom(jid: recipient.jidStr)
self.finishReceivingMessageAnimated(true)
})
} else {
if userDetails == nil {
navigationItem.title = "New message"
}
self.inputToolbar!.contentView!.rightBarButtonItem!.enabled = false
self.navigationItem.setRightBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addRecipient"), animated: true)
if firstTime {
firstTime = false
addRecipient()
}
}
// Mark: Checking the internet connection
if !OneChat.sharedInstance.isConnectionAvailable() {
let alertController = UIAlertController(title: "Error", message: "Please check the internet connection.", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dissmiss", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
//do something
}))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.scrollToBottomAnimated(true)
}
override func viewWillDisappear(animated: Bool) {
userDetails?.removeFromSuperview()
}
// Mark: Private methods
func addRecipient() {
let navController = self.storyboard?.instantiateViewControllerWithIdentifier("contactListNav") as? UINavigationController
let contactController: ContactListTableViewController? = navController?.viewControllers[0] as? ContactListTableViewController
contactController?.delegate = self
self.presentViewController(navController!, animated: true, completion: nil)
}
func didSelectContact(recipient: XMPPUserCoreDataStorageObject) {
self.recipient = recipient
if userDetails == nil {
navigationItem.title = recipient.displayName
}
}
// Mark: JSQMessagesViewController method overrides
var isComposing = false
var timer: NSTimer?
override func textViewDidChange(textView: UITextView) {
super.textViewDidChange(textView)
if textView.text.characters.count == 0 {
if isComposing {
hideTypingIndicator()
}
} else {
timer?.invalidate()
if !isComposing {
self.isComposing = true
OneMessage.sendIsComposingMessage((recipient?.jidStr)!, completionHandler: { (stream, message) -> Void in
self.timer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: "hideTypingIndicator", userInfo: nil, repeats: false)
})
} else {
self.timer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: "hideTypingIndicator", userInfo: nil, repeats: false)
}
}
}
func hideTypingIndicator() {
if let recipient = recipient {
self.isComposing = false
OneMessage.sendIsComposingMessage((recipient.jidStr)!, completionHandler: { (stream, message) -> Void in
})
}
}
override func didPressSendButton(button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: NSDate!) {
let fullMessage = JSQMessage(senderId: OneChat.sharedInstance.xmppStream?.myJID.bare(), senderDisplayName: OneChat.sharedInstance.xmppStream?.myJID.bare(), date: NSDate(), text: text)
messages.addObject(fullMessage)
if let recipient = recipient {
OneMessage.sendMessage(text, to: recipient.jidStr, completionHandler: { (stream, message) -> Void in
JSQSystemSoundPlayer.jsq_playMessageSentSound()
self.finishSendingMessageAnimated(true)
})
if !OneChats.knownUserForJid(jidStr: recipient.jidStr) {
OneChats.addUserToChatList(jidStr: recipient.jidStr)
} else {
messages = OneMessage.sharedInstance.loadArchivedMessagesFrom(jid: recipient.jidStr)
finishReceivingMessageAnimated(true)
}
}
}
// Mark: JSQMessages CollectionView DataSource
override func collectionView(collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! {
let message: JSQMessage = self.messages[indexPath.item] as! JSQMessage
return message
}
override func collectionView(collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource! {
let message: JSQMessage = self.messages[indexPath.item] as! JSQMessage
let bubbleFactory = JSQMessagesBubbleImageFactory()
let outgoingBubbleImageData = bubbleFactory.outgoingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleLightGrayColor())
let incomingBubbleImageData = bubbleFactory.incomingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleGreenColor())
if message.senderId == self.senderId {
return outgoingBubbleImageData
}
return incomingBubbleImageData
}
override func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! {
let message: JSQMessage = self.messages[indexPath.item] as! JSQMessage
if message.senderId == self.senderId {
if let photoData = OneChat.sharedInstance.xmppvCardAvatarModule?.photoDataForJID(OneChat.sharedInstance.xmppStream?.myJID) {
let senderAvatar = JSQMessagesAvatarImageFactory.avatarImageWithImage(UIImage(data: photoData), diameter: 30)
return senderAvatar
} else {
let senderAvatar = JSQMessagesAvatarImageFactory.avatarImageWithUserInitials("SR", backgroundColor: UIColor(white: 0.85, alpha: 1.0), textColor: UIColor(white: 0.60, alpha: 1.0), font: UIFont(name: "Helvetica Neue", size: 14.0), diameter: 30)
return senderAvatar
}
} else {
if let photoData = OneChat.sharedInstance.xmppvCardAvatarModule?.photoDataForJID(recipient!.jid!) {
let recipientAvatar = JSQMessagesAvatarImageFactory.avatarImageWithImage(UIImage(data: photoData), diameter: 30)
return recipientAvatar
} else {
let recipientAvatar = JSQMessagesAvatarImageFactory.avatarImageWithUserInitials("SR", backgroundColor: UIColor(white: 0.85, alpha: 1.0), textColor: UIColor(white: 0.60, alpha: 1.0), font: UIFont(name: "Helvetica Neue", size: 14.0)!, diameter: 30)
return recipientAvatar
}
}
}
override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
if indexPath.item % 3 == 0 {
let message: JSQMessage = self.messages[indexPath.item] as! JSQMessage
return JSQMessagesTimestampFormatter.sharedFormatter().attributedTimestampForDate(message.date)
}
return nil;
}
override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
let message: JSQMessage = self.messages[indexPath.item] as! JSQMessage
if message.senderId == self.senderId {
return nil
}
if indexPath.item - 1 > 0 {
let previousMessage: JSQMessage = self.messages[indexPath.item - 1] as! JSQMessage
if previousMessage.senderId == message.senderId {
return nil
}
}
return nil
}
override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
return nil
}
// Mark: UICollectionView DataSource
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.messages.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: JSQMessagesCollectionViewCell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell
let msg: JSQMessage = self.messages[indexPath.item] as! JSQMessage
if !msg.isMediaMessage {
if msg.senderId == self.senderId {
cell.textView!.textColor = UIColor.blackColor()
cell.textView!.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.blackColor(), NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
} else {
cell.textView!.textColor = UIColor.whiteColor()
cell.textView!.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor(), NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
}
}
return cell
}
// Mark: JSQMessages collection view flow layout delegate
override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
if indexPath.item % 3 == 0 {
return kJSQMessagesCollectionViewCellLabelHeightDefault
}
return 0.0
}
override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
let currentMessage: JSQMessage = self.messages[indexPath.item] as! JSQMessage
if currentMessage.senderId == self.senderId {
return 0.0
}
if indexPath.item - 1 > 0 {
let previousMessage: JSQMessage = self.messages[indexPath.item - 1] as! JSQMessage
if previousMessage.senderId == currentMessage.senderId {
return 0.0
}
}
return kJSQMessagesCollectionViewCellLabelHeightDefault
}
override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
return 0.0
}
// Mark: Chat message Delegates
func oneStream(sender: XMPPStream, didReceiveMessage message: XMPPMessage, from user: XMPPUserCoreDataStorageObject) {
if message.isChatMessageWithBody() {
//let displayName = user.displayName
JSQSystemSoundPlayer.jsq_playMessageReceivedSound()
if let msg: String = message.elementForName("body")?.stringValue() {
if let from: String = message.attributeForName("from")?.stringValue() {
let message = JSQMessage(senderId: from, senderDisplayName: from, date: NSDate(), text: msg)
messages.addObject(message)
self.finishReceivingMessageAnimated(true)
}
}
}
}
func oneStream(sender: XMPPStream, userIsComposing user: XMPPUserCoreDataStorageObject) {
self.showTypingIndicator = !self.showTypingIndicator
self.scrollToBottomAnimated(true)
}
// Mark: Memory Management
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 0d119baa2821ae69d705a98957ef28f3 | 39.345679 | 250 | 0.735695 | 4.901387 | false | false | false | false |
HabitRPG/habitrpg-ios | Habitica API Client/Habitica API Client/HabiticaServerConfig.swift | 1 | 1311 | //
// HRPGServerConfig.swift
// Habitica
//
// Created by Elliot Schrock on 9/20/17.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import UIKit
public class HabiticaServerConfig {
public static let production = ServerConfiguration(scheme: "https", host: "habitica.com", apiRoute: "api/v4")
public static let staging = ServerConfiguration(scheme: "https", host: "habitrpg-staging.herokuapp.com", apiRoute: "api/v4")
public static let beta = ServerConfiguration(scheme: "https", host: "habitrpg-beta.herokuapp.com", apiRoute: "api/v4")
public static let gamma = ServerConfiguration(scheme: "https", host: "habitrpg-gamma.herokuapp.com", apiRoute: "api/v4")
public static let delta = ServerConfiguration(scheme: "https", host: "habitrpg-delta.herokuapp.com", apiRoute: "api/v4")
public static let localhost = ServerConfiguration(scheme: "http", host: "192.168.178.52:3000", apiRoute: "api/v4")
public static let stub = ServerConfiguration(shouldStub: true, scheme: "https", host: "habitica.com", apiRoute: "api/v4")
public static var current = production
public static var aws = ServerConfiguration(scheme: "https", host: "s3.amazonaws.com", apiRoute: "habitica-assets/mobileApp/endpoint")
public static var etags: [String: String] = [:]
}
| gpl-3.0 | fa04b5b44f487d79145af1b9952b711a | 51.4 | 138 | 0.716794 | 3.864307 | false | true | false | false |
BridgeTheGap/KRClient | KRClient/Classes/KRClient.swift | 1 | 17777 | //
// KRClient.swift
// Pods
//
// Created by Joshua Park on 9/8/16.
//
//
import UIKit
public enum KRClientSuccessHandler {
case data((_ data: Data, _ response: URLResponse) -> Void)
case json((_ json: [String: Any], _ response: URLResponse) -> Void)
case string((_ string: String, _ response: URLResponse) -> Void)
case response((_ response: URLResponse) -> Void)
case none
}
public enum KRClientFailureHandler {
case failure((_ error: NSError, _ response: URLResponse?) -> Void)
case response((_ response: URLResponse?) -> Void)
case none
}
let kDEFAULT_API_ID = "com.KRClient.defaultID"
fileprivate class GroupRequestHandler {
let mode: GroupRequestMode
var position: Position
var success: (() -> Void)!
var failure: (() -> Void)!
var alternative: Request?
var completion: ((Bool) -> Void)?
init(mode: GroupRequestMode, position: Position, completion: ((Bool) -> Void)?) {
(self.mode, self.position, self.completion) = (mode, position, completion)
}
}
public enum GroupRequestMode {
case abort
case ignore
case recover
}
open class KRClient: NSObject {
open static let shared = KRClient()
open let session: URLSession
open weak var delegate: KRClientDelegate?
open private(set) var hosts = [String: String]()
open private(set) var headerFields = [String: [String: String]] ()
open var timeoutInterval: Double = 20.0
open private(set) var templates = [String: RequestTemplate]()
open var indicatorView: UIView?
// MARK: - Initializer
public init(sessionConfig: URLSessionConfiguration? = nil, delegateQueue: OperationQueue? = nil) {
let sessionConfig = sessionConfig ?? URLSessionConfiguration.default
let delegateQueue = delegateQueue ?? {
let queue = OperationQueue()
queue.qualityOfService = .userInitiated
return queue
}()
session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: delegateQueue)
}
// MARK: - API
open func set(defaultHost: String) {
var strHost = defaultHost
if strHost[-1][nil] == "/" { strHost = strHost[nil][-1] }
hosts[kDEFAULT_API_ID] = strHost
}
open func set(defaultHeaderFields: [String: String]) {
self.headerFields[kDEFAULT_API_ID] = defaultHeaderFields
}
open func set(identifier: String, host hostString: String) {
var strHost = hostString
if strHost[-1][nil] == "/" { strHost = strHost[nil][-1] }
hosts[identifier] = strHost
}
open func set(identifier: String, headerFields: [String: String]) {
self.headerFields[identifier] = headerFields
}
open func set(defaultTemplate: RequestTemplate) {
self.templates[kDEFAULT_API_ID] = defaultTemplate
}
open func set(identifier: String, template: RequestTemplate) {
self.templates[identifier] = template
}
private func getQueryString(from parameters: [String: Any]) throws -> String {
let queryString = "?" + parameters.map({ "\($0)=\($1)" }).joined(separator: "&")
guard let str = queryString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { fatalError() }
return str
}
// MARK: - URL Request
open func getURLRequest(from baseRequest: URLRequest, parameters: [String: Any]) throws -> URLRequest {
guard let urlString = baseRequest.url?.absoluteString else {
let message = "<KRClient> Attempt to make a `URLRequest` from an empty string."
throw KRClientError.invalidOperation(description: message, location: (file: #file, line: #line))
}
switch baseRequest.httpMethod ?? "GET" {
case "POST":
var request = baseRequest
request.httpBody = try JSONSerialization.data(withJSONObject: parameters)
return request
default:
let strQuery = try getQueryString(from: parameters)
guard let url = URL(string: urlString + strQuery) else {
throw KRClientError.stringToURLConversionFailure(string: urlString + strQuery)
}
return URLRequest(url: url)
}
}
open func getURLRequest(withID identifier: String = "com.KRClient.defaultID", for api: API, parameters: [String: Any]? = nil) throws -> URLRequest {
guard let strHost = hosts[identifier] else {
let message = identifier == kDEFAULT_API_ID ?
"<KRClient> There is no default host set." :
"<KRClient> There is no host name set for the identifier: \(identifier)"
throw KRClientError.invalidOperation(description: message, location: (file: #file, line: #line))
}
let strProtocol = api.SSL ? "https://" : "http://"
let strURL = strProtocol + strHost + api.path
var request = try getURLRequest(method: api.method, urlString: strURL, parameters: parameters)
if let headerFields = self.headerFields[identifier] {
for (key, value) in headerFields {
request.addValue(value, forHTTPHeaderField: key)
}
}
return request
}
open func getURLRequest(method: HTTPMethod, urlString: String, parameters: [String: Any]? = nil) throws -> URLRequest {
var request: URLRequest = try {
if let params = parameters {
switch method {
case .GET, .HEAD:
let strQuery = try getQueryString(from: params)
guard let url = URL(string: urlString + strQuery) else {
throw KRClientError.stringToURLConversionFailure(string: urlString + strQuery)
}
return URLRequest(url: url)
case .POST, .PUT:
guard let url = URL(string: urlString) else {
throw KRClientError.stringToURLConversionFailure(string: urlString)
}
var request = URLRequest(url: url)
request.httpBody = try JSONSerialization.data(withJSONObject: params)
return request
// TODO: Implementation
}
} else {
guard let url = URL(string: urlString) else {
throw KRClientError.stringToURLConversionFailure(string: urlString)
}
return URLRequest(url: url)
}
}()
request.httpMethod = method.rawValue
request.timeoutInterval = timeoutInterval
return request
}
// MARK: - Dispatch
open func make(httpRequest method: HTTPMethod, urlString: String, parameters: [String: Any]? = nil, successHandler: KRClientSuccessHandler, failureHandler: KRClientFailureHandler) {
do {
let request = try getURLRequest(method: method, urlString: urlString)
make(httpRequest: request, successHandler: successHandler, failureHandler: failureHandler)
} catch {
if let error = error as? KRClientError {
print(error.nsError)
} else {
print(error)
}
}
}
open func make(httpRequestFor apiIdentifier: String, requestAPI: API, parameters: [String: Any]? = nil, successHandler: KRClientSuccessHandler, failureHandler: KRClientFailureHandler) {
do {
let request = try getURLRequest(withID: apiIdentifier, for: requestAPI)
make(httpRequest: request, successHandler: successHandler, failureHandler: failureHandler)
} catch {
if let error = error as? KRClientError {
print(error.nsError)
} else {
print(error)
}
}
}
open func make(httpRequest urlRequest: URLRequest, successHandler: KRClientSuccessHandler, failureHandler: KRClientFailureHandler) {
var request = Request(urlRequest: urlRequest)
(request.successHandler, request.failureHandler) = (successHandler, failureHandler)
make(httpRequest: request)
}
open func make(httpRequest request: Request) {
session.delegateQueue.addOperation {
self.make(httpRequest: request, groupRequestHandler: nil)
}
}
private func make(httpRequest request: Request, groupRequestHandler: GroupRequestHandler?) {
var request = request
if request.shouldSetParameters {
let urlRequest = try! getURLRequest(from: request.urlRequest,
parameters: request.parameters!())
request.urlRequest = urlRequest
}
let delegateQueue = request.queue ?? DispatchQueue.main
weak var delegate = self.delegate
let counter = groupRequestHandler?.position
delegateQueue.sync { delegate?.client(self, willMake: request, at: counter) }
self.session.dataTask(with: request.urlRequest, completionHandler: { (optData, optResponse, optError) in
delegateQueue.async {
var alternative: Request?
do {
guard let data = optData, optError == nil else { throw optError! }
guard let response = optResponse as? HTTPURLResponse else {
throw NSError(domain: KRClientError.Domain.response,
code: KRClientError.ErrorCode.unknown,
userInfo: [KRClientError.UserInfoKey.urlResponse: optResponse as Any])
}
if let validation = request.responseTest?(data, response) {
guard validation.error == nil, validation.alternative == nil else {
alternative = validation.alternative
throw validation.error ?? KRClientError.dataValidationFailure.nsError
}
}
delegate?.client(self, willFinish: request, at: counter, withSuccess: true)
switch request.successHandler ?? .none {
case .data(let handler):
handler(data, response)
case .json(let handler):
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
throw KRClientError.dataConversionFailure(type: [String: Any].self)
}
handler(json, response)
case .string(let handler):
let encoding: UInt = {
if let encodingName = response.textEncodingName {
let cfEncoding = CFStringConvertIANACharSetNameToEncoding(encodingName as CFString)
return CFStringConvertEncodingToNSStringEncoding(cfEncoding)
} else {
return String.Encoding.isoLatin1.rawValue
}
}()
guard let string = String(data: data, encoding: String.Encoding(rawValue: encoding)) else {
throw KRClientError.dataConversionFailure(type: String.self)
}
handler(string, optResponse!)
case .response(let handler):
handler(response)
case .none:
break
}
delegate?.client(self, didFinish: request, at: counter, withSuccess: true)
groupRequestHandler?.success()
} catch let error {
delegate?.client(self, willFinish: request, at: counter, withSuccess: false)
switch request.failureHandler ?? .none {
case .failure(let handler):
handler(error as NSError, optResponse)
case .response(let handler):
handler(optResponse)
case .none:
break
}
defer {
delegate?.client(self, didFinish: request, at: counter, withSuccess: false)
if let groupRequestHandler = groupRequestHandler {
groupRequestHandler.alternative = alternative
groupRequestHandler.failure()
} else if let alternative = alternative {
print("<KRClient> Attempting to recover from failure (\(alternative.urlRequest)).")
self.session.delegateQueue.addOperation {
self.make(httpRequest: alternative, groupRequestHandler: nil)
}
}
}
}
}
}).resume()
delegateQueue.sync { delegate?.client(self, didMake: request, at: counter) }
}
// MARK: - Grouped Requests
open func make(groupHTTPRequests groupRequest: RequestType..., mode: GroupRequestMode = .abort, completion: ((Bool) -> Void)? = nil) {
session.delegateQueue.addOperation {
self.dispatch(groupHTTPRequests: groupRequest, mode: mode, completion: completion)
}
}
private func dispatch(groupHTTPRequests groupRequest: [RequestType], mode: GroupRequestMode, completion: ((Bool) -> Void)?) {
let originalReq = groupRequest
var groupRequest = groupRequest
var abort = false
let queue = DispatchQueue.global(qos: .utility)
delegate?.client(self, willBegin: originalReq)
queue.async {
let sema = DispatchSemaphore(value: 0)
let count = groupRequest.reduce(0) { (i, e) -> Int in
if e is Request { return i + 1 }
else { return i + (e as! [Request]).count }
}
let counter = Position(index: 0, count: count)
let handler = GroupRequestHandler(mode: mode, position: counter, completion: completion)
var completionQueue: DispatchQueue?
reqIter: repeat {
let req = groupRequest.removeFirst()
if req is Request {
handler.success = { sema.signal() }
handler.failure = { abort = true; sema.signal() }
self.make(httpRequest: req as! Request, groupRequestHandler: handler)
completionQueue = (req as! Request).queue ?? DispatchQueue.main
handler.position.index += 1
} else {
let reqArr = req as! [Request]
let group = DispatchGroup()
handler.success = { group.leave() }
handler.failure = { abort = true; group.leave() }
for r in reqArr {
group.enter()
self.make(httpRequest: r, groupRequestHandler: handler)
handler.position.index += 1
}
completionQueue = reqArr.last!.queue ?? DispatchQueue.main
group.wait()
sema.signal()
}
sema.wait()
guard !abort else {
mode: switch mode {
case .abort:
print("<KRClient> Aborting group requests due to failure.")
break reqIter
case .ignore:
abort = false
continue reqIter
case .recover:
if let recover = handler.alternative {
print("<KRClient> Attempting to recover from failure (\(recover.urlRequest)).")
completionQueue = nil
self.dispatch(groupHTTPRequests: [recover as RequestType] + groupRequest, mode: mode, completion: completion)
} else {
print("<KRClient> Aborting group requests due to failure.")
}
break reqIter
}
}
} while groupRequest.count > 0
if let completionQueue = completionQueue {
completionQueue.sync { handler.completion?(!abort && groupRequest.isEmpty) }
self.session.delegateQueue.addOperation { self.delegate?.client(self, didFinish: originalReq) }
}
}
}
}
| mit | bae31c58d7078076e7b661d25bcf651a | 39.494305 | 189 | 0.526579 | 5.896186 | false | false | false | false |
sclark01/Swift_VIPER_Demo | VIPER_Demo/VIPER_DemoTests/ModulesTests/PersonDetailsTests/PersonDetailsWireFrameTests.swift | 1 | 1119 | import UIKit
import Quick
import Nimble
@testable import VIPER_Demo
class PersonDetailsWireFrameTests : QuickSpec {
override func spec() {
describe("present details view from viewcontroller") {
var wireFrame: TestablePersonDetailsWireFrame?
beforeEach {
wireFrame = TestablePersonDetailsWireFrame(personDetailsPresenter: PersonDetailsPresenterMock(), personDetailsInteractor: PersonDetailsInteractorMock())
}
it("push the correct viewcontroller") {
wireFrame?.presentDetailsViewFrom(viewController: UIViewController(), withId: 1)
expect(wireFrame?.pushedViewController).to(beAKindOf(PersonDetailsViewController.self))
}
it("set the correct person id on the view controller") {
let id = 2
wireFrame?.presentDetailsViewFrom(viewController: UIViewController(), withId: id)
let pushedVC = wireFrame?.pushedViewController as! PersonDetailsViewController
expect(pushedVC.personId) == id
}
}
}
}
| mit | 1e6824a9198158ea75631a5f8c0dc893 | 31.911765 | 168 | 0.654155 | 6.016129 | false | true | false | false |
KimpossibleG/billfold | BillFoldApp/BillFold/BillFold/PhotoViewController.swift | 1 | 4336 | //
// ViewController.swift
// MyCamera
//
// Created by Rick Dsida on 7/4/14.
// Copyright (c) 2014 Rick Dsida. All rights reserved.
//
import UIKit
class PhotoViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
var overLayLoader = UIView()
@IBAction func buttonTap(sender: AnyObject) {
}
// FONT STLYING //
let attributeDictionary = [UITextAttributeTextColor: UIColor.whiteColor(), UITextAttributeFont: UIFont(name: "Noteworthy-Bold", size: 35)]
func makeSpinner() {
overLayLoader.frame = UIScreen.mainScreen().bounds
overLayLoader.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
activityIndicator.startAnimating()
activityIndicator.center = overLayLoader.center
overLayLoader.addSubview(activityIndicator)
navigationController.view.addSubview(overLayLoader)
overLayLoader.hidden = true
}
override func shouldPerformSegueWithIdentifier(identifier: String!, sender: AnyObject!) -> Bool {
if self.image!.image == nil {
photoAlert()
return false
} else {
return true
}
}
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
var segueImage:UIImage = UIImage(named: "photo.JPG")
var imageString:NSString = TesseractController.recognizeImage(segueImage) as NSString
var foodCollection = TesseractController.regexDo(imageString)
foodCollection.enumerateObjectsUsingBlock(
{
(obj, index, pointer) -> Void in
sharedFoodController.foodAndPrices += obj as ParsedFood
}
)
sharedRegexController.deleteNonFood(foodCollection)
sharedRegexController.summarizeTaxes(foodCollection)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Outlets
@IBOutlet var photoButton: UIBarButtonItem
@IBOutlet var Instructions: UILabel
@IBOutlet var Continue: UILabel
@IBOutlet var Welcome: UILabel
@IBOutlet var image: UIImageView?
@IBOutlet var doneButton: UIBarButtonItem
@IBOutlet var choosePhotoButton: UIBarButtonItem
override func viewDidLoad() {
super.viewDidLoad()
navigationController.navigationBar.setTitleVerticalPositionAdjustment(8, forBarMetrics: UIBarMetrics.Default)
self.view.backgroundColor = lightBlue
self.navigationItem.title = "BillFold"
navigationController.navigationBar.titleTextAttributes = attributeDictionary
photoButton.title = "Photo"
navigationController.navigationBar.barTintColor = lightColor
}
func photoAlert() {
var photoAlert = UIAlertController(title: "No Photo Found", message: "Please take a photo", preferredStyle: UIAlertControllerStyle.Alert)
photoAlert.addAction(UIAlertAction(title: "Okay!", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(photoAlert, animated: true, completion: nil)
}
// Actions
@IBAction func choosePhoto(sender: UIBarButtonItem) {
let capture = UIImagePickerController()
capture.delegate = self
capture.sourceType = .PhotoLibrary
self.presentViewController(capture, animated: true, completion: nil)
}
@IBAction func takePhoto(sender : UIBarButtonItem) {
let capture = UIImagePickerController()
capture.delegate = self
if UIImagePickerController.isSourceTypeAvailable(.Camera) {
capture.sourceType = .Camera
}
else {
capture.sourceType = .PhotoLibrary
}
self.presentViewController(capture, animated: true, completion: nil)
}
// Delegate Methods
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
self.image!.image = image as UIImage
self.dismissModalViewControllerAnimated(true)
var cameraOverlayView: UITableView!
}
} | mit | a94ca65fd723fa978e77bb2bc5031648 | 35.754237 | 145 | 0.686808 | 5.56611 | false | false | false | false |
s-aska/Justaway-for-iOS | Justaway/AsyncOperation.swift | 1 | 2455 | // See also
// https://gist.github.com/calebd/93fa347397cec5f88233
// https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html
import Foundation
import Async
class AsyncOperation: Operation {
// MARK: - Types
enum State {
case ready, executing, finished
func keyPath() -> String {
switch self {
case .ready:
return "isReady"
case .executing:
return "isExecuting"
case .finished:
return "isFinished"
}
}
}
// MARK: - Properties
var state: State {
willSet {
willChangeValue(forKey: newValue.keyPath())
willChangeValue(forKey: state.keyPath())
}
didSet {
didChangeValue(forKey: oldValue.keyPath())
didChangeValue(forKey: state.keyPath())
}
}
// MARK: - Initializers
override init() {
state = .ready
super.init()
}
// MARK: - NSOperation
override var isReady: Bool {
return super.isReady && state == .ready
}
override var isExecuting: Bool {
return state == .executing
}
override var isFinished: Bool {
return state == .finished
}
override var isAsynchronous: Bool {
return true
}
}
class AsyncBlockOperation: AsyncOperation {
let executionBlock: (_ op: AsyncBlockOperation) -> Void
init(_ executionBlock: @escaping (_ op: AsyncBlockOperation) -> Void) {
self.executionBlock = executionBlock
super.init()
}
override func start() {
super.start()
state = .executing
executionBlock(self)
}
override func cancel() {
super.cancel()
state = .finished
}
func finish() {
state = .finished
}
}
class MainBlockOperation: AsyncOperation {
let executionBlock: (_ op: MainBlockOperation) -> Void
init(_ executionBlock: @escaping (_ op: MainBlockOperation) -> Void) {
self.executionBlock = executionBlock
super.init()
}
override func start() {
super.start()
state = .executing
Async.main {
self.executionBlock(self)
}
}
override func cancel() {
super.cancel()
state = .finished
}
func finish() {
state = .finished
}
}
| mit | bbd0b75f0246de74d8a8018e47a3f532 | 19.805085 | 134 | 0.567413 | 4.813725 | false | false | false | false |
bridger/NumberPad | NumberPad/SwiftAutoLayout.swift | 1 | 7088 | // Copyright (c) 2014 Indragie Karunaratne. All rights reserved.
// Licensed under the MIT license, see LICENSE file for more info.
#if os(OSX)
import AppKit
public typealias ALView = NSView
#elseif os(iOS)
import UIKit
public typealias ALView = UIView
#endif
public struct ALLayoutItem {
public let view: ALView
public let attribute: NSLayoutAttribute
public let multiplier: CGFloat
public let constant: CGFloat
init (view: ALView, attribute: NSLayoutAttribute, multiplier: CGFloat, constant: CGFloat) {
self.view = view
self.attribute = attribute
self.multiplier = multiplier
self.constant = constant
}
init (view: ALView, attribute: NSLayoutAttribute) {
self.view = view
self.attribute = attribute
self.multiplier = 1.0
self.constant = 0.0
}
// relateTo(), equalTo(), greaterThanOrEqualTo(), and lessThanOrEqualTo() used to be overloaded functions
// instead of having two separately named functions (e.g. relateTo() and relateToConstant()) but they had
// to be renamed due to a compiler bug where the compiler chose the wrong function to call.
//
// Repro case: http://cl.ly/3S0a1T0Q0S1D
// rdar://17412596, OpenRadar: http://www.openradar.me/radar?id=5275533159956480
/// Builds a constraint by relating the item to another item.
public func relateTo(right: ALLayoutItem, relation: NSLayoutRelation) -> NSLayoutConstraint {
return NSLayoutConstraint(item: view, attribute: attribute, relatedBy: relation, toItem: right.view, attribute: right.attribute, multiplier: right.multiplier, constant: right.constant)
}
/// Builds a constraint by relating the item to a constant value.
public func relateToConstant(right: CGFloat, relation: NSLayoutRelation) -> NSLayoutConstraint {
return NSLayoutConstraint(item: view, attribute: attribute, relatedBy: relation, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: right)
}
/// Equivalent to NSLayoutRelation.Equal
public func equalTo(right: ALLayoutItem) -> NSLayoutConstraint {
return relateTo(right: right, relation: .equal)
}
/// Equivalent to NSLayoutRelation.Equal
public func equalToConstant(right: CGFloat) -> NSLayoutConstraint {
return relateToConstant(right: right, relation: .equal)
}
/// Equivalent to NSLayoutRelation.GreaterThanOrEqual
public func greaterThanOrEqualTo(right: ALLayoutItem) -> NSLayoutConstraint {
return relateTo(right: right, relation: .greaterThanOrEqual)
}
/// Equivalent to NSLayoutRelation.GreaterThanOrEqual
public func greaterThanOrEqualToConstant(right: CGFloat) -> NSLayoutConstraint {
return relateToConstant(right: right, relation: .greaterThanOrEqual)
}
/// Equivalent to NSLayoutRelation.LessThanOrEqual
public func lessThanOrEqualTo(right: ALLayoutItem) -> NSLayoutConstraint {
return relateTo(right: right, relation: .lessThanOrEqual)
}
/// Equivalent to NSLayoutRelation.LessThanOrEqual
public func lessThanOrEqualToConstant(right: CGFloat) -> NSLayoutConstraint {
return relateToConstant(right: right, relation: .lessThanOrEqual)
}
}
/// Multiplies the operand's multiplier by the RHS value
public func * (left: ALLayoutItem, right: CGFloat) -> ALLayoutItem {
return ALLayoutItem(view: left.view, attribute: left.attribute, multiplier: left.multiplier * right, constant: left.constant)
}
/// Divides the operand's multiplier by the RHS value
public func / (left: ALLayoutItem, right: CGFloat) -> ALLayoutItem {
return ALLayoutItem(view: left.view, attribute: left.attribute, multiplier: left.multiplier / right, constant: left.constant)
}
/// Adds the RHS value to the operand's constant
public func + (left: ALLayoutItem, right: CGFloat) -> ALLayoutItem {
return ALLayoutItem(view: left.view, attribute: left.attribute, multiplier: left.multiplier, constant: left.constant + right)
}
/// Subtracts the RHS value from the operand's constant
public func - (left: ALLayoutItem, right: CGFloat) -> ALLayoutItem {
return ALLayoutItem(view: left.view, attribute: left.attribute, multiplier: left.multiplier, constant: left.constant - right)
}
/// Equivalent to NSLayoutRelation.Equal
public func == (left: ALLayoutItem, right: ALLayoutItem) -> NSLayoutConstraint {
return left.equalTo(right: right)
}
/// Equivalent to NSLayoutRelation.Equal
public func == (left: ALLayoutItem, right: CGFloat) -> NSLayoutConstraint {
return left.equalToConstant(right: right)
}
/// Equivalent to NSLayoutRelation.GreaterThanOrEqual
public func >= (left: ALLayoutItem, right: ALLayoutItem) -> NSLayoutConstraint {
return left.greaterThanOrEqualTo(right: right)
}
/// Equivalent to NSLayoutRelation.GreaterThanOrEqual
public func >= (left: ALLayoutItem, right: CGFloat) -> NSLayoutConstraint {
return left.greaterThanOrEqualToConstant(right: right)
}
/// Equivalent to NSLayoutRelation.LessThanOrEqual
public func <= (left: ALLayoutItem, right: ALLayoutItem) -> NSLayoutConstraint {
return left.lessThanOrEqualTo(right: right)
}
/// Equivalent to NSLayoutRelation.LessThanOrEqual
public func <= (left: ALLayoutItem, right: CGFloat) -> NSLayoutConstraint {
return left.lessThanOrEqualToConstant(right: right)
}
public extension ALView {
func al_operand(attribute: NSLayoutAttribute) -> ALLayoutItem {
return ALLayoutItem(view: self, attribute: attribute)
}
/// Equivalent to NSLayoutAttribute.Left
var al_left: ALLayoutItem {
return al_operand(attribute: .left)
}
/// Equivalent to NSLayoutAttribute.Right
var al_right: ALLayoutItem {
return al_operand(attribute: .right)
}
/// Equivalent to NSLayoutAttribute.Top
var al_top: ALLayoutItem {
return al_operand(attribute: .top)
}
/// Equivalent to NSLayoutAttribute.Bottom
var al_bottom: ALLayoutItem {
return al_operand(attribute: .bottom)
}
/// Equivalent to NSLayoutAttribute.Leading
var al_leading: ALLayoutItem {
return al_operand(attribute: .leading)
}
/// Equivalent to NSLayoutAttribute.Trailing
var al_trailing: ALLayoutItem {
return al_operand(attribute: .trailing)
}
/// Equivalent to NSLayoutAttribute.Width
var al_width: ALLayoutItem {
return al_operand(attribute: .width)
}
/// Equivalent to NSLayoutAttribute.Height
var al_height: ALLayoutItem {
return al_operand(attribute: .height)
}
/// Equivalent to NSLayoutAttribute.CenterX
var al_centerX: ALLayoutItem {
return al_operand(attribute: .centerX)
}
/// Equivalent to NSLayoutAttribute.CenterY
var al_centerY: ALLayoutItem {
return al_operand(attribute: .centerY)
}
/// Equivalent to NSLayoutAttribute.Baseline
var al_baseline: ALLayoutItem {
return al_operand(attribute: .lastBaseline)
}
}
| apache-2.0 | b5be7273062a29ae61bea4ba4c75c62e | 36.502646 | 192 | 0.711061 | 4.864791 | false | false | false | false |
nikHowlett/Attend-O | attendo1/ViewController.swift | 1 | 7723 | //
// ViewController.swift
// attendo1
//
// Created by Nik Howlett on 11/7/15.
// Copyright (c) 2015 NikHowlett. All rights reserved.
//
import UIKit
import UIKit
import CoreData
import QuartzCore
//AVCaptureMetadataOutputObjectsDelegate
var TSAuthenticatedReader2: TSReader!
let TSLogoutNotification2 = "edu.gatech.cal.logout"
let TSDismissWebViewNotification2 = "edu.gatech.cal.dismissWeb"
class ViewController: UIViewController {
@IBOutlet weak var usernametextfield: UITextField!
@IBOutlet weak var passwordtextfield: UITextField!
var classes1: [Class]?
required init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)!
}
override func viewDidLoad() {
super.viewDidLoad()
print("console output: true")
// Do any additional setup after loading the view, typically from a nib.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
view.addGestureRecognizer(tap)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func newCasLogin(newLogin newLogin: Bool) {
print("function called")
//print(TSAuthenticatedReader2.getAllClasses())
//attempt to authenticate
dispatch_async(TSNetworkQueue, {
TSReader.authenticatedReader(user: self.usernametextfield.text!, password: self.passwordtextfield.text!, isNewLogin: newLogin, completion: { reader in
print("dispatch_async called")
//successful login
if let reader = reader {
//let loginCount = 29//
print("this shit worked")
//NSUserDefaults.standardUserDefaults().integerForKey(TSLoginCountKey)
/*NSUserDefaults.standardUserDefaults().setInteger(loginCount + 1, forKey: TSLoginCountKey)*/
TSAuthenticatedReader2 = reader
self.presentClassesView(reader)
//self.performSegueWithIdentifier("newStudent", sender: self)
/*self.animateFormSubviewsWithDuration(0.5, hidden: false)
self.animateActivityIndicator(on: false)
self.setSavedCredentials(correct: true)
self.presentClassesView(reader)*/
}
else {
print("didn't work")
self.passwordtextfield.text = ""
/*shakeView(self.formView)*/
/*self.animateFormSubviewsWithDuration(0.5, hidden: false)
self.animateActivityIndicator(on: false)
self.setSavedCredentials(correct: false)*/
}
})
})
}
@IBAction func Login(sender: AnyObject) {
print("login button pressed")
newCasLogin(newLogin: true)
//old code for demos, prototypes and such
/*
if usernametextfield.text == "abowd" {
self.performSegueWithIdentifier("teacherLogin", sender: self)
} else if usernametextfield.text == "sampleTeacher" {
self.performSegueWithIdentifier("newTeacher", sender: self)
} else if usernametextfield.text == "teacher" {
self.performSegueWithIdentifier("teacher", sender: self)
} else if usernametextfield.text == "student" {
self.performSegueWithIdentifier("newStudent", sender: self)
} else if usernametextfield.text == "testAPI" {
self.performSegueWithIdentifier("testAPI", sender: self)
} else {
self.performSegueWithIdentifier("studentLogin", sender: self)
}*/
/*if TeacherStudent.on {
self.performSegueWithIdentifier("teacherLogin", sender: self)
} else {
self.performSegueWithIdentifier("studentLogin", sender: self)
}*/
}
func DismissKeyboard(){
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
//pragma mark - Unwind Seques
@IBAction func unwindToVC(segue: UIStoryboardSegue) {
print("Called goToSideMenu: unwind action")
}
func presentClassesView(reader: TSReader) {
//tapRecognizer.enabled = false
var classes: [Class] = []
var loadAttempt = 0
while classes.count == 0 && loadAttempt < 4 && !reader.actuallyHasNoClasses {
loadAttempt += 1
classes = reader.getActiveClasses()
print(classes)
print("presentClassesView")
classes1 = classes
//self.prepareForS)
if classes.count == 0 {
reader.checkIfHasNoClasses()
}
if loadAttempt > 2 {
HttpClient.clearCookies()
}
}
if loadAttempt >= 4 {
//present an alert and then exit the app if the classes aren't loading
//this means a failed authentication looked like it passed
//AKA I have no idea what happened
let message = "This happens every now and then. Please restart Attend-O and try again. If this keeps happening, please send an email to [email protected]"
let alert = UIAlertController(title: "There was a problem logging you in.", message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Restart", style: .Default, handler: { _ in
//crash
let null: Int! = nil
//null.threeCharacterString()
}))
self.presentViewController(alert, animated: true, completion: nil)
//self.setSavedCredentials(correct: false)
return
}
//self.performSegueWithIdentifier("newStudent", sender: self)
NSOperationQueue.mainQueue().addOperationWithBlock {
[weak self] in
self?.performSegueWithIdentifier("newStudent", sender: self)
}
//newStudentViewController.classes2 = classes
//newStudentViewController.reloadTable()
//open to the shortcut item if there is one queued
/*if let delegate = UIApplication.sharedApplication().delegate as? AppDelegate {
delegate.openShortcutItemIfPresent()
}*/
//animatePresentClassesView()
/*classesViewController.loadAnnouncements(reloadClasses: false, withInlineActivityIndicator: true)*/
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "newStudent" {
//if let classes = segue.destinationViewController as? newStudentViewController {
//classes.classes2 = classes1
//}
let navVC = segue.destinationViewController as! UINavigationController
let tableVC = navVC.viewControllers.first as! newStudentViewController
tableVC.classes2 = classes1
tableVC.username = usernametextfield.text!
}
/*print(TSAuthenticatedReader2.getActiveClasses())
print("classesprinted")
classes1 = classes.classes2*/
//classes.loginController = self
//classesViewController = classes
/*if let browser = segue.destinationViewController as? TSWebView {
browser.loginController = self
self.browserViewController = browser
}*/
}
}
| mit | 495168da38893a86c6a6db5c0ee935bf | 38.809278 | 169 | 0.602616 | 5.450247 | false | false | false | false |
troystribling/BlueCap | Tests/BlueCapKitTests/RawArrayPairDeserializableTests.swift | 1 | 2172 | //
// RawArrayPairDeserializableTests.swift
// BlueCapKit
//
// Created by Troy Stribling on 2/10/15.
// Copyright (c) 2015 Troy Stribling. The MIT License (MIT).
//
import UIKit
import XCTest
import CoreBluetooth
import CoreLocation
@testable import BlueCapKit
// MARK: - RawArrayPairDeserializableTests -
class RawArrayPairDeserializableTests: XCTestCase {
struct Pair: RawArrayPairDeserializable {
let value1: [Int8]
let value2: [UInt8]
static let size1: Int = 2
static let size2: Int = 2
// RawArrayPairDeserializable
static let uuid = "abc"
var rawValue1: [Int8] {
return self.value1
}
var rawValue2: [UInt8] {
return self.value2
}
init?(rawValue1: [Int8], rawValue2: [UInt8]) {
if rawValue1.count == Pair.size1 && rawValue2.count == Pair.size2 {
self.value1 = rawValue1
self.value2 = rawValue2
} else {
return nil
}
}
}
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testDeserialize_ValidRawPairArray_Sucess() {
let data = "02ab03ab".dataFromHexString()
if let value : Pair = SerDe.deserialize(data) {
XCTAssert(value.value1 == [Int8]([2, -85]) && value.value2 == [UInt8]([3, 171]))
} else {
XCTFail()
}
}
func testDeserialize_InvalidRawPairArray_Fails() {
let data = "020103".dataFromHexString()
if let _ : Pair = SerDe.deserialize(data) {
XCTFail()
}
}
func testSerialize_ValidRawPairArray_Sucess() {
if let value = Pair(rawValue1:[2, -85], rawValue2:[3, 171]) {
let data = SerDe.serialize(value)
XCTAssert(data.hexStringValue() == "02ab03ab")
} else {
XCTFail()
}
}
func testCreate_InValidRawPairArray_Fails() {
if let _ = Pair(rawValue1: [5], rawValue2: [1]) {
XCTFail()
}
}
}
| mit | f3170479985ca31ca3f5b3b7ddb35b71 | 24.255814 | 92 | 0.542818 | 4.217476 | false | true | false | false |
Pluto-Y/SwiftyEcharts | SwiftyEchartsTest_iOS/AxisPointerSpec.swift | 1 | 20136 | //
// AxisPointerSpec.swift
// SwiftyEcharts
//
// Created by Pluto Y on 26/08/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
import Quick
import Nimble
@testable import SwiftyEcharts
class AxisPointerSpec: QuickSpec {
override func spec() {
context("For AxisPointerForAxis") {
describe("For AxisPointerForAxis.Type") {
let lineString = "line"
let shadowString = "shadow"
let lineType = SwiftyEcharts.AxisPointerForAxis.Type.line
let shadowType = SwiftyEcharts.AxisPointerForAxis.Type.shadow
it("needs to check the jsonString") {
expect(lineType.jsonString).to(equal(lineString.jsonString))
expect(shadowType.jsonString).to(equal(shadowString.jsonString))
}
}
let showLabelValue = false
let precisionLabelValue: UInt8 = 4
let formatterLabelValue = Formatter.string("labelFormatterValue")
let marginLabelValue: Float = 0.0
let textStyleLabelValue = TextStyle()
let paddingLabelValue = Padding.verticalAndHorizontal(5, 10)
let backgroundColorLabelValue = Color.hexColor("#029573")
let borderColorLabelValue = Color.red
let borderWidthLabelValue: Float = 0.8572
let shadowBlurLabelValue: Float = 10
let shadowColorLabelValue = rgb(100, 0, 38)
let shadowOffsetXLabelValue: Float = 0.8572
let shadowOffsetYLabelValue: Float = 8937462.7623467
let label = Label()
label.show = showLabelValue
label.precision = precisionLabelValue
label.formatter = formatterLabelValue
label.margin = marginLabelValue
label.textStyle = textStyleLabelValue
label.padding = paddingLabelValue
label.backgroundColor = backgroundColorLabelValue
label.borderColor = borderColorLabelValue
label.borderWidth = borderWidthLabelValue
label.shadowBlur = shadowBlurLabelValue
label.shadowColor = shadowColorLabelValue
label.shadowOffsetX = shadowOffsetXLabelValue
label.shadowOffsetY = shadowOffsetYLabelValue
let showHandleValue = false
let iconHandleValue = "path://handleIconValue"
let sizeHandleValue: Pair<Float> = [20.5, 50.2]
let marginHandleValue: Float = 45
let colorHandleValue = Color.hexColor("#88ffaa")
let throttleHandleValue: Float = 5.555555
let shadowBlurHandleValue: Float = 20.20
let shadowColorHandleValue = Color.transparent
let shadowOffsetXHandleValue: Float = 0.5737
let shadowOffsetYHandleValue: Float = 85723.7234
let handle = AxisPointerForAxis.Handle()
handle.show = showHandleValue
handle.icon = iconHandleValue
handle.size = sizeHandleValue
handle.margin = marginHandleValue
handle.color = colorHandleValue
handle.throttle = throttleHandleValue
handle.shadowBlur = shadowBlurHandleValue
handle.shadowColor = shadowColorHandleValue
handle.shadowOffsetX = shadowOffsetXHandleValue
handle.shadowOffsetY = shadowOffsetYHandleValue
describe("For AxisPointerForAxis.Handle") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"show": showHandleValue,
"icon": iconHandleValue,
"size": sizeHandleValue,
"margin": marginHandleValue,
"color": colorHandleValue,
"throttle": throttleHandleValue,
"shadowBlur": shadowBlurHandleValue,
"shadowColor": shadowColorHandleValue,
"shadowOffsetX": shadowOffsetXHandleValue,
"shadowOffsetY": shadowOffsetYHandleValue
]
expect(handle.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let handleByEnums = AxisPointerForAxis.Handle(
.show(showHandleValue),
.icon(iconHandleValue),
.size(sizeHandleValue),
.margin(marginHandleValue),
.color(colorHandleValue),
.throttle(throttleHandleValue),
.shadowBlur(shadowBlurHandleValue),
.shadowColor(shadowColorHandleValue),
.shadowOffsetX(shadowOffsetXHandleValue),
.shadowOffsetY(shadowOffsetYHandleValue)
)
expect(handleByEnums.jsonString).to(equal(handle.jsonString))
}
}
let showAxisPointerValue = true
let typeAxisPointerValue = SwiftyEcharts.AxisPointerForAxis.Type.line
let snapAxisPointerValue = true
let zAxisPointerValue: Float = 0.58364
let labelAxisPointerValue = label
let lineStyleAxisPointerValue = LineStyle(
.opacity(0.8573),
.shadowBlur(20.57),
.curveness(200)
)
let shadowStyleAxisPointerValue = ShadowStyle(
.color(Color.rgb(0, 0, 200)),
.shadowColor(Color.rgba(200, 0, 0, 0.01)),
.shadowOffsetX(200.0)
)
let triggerAxisPointerForTooltipValue = false
let valueAxisPointerValue: Float = 0.8576
let stateAxisPointerValue = false
let handleAxisPointerValue = handle
let linkAxisPointerValue: [String: Jsonable] = ["xAxisIndex": "all"]
let triggerOnAxisPointerValue = AxisPointerForAxis.TriggerOn.click
let axisPointer = AxisPointerForAxis()
axisPointer.show = showAxisPointerValue
axisPointer.type = typeAxisPointerValue
axisPointer.snap = snapAxisPointerValue
axisPointer.z = zAxisPointerValue
axisPointer.label = labelAxisPointerValue
axisPointer.lineStyle = lineStyleAxisPointerValue
axisPointer.shadowStyle = shadowStyleAxisPointerValue
axisPointer.triggerTooltip = triggerAxisPointerForTooltipValue
axisPointer.value = valueAxisPointerValue
axisPointer.state = stateAxisPointerValue
axisPointer.handle = handleAxisPointerValue
axisPointer.link = OneOrMore(one: linkAxisPointerValue)
axisPointer.triggerOn = triggerOnAxisPointerValue
describe("For AxisPointerForAxis") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"show": showAxisPointerValue,
"type": typeAxisPointerValue,
"snap": snapAxisPointerValue,
"z": zAxisPointerValue,
"label": labelAxisPointerValue,
"lineStyle": lineStyleAxisPointerValue,
"shadowStyle": shadowStyleAxisPointerValue,
"triggerTooltip": triggerAxisPointerForTooltipValue,
"value": valueAxisPointerValue,
"state": stateAxisPointerValue,
"handle": handleAxisPointerValue,
"link": OneOrMore(one: linkAxisPointerValue),
"triggerOn": triggerOnAxisPointerValue
]
expect(axisPointer.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let axisPointerByEnums = AxisPointerForAxis(
.show(showAxisPointerValue),
.type(typeAxisPointerValue),
.snap(snapAxisPointerValue),
.z(zAxisPointerValue),
.label(labelAxisPointerValue),
.lineStyle(lineStyleAxisPointerValue),
.shadowStyle(shadowStyleAxisPointerValue),
.triggerTooltip(triggerAxisPointerForTooltipValue),
.value(valueAxisPointerValue),
.state(stateAxisPointerValue),
.handle(handleAxisPointerValue),
.link(linkAxisPointerValue),
.triggerOn(triggerOnAxisPointerValue)
)
expect(axisPointerByEnums.jsonString).to(equal(axisPointer.jsonString))
}
it("needs to check the links enum case") {
let links: [[String: Jsonable]] = [
[
"xAxisIndex": [0, 3, 4],
"yAxisName": "someName"
],
[
"xAxisId": ["aa", "cc"],
"angleAxis": "all"
]
]
axisPointer.link = OneOrMore(more: links)
let axisPointerByEnums = AxisPointerForAxis(
.show(showAxisPointerValue),
.type(typeAxisPointerValue),
.snap(snapAxisPointerValue),
.z(zAxisPointerValue),
.label(labelAxisPointerValue),
.lineStyle(lineStyleAxisPointerValue),
.shadowStyle(shadowStyleAxisPointerValue),
.triggerTooltip(triggerAxisPointerForTooltipValue),
.value(valueAxisPointerValue),
.state(stateAxisPointerValue),
.handle(handleAxisPointerValue),
.links(links),
.triggerOn(triggerOnAxisPointerValue)
)
expect(axisPointerByEnums.jsonString).to(equal(axisPointer.jsonString))
}
}
}
describe("For AxisPointerForTooltip.Type") {
let lineString = "line"
let crossString = "cross"
let shadowString = "shadow"
let noneString = "none"
let lineType = SwiftyEcharts.AxisPointerForTooltip.Type.line
let crossType = SwiftyEcharts.AxisPointerForTooltip.Type.cross
let shadowType = SwiftyEcharts.AxisPointerForTooltip.Type.shadow
let noneType = SwiftyEcharts.AxisPointerForTooltip.Type.none
it("needs to check the enum case jsonString") {
expect(lineType.jsonString).to(equal(lineString.jsonString))
expect(crossType.jsonString).to(equal(crossString.jsonString))
expect(shadowType.jsonString).to(equal(shadowString.jsonString))
expect(noneType.jsonString).to(equal(noneString.jsonString))
}
}
describe("For AxisPointerForTooltip.Axis") {
let xString = "x"
let yString = "y"
let radiusString = "radius"
let angleString = "angle"
let autoString = "auto"
let xAxis = AxisPointerForTooltip.Axis.x
let yAxis = AxisPointerForTooltip.Axis.y
let radiusAxis = AxisPointerForTooltip.Axis.radius
let angleAxis = AxisPointerForTooltip.Axis.angle
let autoAxis = AxisPointerForTooltip.Axis.auto
it("needs to check the enum case jsonString") {
expect(xAxis.jsonString).to(equal(xString.jsonString))
expect(yAxis.jsonString).to(equal(yString.jsonString))
expect(radiusAxis.jsonString).to(equal(radiusString.jsonString))
expect(angleAxis.jsonString).to(equal(angleString.jsonString))
expect(autoAxis.jsonString).to(equal(autoString.jsonString))
}
}
let colorCrossStyleValue = Color.hexColor("#87fabe")
let widthCrossStyleValue: Float = 85.347
let typeCrossStyleValue = LineType.dashed
let shadowBlurCrossStyleValue: Float = 985479
let shadowColorCrossStyleValue = Color.auto
let shadowOffsetXCrossStyleValue: Float = 0
let shadowOffsetYCrossStyleValue: Float = 0.0000038747238
let textStyleCrossStyleValue = TextStyle(
.color(Color.blue),
.fontStyle(FontStyle.italic),
.fontSize(75)
)
let crossStyle = AxisPointerForTooltip.CrossStyle()
crossStyle.color = colorCrossStyleValue
crossStyle.width = widthCrossStyleValue
crossStyle.type = typeCrossStyleValue
crossStyle.shadowBlur = shadowBlurCrossStyleValue
crossStyle.shadowColor = shadowColorCrossStyleValue
crossStyle.shadowOffsetX = shadowOffsetXCrossStyleValue
crossStyle.shadowOffsetY = shadowOffsetYCrossStyleValue
crossStyle.textStyle = textStyleCrossStyleValue
describe("For AxisPointerForTooltip.CrossStyle") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"color": colorCrossStyleValue,
"width": widthCrossStyleValue,
"type": typeCrossStyleValue,
"shadowBlur": shadowBlurCrossStyleValue,
"shadowColor": shadowColorCrossStyleValue,
"shadowOffsetX": shadowOffsetXCrossStyleValue,
"shadowOffsetY": shadowOffsetYCrossStyleValue,
"textStyle": textStyleCrossStyleValue
]
expect(crossStyle.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let crossStyleByEnums = AxisPointerForTooltip.CrossStyle(
.color(colorCrossStyleValue),
.width(widthCrossStyleValue),
.type(typeCrossStyleValue),
.shadowBlur(shadowBlurCrossStyleValue),
.shadowColor(shadowColorCrossStyleValue),
.shadowOffsetX(shadowOffsetXCrossStyleValue),
.shadowOffsetY(shadowOffsetYCrossStyleValue),
.textStyle(textStyleCrossStyleValue)
)
expect(crossStyleByEnums.jsonString).to(equal(crossStyle.jsonString))
}
}
let typeAxisPointerForTooltipValue = SwiftyEcharts.AxisPointerForTooltip.Type.cross
let axisAxisPointerForTooltipValue = AxisPointerForTooltip.Axis.angle
let animationAxisPointerForTooltipValue = false
let animationThresholdAxisPointerForTooltipValue: Float = 0.000000
let animationDurationAxisPointerForTooltipValue = Time.number(764.7777)
let animationEasingAxisPointerForTooltipValue = EasingFunction.quarticInOut
let animationDelayAxisPointerForTooltipValue: Time = 88
let animationDurationUpdateAxisPointerForTooltipValue: Time = 75.37
let animationEasingUpdateAxisPointerForTooltipValue: EasingFunction = .cubicInOut
let animationDelayUpdateAxisPointerForTooltipValue = Time.init(integerLiteral: 84723)
let lineStyleAxisPointerForTooltipValue = LineStyle(
.width(7.247),
.color(rgb(88, 102, 200)),
.curveness(888.8888),
.type(LineType.solid)
)
let crossStyleAxisPointerForTooltipValue = crossStyle
let shadowStyleAxisPointerForTooltipValue = ShadowStyle(
.shadowBlur(10),
.shadowColor(rgba(0, 0, 0, 0.5))
)
let axisPointer = AxisPointerForTooltip()
axisPointer.type = typeAxisPointerForTooltipValue
axisPointer.axis = axisAxisPointerForTooltipValue
axisPointer.animation = animationAxisPointerForTooltipValue
axisPointer.animationThreshold = animationThresholdAxisPointerForTooltipValue
axisPointer.animationDuration = animationDurationAxisPointerForTooltipValue
axisPointer.animationEasing = animationEasingAxisPointerForTooltipValue
axisPointer.animationDelay = animationDelayAxisPointerForTooltipValue
axisPointer.animationDurationUpdate = animationDurationUpdateAxisPointerForTooltipValue
axisPointer.animationEasingUpdate = animationEasingUpdateAxisPointerForTooltipValue
axisPointer.animationDelayUpdate = animationDelayUpdateAxisPointerForTooltipValue
axisPointer.lineStyle = lineStyleAxisPointerForTooltipValue
axisPointer.crossStyle = crossStyleAxisPointerForTooltipValue
axisPointer.shadowStyle = shadowStyleAxisPointerForTooltipValue
describe("For AxisPointerForTooltip") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"type": typeAxisPointerForTooltipValue,
"axis": axisAxisPointerForTooltipValue,
"animation": animationAxisPointerForTooltipValue,
"animationThreshold": animationThresholdAxisPointerForTooltipValue,
"animationDuration": animationDurationAxisPointerForTooltipValue,
"animationEasing": animationEasingAxisPointerForTooltipValue,
"animationDelay": animationDelayAxisPointerForTooltipValue,
"animationDurationUpdate": animationDurationUpdateAxisPointerForTooltipValue,
"animationEasingUpdate": animationEasingUpdateAxisPointerForTooltipValue,
"animationDelayUpdate": animationDelayUpdateAxisPointerForTooltipValue,
"lineStyle": lineStyleAxisPointerForTooltipValue,
"crossStyle": crossStyleAxisPointerForTooltipValue,
"shadowStyle": shadowStyleAxisPointerForTooltipValue
]
expect(axisPointer.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let axisPointerByEnums = AxisPointerForTooltip(
.type(typeAxisPointerForTooltipValue),
.axis(axisAxisPointerForTooltipValue),
.animation(animationAxisPointerForTooltipValue),
.animationThreshold(animationThresholdAxisPointerForTooltipValue),
.animationDuration(animationDurationAxisPointerForTooltipValue),
.animationEasing(animationEasingAxisPointerForTooltipValue),
.animationDelay(animationDelayAxisPointerForTooltipValue),
.animationDurationUpdate(animationDurationUpdateAxisPointerForTooltipValue),
.animationEasingUpdate(animationEasingUpdateAxisPointerForTooltipValue),
.animationDelayUpdate(animationDelayUpdateAxisPointerForTooltipValue),
.lineStyle(lineStyleAxisPointerForTooltipValue),
.crossStyle(crossStyleAxisPointerForTooltipValue),
.shadowStyle(shadowStyleAxisPointerForTooltipValue)
)
expect(axisPointerByEnums.jsonString).to(equal(axisPointer.jsonString))
}
}
}
}
| mit | 8b3ec7eda556d50fbec3aac0cc841423 | 48.593596 | 97 | 0.586988 | 7.023021 | false | false | false | false |
joneshq/MessagePack.swift | MessagePack/Source/Helpers.swift | 2 | 6305 | import Foundation
/**
Creates a data object from the underlying storage of the array.
:param: array An array to convert to data.
:returns: A data object.
*/
func makeData(array: [UInt8]) -> NSData {
return array.withUnsafeBufferPointer { (ptr: UnsafeBufferPointer<UInt8>) -> NSData in
NSData(bytes: ptr.baseAddress, length: ptr.count)
}
}
/**
Joins `size` values from `generator` to form a `UInt64`.
:param: generator The generator that yields bytes.
:param: size The number of bytes to yield.
:returns: A `UInt64`, or `nil` if the generator runs out of elements.
*/
func joinUInt64<G: GeneratorType where G.Element == UInt8>(inout generator: G, size: Int) -> UInt64? {
var int: UInt64 = 0
for _ in 0..<size {
if let byte = generator.next() {
int = int << 8 | UInt64(byte)
} else {
return nil
}
}
return int
}
/**
Joins `length` values from `generator` to form a `String`.
:param: generator The generator that yields bytes.
:param: length The length of the resulting string.
:returns: A `String`, or `nil` if the generator runs out of elements.
*/
func joinString<G: GeneratorType where G.Element == UInt8>(inout generator: G, length: Int) -> String? {
var result = ""
for _ in 0..<length {
if let byte = generator.next() {
result.append(Character(UnicodeScalar(byte)))
} else {
return nil
}
}
return result
}
/**
Joins bytes from `generator` to form an `Array` of size `length`.
:param: generator The generator that yields bytes.
:param: length The length of the array.
:returns: An `Array`, or `nil` if the generator runs out of elements.
*/
func joinData<G: GeneratorType where G.Element == UInt8>(inout generator: G, length: Int) -> NSData? {
var array = [UInt8]()
array.reserveCapacity(length)
for _ in 0..<length {
if let value = generator.next() {
array.append(value)
} else {
return nil
}
}
return makeData(array)
}
/**
Joins bytes from `generator` to form an `Array` of size `length` containing `MessagePackValue` values.
:param: generator The generator that yields bytes.
:param: length The length of the array.
:returns: An `Array`, or `nil` if the generator runs out of elements.
*/
func joinArray<G: GeneratorType where G.Element == UInt8>(inout generator: G, length: Int, #compatibility: Bool) -> [MessagePackValue]? {
var array = [MessagePackValue]()
array.reserveCapacity(length)
for _ in 0..<length {
if let value = unpack(&generator, compatibility: compatibility) {
array.append(value)
} else {
return nil
}
}
return array
}
/**
Joins bytes from `generator` to form a `Dictionary` of size `length` containing `MessagePackValue` keys and values.
:param: generator The generator that yields bytes.
:param: length The length of the array.
:returns: A `Dictionary`, or `nil` if the generator runs out of elements.
*/
func joinMap<G: GeneratorType where G.Element == UInt8>(inout generator: G, length: Int, #compatibility: Bool) -> [MessagePackValue : MessagePackValue]? {
let doubleLength = length * 2
if let array = joinArray(&generator, length * 2, compatibility: compatibility) {
var dict = [MessagePackValue : MessagePackValue]()
var lastKey: MessagePackValue? = nil
for item in array {
if let key = lastKey {
dict[key] = item
lastKey = nil
} else {
lastKey = item
}
}
return dict
} else {
return nil
}
}
/**
Splits an integer into `parts` bytes.
:param: value The integer to split.
:param: parts The number of bytes into which to split.
:returns: An byte array representation of `value`.
*/
func splitInt(value: UInt64, #parts: Int) -> [UInt8] {
return map(stride(from: 8 * (parts - 1), through: 0, by: -8)) { (shift: Int) -> UInt8 in
return UInt8(truncatingBitPattern: value >> UInt64(shift))
}
}
/**
Encodes a positive integer into MessagePack bytes.
:param: value The integer to split.
:returns: A MessagePack byte representation of `value`.
*/
func packIntPos(value: UInt64) -> NSData {
switch value {
case let value where value <= 0x7f:
return makeData([UInt8(truncatingBitPattern: value)])
case let value where value <= 0xff:
return makeData([0xcc, UInt8(truncatingBitPattern: value)])
case let value where value <= 0xffff:
return makeData([0xcd] + splitInt(value, parts: 2))
case let value where value <= 0xffff_ffff:
return makeData([0xce] + splitInt(value, parts: 4))
case let value where value <= 0xffff_ffff_ffff_ffff:
return makeData([0xcf] + splitInt(value, parts: 8))
default:
preconditionFailure()
}
}
/**
Encodes a negative integer into MessagePack bytes.
:param: value The integer to split.
:returns: A MessagePack byte representation of `value`.
*/
func packIntNeg(value: Int64) -> NSData {
switch value {
case let value where value >= -0x20:
return makeData([0xe0 + UInt8(truncatingBitPattern: value)])
case let value where value >= -0x7f:
return makeData([0xd0, UInt8(bitPattern: Int8(value))])
case let value where value >= -0x7fff:
let truncated = UInt16(bitPattern: Int16(value))
return makeData([0xd1] + splitInt(UInt64(truncated), parts: 2))
case let value where value >= -0x7fff_ffff:
let truncated = UInt32(bitPattern: Int32(value))
return makeData([0xd2] + splitInt(UInt64(truncated), parts: 4))
case let value where value >= -0x7fff_ffff_ffff_ffff:
let truncated = UInt64(bitPattern: value)
return makeData([0xd3] + splitInt(truncated, parts: 8))
default:
preconditionFailure()
}
}
/**
Flattens a dictionary into an array of alternating keys and values.
:param: dict The dictionary to flatten.
:returns: An array of keys and values.
*/
func flatten<T>(dict: [T : T]) -> [T] {
return map(dict) { [$0.0, $0.1] }.reduce([], combine: +)
}
| mit | 16d3b844ba1dc07a4c198c3bbf19b21b | 29.458937 | 154 | 0.628866 | 4.013367 | false | false | false | false |
El-Fitz/ImageSlideshow | Pod/Classes/Core/ImageSlideshow.swift | 1 | 12709 | //
// ImageSlideshow.swift
// ImageSlideshow
//
// Created by Petr Zvoníček on 30.07.15.
//
import UIKit
public enum PageControlPosition {
case hidden
case insideScrollView
case underScrollView
case custom(padding: CGFloat)
var bottomPadding: CGFloat {
switch self {
case .hidden, .insideScrollView:
return 0.0
case .underScrollView:
return 30.0
case .custom(let padding):
return padding
}
}
}
public enum ImagePreload {
case fixed(offset: Int)
case all
}
open class ImageSlideshow: UIView {
open let scrollView = UIScrollView()
open let pageControl = UIPageControl()
// MARK: - State properties
/// Page control position
open var pageControlPosition = PageControlPosition.insideScrollView {
didSet {
setNeedsLayout()
layoutScrollView()
}
}
/// Current page
open fileprivate(set) var currentPage: Int = 0 {
didSet {
pageControl.currentPage = currentPage
if oldValue != currentPage {
currentPageChanged?(currentPage)
loadImages(for: currentPage)
}
}
}
/// Called on each currentPage change
open var currentPageChanged: ((_ page: Int) -> ())?
/// Called on scrollViewWillBeginDragging
open var willBeginDragging: (() -> ())?
/// Called on scrollViewDidEndDecelerating
open var didEndDecelerating: (() -> ())?
/// Currenlty displayed slideshow item
open var currentSlideshowItem: ImageSlideshowItem? {
if slideshowItems.count > scrollViewPage {
return slideshowItems[scrollViewPage]
} else {
return nil
}
}
open fileprivate(set) var scrollViewPage: Int = 0
open fileprivate(set) var images = [InputSource]()
open fileprivate(set) var slideshowItems = [ImageSlideshowItem]()
// MARK: - Preferences
/// Enables/disables infinite scrolling between images
open var circular = true
/// Enables/disables user interactions
open var draggingEnabled = true {
didSet {
self.scrollView.isUserInteractionEnabled = draggingEnabled
}
}
/// Enables/disables zoom
open var zoomEnabled = false
/// Image change interval, zero stops the auto-scrolling
open var slideshowInterval = 0.0 {
didSet {
self.slideshowTimer?.invalidate()
self.slideshowTimer = nil
setTimerIfNeeded()
}
}
/// Image preload configuration, can be sed to .fixed to enable lazy load or .all
open var preload = ImagePreload.all
/// Content mode of each image in the slideshow
open var contentScaleMode: UIViewContentMode = UIViewContentMode.scaleAspectFit {
didSet {
for view in slideshowItems {
view.imageView.contentMode = contentScaleMode
}
}
}
fileprivate var slideshowTimer: Timer?
fileprivate var scrollViewImages = [InputSource]()
open fileprivate(set) var slideshowTransitioningDelegate: ZoomAnimatedTransitioningDelegate?
// MARK: - Life cycle
override public init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
convenience init() {
self.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
fileprivate func initialize() {
autoresizesSubviews = true
clipsToBounds = true
// scroll view configuration
scrollView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height - 50.0)
scrollView.delegate = self
scrollView.isPagingEnabled = true
scrollView.bounces = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.autoresizingMask = self.autoresizingMask
addSubview(scrollView)
addSubview(pageControl)
setTimerIfNeeded()
layoutScrollView()
}
override open func layoutSubviews() {
super.layoutSubviews()
// fixes the case when automaticallyAdjustsScrollViewInsets on parenting view controller is set to true
scrollView.contentInset = UIEdgeInsets.zero
if case .hidden = self.pageControlPosition {
pageControl.isHidden = true
} else {
pageControl.isHidden = false
}
pageControl.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: 10)
pageControl.center = CGPoint(x: frame.size.width / 2, y: frame.size.height - 12.0)
layoutScrollView()
}
/// updates frame of the scroll view and its inner items
func layoutScrollView() {
let scrollViewBottomPadding: CGFloat = pageControlPosition.bottomPadding
scrollView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height - scrollViewBottomPadding)
scrollView.contentSize = CGSize(width: scrollView.frame.size.width * CGFloat(scrollViewImages.count), height: scrollView.frame.size.height)
for (index, view) in self.slideshowItems.enumerated() {
if !view.zoomInInitially {
view.zoomOut()
}
view.frame = CGRect(x: scrollView.frame.size.width * CGFloat(index), y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height)
}
setCurrentPage(currentPage, animated: false)
}
/// reloads scroll view with latest slideshow items
func reloadScrollView() {
// remove previous slideshow items
for view in self.slideshowItems {
view.removeFromSuperview()
}
self.slideshowItems = []
var i = 0
for image in scrollViewImages {
let item = ImageSlideshowItem(image: image, zoomEnabled: self.zoomEnabled)
item.imageView.contentMode = self.contentScaleMode
slideshowItems.append(item)
scrollView.addSubview(item)
i += 1
}
if circular && (scrollViewImages.count > 1) {
scrollViewPage = 1
scrollView.scrollRectToVisible(CGRect(x: scrollView.frame.size.width, y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height), animated: false)
} else {
scrollViewPage = 0
}
loadImages(for: 0)
}
private func loadImages(for page: Int) {
let totalCount = slideshowItems.count
for i in 0..<totalCount {
let item = slideshowItems[i]
switch self.preload {
case .all:
item.loadImage()
case .fixed(let offset):
// load image if page is in range of loadOffset, else release image
let shouldLoad = abs(page-i) <= offset || abs(page-i) > totalCount-offset
shouldLoad ? item.loadImage() : item.releaseImage()
}
}
}
// MARK: - Image setting
open func setImageInputs(_ inputs: [InputSource]) {
self.images = inputs
self.pageControl.numberOfPages = inputs.count;
// in circular mode we add dummy first and last image to enable smooth scrolling
if circular && images.count > 1 {
var scImages = [InputSource]()
if let last = images.last {
scImages.append(last)
}
scImages += images
if let first = images.first {
scImages.append(first)
}
self.scrollViewImages = scImages
} else {
self.scrollViewImages = images;
}
reloadScrollView()
layoutScrollView()
setTimerIfNeeded()
}
// MARK: paging methods
open func setCurrentPage(_ currentPage: Int, animated: Bool) {
var pageOffset = currentPage
if circular {
pageOffset += 1
}
self.setScrollViewPage(pageOffset, animated: animated)
}
open func setScrollViewPage(_ scrollViewPage: Int, animated: Bool) {
if scrollViewPage < scrollViewImages.count {
self.scrollView.scrollRectToVisible(CGRect(x: scrollView.frame.size.width * CGFloat(scrollViewPage), y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height), animated: animated)
self.setCurrentPageForScrollViewPage(scrollViewPage)
}
}
fileprivate func setTimerIfNeeded() {
if slideshowInterval > 0 && scrollViewImages.count > 1 && slideshowTimer == nil {
slideshowTimer = Timer.scheduledTimer(timeInterval: slideshowInterval, target: self, selector: #selector(ImageSlideshow.slideshowTick(_:)), userInfo: nil, repeats: true)
}
}
func slideshowTick(_ timer: Timer) {
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
var nextPage = page + 1
if !circular && page == scrollViewImages.count - 1 {
nextPage = 0
}
self.scrollView.scrollRectToVisible(CGRect(x: scrollView.frame.size.width * CGFloat(nextPage), y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height), animated: true)
self.setCurrentPageForScrollViewPage(nextPage);
}
open func setCurrentPageForScrollViewPage(_ page: Int) {
if scrollViewPage != page {
// current page has changed, zoom out this image
if slideshowItems.count > scrollViewPage {
slideshowItems[scrollViewPage].zoomOut()
}
}
scrollViewPage = page
if circular {
if page == 0 {
// first page contains the last image
currentPage = Int(images.count) - 1
} else if page == scrollViewImages.count - 1 {
// last page contains the first image
currentPage = 0
} else {
currentPage = page - 1
}
} else {
currentPage = page
}
}
/// Stops slideshow timer
open func pauseTimerIfNeeded() {
slideshowTimer?.invalidate()
slideshowTimer = nil
}
/// Restarts slideshow timer
open func unpauseTimerIfNeeded() {
setTimerIfNeeded()
}
/// Open full screen slideshow
@discardableResult
open func presentFullScreenController(from controller:UIViewController) -> FullScreenSlideshowViewController {
let fullscreen = FullScreenSlideshowViewController()
fullscreen.pageSelected = {(page: Int) in
self.setCurrentPage(page, animated: false)
}
fullscreen.initialPage = self.currentPage
fullscreen.inputs = self.images
slideshowTransitioningDelegate = ZoomAnimatedTransitioningDelegate(slideshowView: self, slideshowController: fullscreen)
fullscreen.transitioningDelegate = slideshowTransitioningDelegate
controller.present(fullscreen, animated: true, completion: nil)
return fullscreen
}
}
extension ImageSlideshow: UIScrollViewDelegate {
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if slideshowTimer?.isValid != nil {
slideshowTimer?.invalidate()
slideshowTimer = nil
}
setTimerIfNeeded()
willBeginDragging?()
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
setCurrentPageForScrollViewPage(page);
didEndDecelerating?()
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if circular {
let regularContentOffset = scrollView.frame.size.width * CGFloat(images.count)
if (scrollView.contentOffset.x >= scrollView.frame.size.width * CGFloat(images.count + 1)) {
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x - regularContentOffset, y: 0)
} else if (scrollView.contentOffset.x < 0) {
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x + regularContentOffset, y: 0)
}
}
}
}
| mit | 33367f5b8831068a1b16f39a96375fcc | 32.177546 | 213 | 0.60565 | 5.40034 | false | false | false | false |
steve-cuzzort/ReadableConstraints | Example/Tests/Tests.swift | 1 | 46400 | // https://github.com/Quick/Quick
import Quick
import Nimble
import ReadableConstraints
class ReadableConstrantsSpec: QuickSpec
{
let TEST_CONSTANT:CGFloat = 10.0
var baseView:UIView! = UIView()
override func spec()
{
describe("isRightOf")
{
it("by")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t2")
.isRightOf(self.baseView, .By, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Trailing)
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isRightOf(self.baseView, .By, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Trailing)
}
it("plus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isRightOf(self.baseView, .Plus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Trailing)
}
it("minus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isRightOf(self.baseView, .Minus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Trailing,
constant: -self.TEST_CONSTANT)
}
it("exactly")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isRightOf(self.baseView, .Exactly, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Trailing,
constant: 0)
}
it("toCenter")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isRightOf(self.baseView, .By, self.TEST_CONSTANT, fromThe: .Center),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.CenterX)
}
it("toLeft")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isRightOf(self.baseView, .By, self.TEST_CONSTANT, fromThe: .Left),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Leading)
}
it("AtLeast")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isRightOf(self.baseView, .ByAtLeast, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Trailing,
equalityTest: NSLayoutRelation.GreaterThanOrEqual)
}
it("AtMost")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isRightOf(self.baseView, .ByAtMost, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Trailing,
equalityTest: NSLayoutRelation.LessThanOrEqual)
}
}
describe("isLeftOf")
{
it("by")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isLeftOf(self.baseView, .By, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.Leading,
constant: -self.TEST_CONSTANT)
}
it("plus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isLeftOf(self.baseView, .Plus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.Leading)
}
it("minus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isLeftOf(self.baseView, .Minus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.Leading,
constant: -self.TEST_CONSTANT)
}
it("exactly")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isLeftOf(self.baseView,.Exactly, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.Leading,
constant: 0)
}
it("toCenter")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isLeftOf(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Center),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.CenterX,
constant: -self.TEST_CONSTANT)
}
it("toRight")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isLeftOf(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Right),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.Trailing,
constant: -self.TEST_CONSTANT)
}
it("AtLeast")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isLeftOf(self.baseView,.ByAtLeast, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.Leading,
equalityTest: NSLayoutRelation.GreaterThanOrEqual,
constant: -self.TEST_CONSTANT)
}
it("AtMost")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isLeftOf(self.baseView,.ByAtMost, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.Leading,
equalityTest: NSLayoutRelation.LessThanOrEqual,
constant: -self.TEST_CONSTANT)
}
}
describe("isHorizontallyCenteredWith")
{
it("by")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isHorizontallyCenteredWith(self.baseView,.By, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.CenterY,
rhsAttr: NSLayoutAttribute.CenterY,
constant: self.TEST_CONSTANT)
}
it("plus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isHorizontallyCenteredWith(self.baseView,.Plus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.CenterY,
rhsAttr: NSLayoutAttribute.CenterY)
}
it("minus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isHorizontallyCenteredWith(self.baseView,.Minus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.CenterY,
rhsAttr: NSLayoutAttribute.CenterY,
constant: -self.TEST_CONSTANT)
}
it("exactly")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isHorizontallyCenteredWith(self.baseView,.Exactly, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.CenterY,
rhsAttr: NSLayoutAttribute.CenterY,
constant: 0)
}
it("toTop")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isHorizontallyCenteredWith(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Top),
lhsAttr: NSLayoutAttribute.CenterY,
rhsAttr: NSLayoutAttribute.Top,
constant: self.TEST_CONSTANT)
}
it("toBottom")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isHorizontallyCenteredWith(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Bottom),
lhsAttr: NSLayoutAttribute.CenterY,
rhsAttr: NSLayoutAttribute.Bottom,
constant: self.TEST_CONSTANT)
}
it("AtLeast")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isHorizontallyCenteredWith(self.baseView,.ByAtLeast, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.CenterY,
rhsAttr: NSLayoutAttribute.CenterY,
equalityTest: NSLayoutRelation.GreaterThanOrEqual,
constant: self.TEST_CONSTANT)
}
it("AtMost")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isHorizontallyCenteredWith(self.baseView,.ByAtMost, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.CenterY,
rhsAttr: NSLayoutAttribute.CenterY,
equalityTest: NSLayoutRelation.LessThanOrEqual,
constant: self.TEST_CONSTANT)
}
}
describe("isAbove")
{
it("by")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAbove(self.baseView,.By, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.Top,
constant: -self.TEST_CONSTANT)
}
it("plus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAbove(self.baseView,.Plus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.Top)
}
it("minus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAbove(self.baseView,.Minus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.Top,
constant: -self.TEST_CONSTANT)
}
it("exactly")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAbove(self.baseView,.Exactly, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.Top,
constant: 0)
}
it("toCenter")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAbove(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Center),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.CenterY,
constant: -self.TEST_CONSTANT)
}
it("toBottom")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAbove(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Bottom),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.Bottom,
constant: -self.TEST_CONSTANT)
}
it("AtLeast")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAbove(self.baseView,.ByAtLeast, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.Top,
equalityTest: NSLayoutRelation.GreaterThanOrEqual,
constant: -self.TEST_CONSTANT)
}
it("AtMost")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAbove(self.baseView,.ByAtMost, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.Top,
equalityTest: NSLayoutRelation.LessThanOrEqual,
constant: -self.TEST_CONSTANT)
}
}
describe("isBelow")
{
it("by")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isBelow(self.baseView,.By, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.Bottom,
constant: self.TEST_CONSTANT)
}
it("plus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isBelow(self.baseView,.Plus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.Bottom)
}
it("minus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isBelow(self.baseView,.Minus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.Bottom,
constant: -self.TEST_CONSTANT)
}
it("exactly")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isBelow(self.baseView,.Exactly, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.Bottom,
constant: 0)
}
it("toCenter")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isBelow(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Center),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.CenterY,
constant: self.TEST_CONSTANT)
}
it("toTp[")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isBelow(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Top),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.Top,
constant: self.TEST_CONSTANT)
}
it("AtLeast")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isBelow(self.baseView,.ByAtLeast, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.Bottom,
equalityTest: NSLayoutRelation.GreaterThanOrEqual,
constant: self.TEST_CONSTANT)
}
it("AtMost")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isBelow(self.baseView,.ByAtMost, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.Bottom,
equalityTest: NSLayoutRelation.LessThanOrEqual,
constant: self.TEST_CONSTANT)
}
}
describe("isVerticallyCenteredWith")
{
it("by")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isVerticallyCenteredWith(self.baseView,.By, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.CenterX,
rhsAttr: NSLayoutAttribute.CenterX,
constant: self.TEST_CONSTANT)
}
it("plus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isVerticallyCenteredWith(self.baseView,.Plus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.CenterX,
rhsAttr: NSLayoutAttribute.CenterX)
}
it("minus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isVerticallyCenteredWith(self.baseView,.Minus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.CenterX,
rhsAttr: NSLayoutAttribute.CenterX,
constant: -self.TEST_CONSTANT)
}
it("exactly")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isVerticallyCenteredWith(self.baseView,.Exactly, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.CenterX,
rhsAttr: NSLayoutAttribute.CenterX,
constant: 0)
}
it("toLeft")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isVerticallyCenteredWith(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Left),
lhsAttr: NSLayoutAttribute.CenterX,
rhsAttr: NSLayoutAttribute.Leading,
constant: self.TEST_CONSTANT)
}
it("toRight")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isVerticallyCenteredWith(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Right),
lhsAttr: NSLayoutAttribute.CenterX,
rhsAttr: NSLayoutAttribute.Trailing,
constant: self.TEST_CONSTANT)
}
it("AtLeast")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isVerticallyCenteredWith(self.baseView,.ByAtLeast, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.CenterX,
rhsAttr: NSLayoutAttribute.CenterX,
equalityTest: NSLayoutRelation.GreaterThanOrEqual,
constant: self.TEST_CONSTANT)
}
it("AtMost")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isVerticallyCenteredWith(self.baseView,.ByAtMost, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.CenterX,
rhsAttr: NSLayoutAttribute.CenterX,
equalityTest: NSLayoutRelation.LessThanOrEqual,
constant: self.TEST_CONSTANT)
}
}
describe("rightEdgeIsAlignedWith")
{
it("by")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.rightEdgeIsAlignedWith(self.baseView,.By, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.Trailing,
constant: self.TEST_CONSTANT)
}
it("plus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.rightEdgeIsAlignedWith(self.baseView,.Plus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.Trailing)
}
it("minus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.rightEdgeIsAlignedWith(self.baseView,.Minus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.Trailing,
constant: -self.TEST_CONSTANT)
}
it("exactly")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.rightEdgeIsAlignedWith(self.baseView,.Exactly, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.Trailing,
constant: 0)
}
it("toLeft")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.rightEdgeIsAlignedWith(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Left),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.Leading,
constant: self.TEST_CONSTANT)
}
it("toCenter")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.rightEdgeIsAlignedWith(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Center),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.CenterX,
constant: self.TEST_CONSTANT)
}
it("AtLeast")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.rightEdgeIsAlignedWith(self.baseView,.ByAtLeast, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.Trailing,
equalityTest: NSLayoutRelation.GreaterThanOrEqual,
constant: self.TEST_CONSTANT)
}
it("AtMost")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.rightEdgeIsAlignedWith(self.baseView,.ByAtMost, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Trailing,
rhsAttr: NSLayoutAttribute.Trailing,
equalityTest: NSLayoutRelation.LessThanOrEqual,
constant: self.TEST_CONSTANT)
}
}
describe("leftEdgeIsAlignedWith")
{
it("by")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.leftEdgeIsAlignedWith(self.baseView,.By, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Leading,
constant: self.TEST_CONSTANT)
}
it("plus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.leftEdgeIsAlignedWith(self.baseView,.Plus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Leading)
}
it("minus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.leftEdgeIsAlignedWith(self.baseView,.Minus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Leading,
constant: -self.TEST_CONSTANT)
}
it("exactly")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.leftEdgeIsAlignedWith(self.baseView,.Exactly, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Leading,
constant: 0)
}
it("toRight")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.leftEdgeIsAlignedWith(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Right),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Trailing,
constant: self.TEST_CONSTANT)
}
it("toCenter")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.leftEdgeIsAlignedWith(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Center),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.CenterX,
constant: self.TEST_CONSTANT)
}
it("AtLeast")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.leftEdgeIsAlignedWith(self.baseView,.ByAtLeast, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Leading,
equalityTest: NSLayoutRelation.GreaterThanOrEqual,
constant: self.TEST_CONSTANT)
}
it("AtMost")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.leftEdgeIsAlignedWith(self.baseView,.ByAtMost, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Leading,
rhsAttr: NSLayoutAttribute.Leading,
equalityTest: NSLayoutRelation.LessThanOrEqual,
constant: self.TEST_CONSTANT)
}
}
describe("topEdgeIsAlignedWith")
{
it("by")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.topEdgeIsAlignedWith(self.baseView,.By, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.Top,
constant: self.TEST_CONSTANT)
}
it("plus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.topEdgeIsAlignedWith(self.baseView,.Plus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.Top)
}
it("minus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.topEdgeIsAlignedWith(self.baseView,.Minus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.Top,
constant: -self.TEST_CONSTANT)
}
it("exactly")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.topEdgeIsAlignedWith(self.baseView,.Exactly, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.Top,
constant: 0)
}
it("toBottom")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.topEdgeIsAlignedWith(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Bottom),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.Bottom,
constant: self.TEST_CONSTANT)
}
it("toCenter")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.topEdgeIsAlignedWith(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Center),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.CenterY,
constant: self.TEST_CONSTANT)
}
it("AtLeast")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.topEdgeIsAlignedWith(self.baseView,.ByAtLeast, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.Top,
equalityTest: NSLayoutRelation.GreaterThanOrEqual,
constant: self.TEST_CONSTANT)
}
it("AtMost")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.topEdgeIsAlignedWith(self.baseView,.ByAtMost, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Top,
rhsAttr: NSLayoutAttribute.Top,
equalityTest: NSLayoutRelation.LessThanOrEqual,
constant: self.TEST_CONSTANT)
}
}
describe("bottomEdgeIsAlignedWidh")
{
it("by")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.bottomEdgeIsAlignedWidh(self.baseView,.By, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.Bottom,
constant: self.TEST_CONSTANT)
}
it("plus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.bottomEdgeIsAlignedWidh(self.baseView,.Plus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.Bottom)
}
it("minus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.bottomEdgeIsAlignedWidh(self.baseView,.Minus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.Bottom,
constant: -self.TEST_CONSTANT)
}
it("exactly")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.bottomEdgeIsAlignedWidh(self.baseView,.Exactly, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.Bottom,
constant: 0)
}
it("toTop")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.bottomEdgeIsAlignedWidh(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Top),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.Top,
constant: self.TEST_CONSTANT)
}
it("toCenter")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.bottomEdgeIsAlignedWidh(self.baseView,.By, self.TEST_CONSTANT, fromThe: .Center),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.CenterY,
constant: self.TEST_CONSTANT)
}
it("AtLeast")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.bottomEdgeIsAlignedWidh(self.baseView,.ByAtLeast, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.Bottom,
equalityTest: NSLayoutRelation.GreaterThanOrEqual,
constant: self.TEST_CONSTANT)
}
it("AtMost")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.bottomEdgeIsAlignedWidh(self.baseView,.ByAtMost, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Bottom,
rhsAttr: NSLayoutAttribute.Bottom,
equalityTest: NSLayoutRelation.LessThanOrEqual,
constant: self.TEST_CONSTANT)
}
}
describe("isAsWideAs")
{
it("by")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAsWideAs(self.baseView,.By, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Width,
rhsAttr: NSLayoutAttribute.Width,
constant: self.TEST_CONSTANT)
}
it("plus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAsWideAs(self.baseView,.Plus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Width,
rhsAttr: NSLayoutAttribute.Width)
}
it("minus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAsWideAs(self.baseView,.Minus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Width,
rhsAttr: NSLayoutAttribute.Width,
constant: -self.TEST_CONSTANT)
}
it("exactly")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAsWideAs(self.baseView,.Exactly, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Width,
rhsAttr: NSLayoutAttribute.Width,
constant: 0)
}
it("isHigh")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAsWideAs(self.baseView,.Exactly, self.TEST_CONSTANT, .IsTall),
lhsAttr: NSLayoutAttribute.Width,
rhsAttr: NSLayoutAttribute.Height,
constant: 0)
}
it("AtLeast")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAsWideAs(self.baseView,.ByAtLeast, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Width,
rhsAttr: NSLayoutAttribute.Width,
equalityTest: NSLayoutRelation.GreaterThanOrEqual,
constant: self.TEST_CONSTANT)
}
it("AtMost")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAsWideAs(self.baseView,.ByAtMost, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Width,
rhsAttr: NSLayoutAttribute.Width,
equalityTest: NSLayoutRelation.LessThanOrEqual,
constant: self.TEST_CONSTANT)
}
it("byRatio")
{
self._doTestForEqualToConstraintsRatio(
self.addNewButton(self.baseView, text: "t")
.isAsWideAs(self.baseView,.ByRatio, 0.5),
lhsAttr: NSLayoutAttribute.Width,
rhsAttr: NSLayoutAttribute.Width,
ratio: 0.5)
}
it("AtLeastRatio")
{
self._doTestForEqualToConstraintsRatio(
self.addNewButton(self.baseView, text: "t")
.isAsWideAs(self.baseView,.RatioOfAtLeast, 0.5),
lhsAttr: NSLayoutAttribute.Width,
rhsAttr: NSLayoutAttribute.Width,
equalityTest: NSLayoutRelation.GreaterThanOrEqual,
ratio: 0.5)
}
it("AtMostRatio")
{
self._doTestForEqualToConstraintsRatio(
self.addNewButton(self.baseView, text: "t")
.isAsWideAs(self.baseView,.RatioOfAtMost, 0.5),
lhsAttr: NSLayoutAttribute.Width,
rhsAttr: NSLayoutAttribute.Width,
equalityTest: NSLayoutRelation.LessThanOrEqual,
ratio: 0.5)
}
}
describe("isAsTallAs")
{
it("by")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAsTallAs(self.baseView,.By, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Height,
rhsAttr: NSLayoutAttribute.Height,
constant: self.TEST_CONSTANT)
}
it("plus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAsTallAs(self.baseView,.Plus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Height,
rhsAttr: NSLayoutAttribute.Height)
}
it("minus")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAsTallAs(self.baseView,.Minus, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Height,
rhsAttr: NSLayoutAttribute.Height,
constant: -self.TEST_CONSTANT)
}
it("exactly")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAsTallAs(self.baseView,.Exactly, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Height,
rhsAttr: NSLayoutAttribute.Height,
constant: 0)
}
it("isWide")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAsTallAs(self.baseView,.Exactly, self.TEST_CONSTANT, .IsWide),
lhsAttr: NSLayoutAttribute.Height,
rhsAttr: NSLayoutAttribute.Width,
constant: 0)
}
it("AtLeast")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAsTallAs(self.baseView,.ByAtLeast, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Height,
rhsAttr: NSLayoutAttribute.Height,
equalityTest: NSLayoutRelation.GreaterThanOrEqual,
constant: self.TEST_CONSTANT)
}
it("AtMost")
{
self._doTestForEqualToConstraints(
self.addNewButton(self.baseView, text: "t")
.isAsTallAs(self.baseView,.ByAtMost, self.TEST_CONSTANT),
lhsAttr: NSLayoutAttribute.Height,
rhsAttr: NSLayoutAttribute.Height,
equalityTest: NSLayoutRelation.LessThanOrEqual,
constant: self.TEST_CONSTANT)
}
it("byRatio")
{
self._doTestForEqualToConstraintsRatio(
self.addNewButton(self.baseView, text: "t")
.isAsTallAs(self.baseView,.ByRatio, 0.5),
lhsAttr: NSLayoutAttribute.Height,
rhsAttr: NSLayoutAttribute.Height,
ratio: 0.5)
}
it("AtLeastRatio")
{
self._doTestForEqualToConstraintsRatio(
self.addNewButton(self.baseView, text: "t")
.isAsTallAs(self.baseView,.RatioOfAtLeast, 0.5),
lhsAttr: NSLayoutAttribute.Height,
rhsAttr: NSLayoutAttribute.Height,
equalityTest: NSLayoutRelation.GreaterThanOrEqual,
ratio: 0.5)
}
it("AtMostRatio")
{
self._doTestForEqualToConstraintsRatio(
self.addNewButton(self.baseView, text: "t")
.isAsTallAs(self.baseView,.RatioOfAtMost, 0.5),
lhsAttr: NSLayoutAttribute.Height,
rhsAttr: NSLayoutAttribute.Height,
equalityTest: NSLayoutRelation.LessThanOrEqual,
ratio: 0.5)
}
}
describe("test_screen_rotation")
{
let button = self.addNewButton(self.baseView, text: "t");
button.isAsTallAs(self.baseView, .ByRatio, 0.5, onlyFor: [.Landscape])
.isAsWideAs(self.baseView, .ByRatio, 1.0, onlyFor: [.Portrait])
expect(button.portraitConstraints.count) > 0
expect(button.landscapeConstraints.count) > 0
self.baseView.enablePortraitConstraints()
for c in button.portraitConstraints
{
expect(c.active) == true
}
for c in button.landscapeConstraints
{
expect(c.active) == false
}
self.baseView.enableLandscapeConstraints()
for c in button.portraitConstraints
{
expect(c.active) == false
}
for c in button.landscapeConstraints
{
expect(c.active) == true
}
}
}
func addNewButton(container:UIView, text label:String) -> (UIButton)
{
let button = UIButton()
button.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.8)
button.layer.cornerRadius = 10.0
button.setTitle(label, forState: UIControlState.Normal)
container.addSubview(button)
return button
}
func _doTestForEqualToConstraints(lhs:UIButton,
lhsAttr:NSLayoutAttribute,
rhsAttr:NSLayoutAttribute,
constant:CGFloat = 10.0,
equalityTest:NSLayoutRelation = NSLayoutRelation.Equal)
{
let realConstraint = lhs.asConstraint()
expect(realConstraint.constant) == constant
expect(realConstraint.firstItem as? UIButton) == lhs
expect(realConstraint.firstAttribute) == lhsAttr
expect(realConstraint.secondItem as? UIView) == self.baseView
expect(realConstraint.secondAttribute) == rhsAttr
expect(realConstraint.relation) == equalityTest
}
func _doTestForEqualToConstraintsRatio(lhs:UIButton,
lhsAttr:NSLayoutAttribute,
rhsAttr:NSLayoutAttribute,
ratio:CGFloat = 0.5,
equalityTest:NSLayoutRelation = NSLayoutRelation.Equal)
{
let realConstraint = lhs.asConstraint()
expect(realConstraint.multiplier) == ratio
expect(realConstraint.firstItem as? UIButton) == lhs
expect(realConstraint.firstAttribute) == lhsAttr
expect(realConstraint.secondItem as? UIView) == self.baseView
expect(realConstraint.secondAttribute) == rhsAttr
expect(realConstraint.relation) == equalityTest
}
}
| mit | fff712192ea1f7d6bea6680b8f60096c | 40.539839 | 109 | 0.505776 | 6.146509 | false | true | false | false |
WhisperSystems/Signal-iOS | Signal/src/network/GiphyAPI.swift | 1 | 18910 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
// There's no UTI type for webp!
enum GiphyFormat {
case gif, mp4, jpg
}
enum GiphyError: Error {
case assertionError(description: String)
case fetchFailure
}
extension GiphyError: LocalizedError {
public var errorDescription: String? {
switch self {
case .assertionError:
return NSLocalizedString("GIF_PICKER_ERROR_GENERIC", comment: "Generic error displayed when picking a GIF")
case .fetchFailure:
return NSLocalizedString("GIF_PICKER_ERROR_FETCH_FAILURE", comment: "Error displayed when there is a failure fetching a GIF from the remote service.")
}
}
}
// Represents a "rendition" of a GIF.
// Giphy offers a plethora of renditions for each image.
// They vary in content size (i.e. width, height),
// format (.jpg, .gif, .mp4, webp, etc.),
// quality, etc.
@objc class GiphyRendition: ProxiedContentAssetDescription {
let format: GiphyFormat
let name: String
let width: UInt
let height: UInt
let fileSize: UInt
init?(format: GiphyFormat,
name: String,
width: UInt,
height: UInt,
fileSize: UInt,
url: NSURL) {
self.format = format
self.name = name
self.width = width
self.height = height
self.fileSize = fileSize
let fileExtension = GiphyRendition.fileExtension(forFormat: format)
super.init(url: url, fileExtension: fileExtension)
}
private class func fileExtension(forFormat format: GiphyFormat) -> String {
switch format {
case .gif:
return "gif"
case .mp4:
return "mp4"
case .jpg:
return "jpg"
}
}
public var utiType: String {
switch format {
case .gif:
return kUTTypeGIF as String
case .mp4:
return kUTTypeMPEG4 as String
case .jpg:
return kUTTypeJPEG as String
}
}
public var isStill: Bool {
return name.hasSuffix("_still")
}
public var isDownsampled: Bool {
return name.hasSuffix("_downsampled")
}
public func log() {
Logger.verbose("\t \(format), \(name), \(width), \(height), \(fileSize)")
}
}
// Represents a single Giphy image.
@objc class GiphyImageInfo: NSObject {
let giphyId: String
let renditions: [GiphyRendition]
// We special-case the "original" rendition because it is the
// source of truth for the aspect ratio of the image.
let originalRendition: GiphyRendition
init(giphyId: String,
renditions: [GiphyRendition],
originalRendition: GiphyRendition) {
self.giphyId = giphyId
self.renditions = renditions
self.originalRendition = originalRendition
}
// TODO: We may need to tweak these constants.
let kMaxDimension = UInt(618)
let kMinPreviewDimension = UInt(60)
let kMinSendingDimension = UInt(101)
let kPreferedPreviewFileSize = UInt(256 * 1024)
let kPreferedSendingFileSize = UInt(3 * 1024 * 1024)
private enum PickingStrategy {
case smallerIsBetter, largerIsBetter
}
public func log() {
Logger.verbose("giphyId: \(giphyId), \(renditions.count)")
for rendition in renditions {
rendition.log()
}
}
public func pickStillRendition() -> GiphyRendition? {
// Stills are just temporary placeholders, so use the smallest still possible.
return pickRendition(renditionType: .stillPreview, pickingStrategy: .smallerIsBetter, maxFileSize: kPreferedPreviewFileSize)
}
public func pickPreviewRendition() -> GiphyRendition? {
// Try to pick a small file...
if let rendition = pickRendition(renditionType: .animatedLowQuality, pickingStrategy: .largerIsBetter, maxFileSize: kPreferedPreviewFileSize) {
return rendition
}
// ...but gradually relax the file restriction...
if let rendition = pickRendition(renditionType: .animatedLowQuality, pickingStrategy: .smallerIsBetter, maxFileSize: kPreferedPreviewFileSize * 2) {
return rendition
}
// ...and relax even more until we find an animated rendition.
return pickRendition(renditionType: .animatedLowQuality, pickingStrategy: .smallerIsBetter, maxFileSize: kPreferedPreviewFileSize * 3)
}
public func pickSendingRendition() -> GiphyRendition? {
// Try to pick a small file...
if let rendition = pickRendition(renditionType: .animatedHighQuality, pickingStrategy: .largerIsBetter, maxFileSize: kPreferedSendingFileSize) {
return rendition
}
// ...but gradually relax the file restriction...
if let rendition = pickRendition(renditionType: .animatedHighQuality, pickingStrategy: .smallerIsBetter, maxFileSize: kPreferedSendingFileSize * 2) {
return rendition
}
// ...and relax even more until we find an animated rendition.
return pickRendition(renditionType: .animatedHighQuality, pickingStrategy: .smallerIsBetter, maxFileSize: kPreferedSendingFileSize * 3)
}
enum RenditionType {
case stillPreview, animatedLowQuality, animatedHighQuality
}
// Picking a rendition must be done very carefully.
//
// * We want to avoid incomplete renditions.
// * We want to pick a rendition of "just good enough" quality.
private func pickRendition(renditionType: RenditionType, pickingStrategy: PickingStrategy, maxFileSize: UInt) -> GiphyRendition? {
var bestRendition: GiphyRendition?
for rendition in renditions {
switch renditionType {
case .stillPreview:
// Accept GIF or JPEG stills. In practice we'll
// usually select a JPEG since they'll be smaller.
guard [.gif, .jpg].contains(rendition.format) else {
continue
}
// Only consider still renditions.
guard rendition.isStill else {
continue
}
// Accept still renditions without a valid file size. Note that fileSize
// will be zero for renditions without a valid file size, so they will pass
// the maxFileSize test.
//
// Don't worry about max content size; still images are tiny in comparison
// with animated renditions.
guard rendition.width >= kMinPreviewDimension &&
rendition.height >= kMinPreviewDimension &&
rendition.fileSize <= maxFileSize
else {
continue
}
case .animatedLowQuality:
// Only use GIFs for animated renditions.
guard rendition.format == .gif else {
continue
}
// Ignore stills.
guard !rendition.isStill else {
continue
}
// Ignore "downsampled" renditions which skip frames, etc.
guard !rendition.isDownsampled else {
continue
}
guard rendition.width >= kMinPreviewDimension &&
rendition.width <= kMaxDimension &&
rendition.height >= kMinPreviewDimension &&
rendition.height <= kMaxDimension &&
rendition.fileSize > 0 &&
rendition.fileSize <= maxFileSize
else {
continue
}
case .animatedHighQuality:
// Only use GIFs for animated renditions.
guard rendition.format == .gif else {
continue
}
// Ignore stills.
guard !rendition.isStill else {
continue
}
// Ignore "downsampled" renditions which skip frames, etc.
guard !rendition.isDownsampled else {
continue
}
guard rendition.width >= kMinSendingDimension &&
rendition.width <= kMaxDimension &&
rendition.height >= kMinSendingDimension &&
rendition.height <= kMaxDimension &&
rendition.fileSize > 0 &&
rendition.fileSize <= maxFileSize
else {
continue
}
}
if let currentBestRendition = bestRendition {
if rendition.width == currentBestRendition.width &&
rendition.fileSize > 0 &&
currentBestRendition.fileSize > 0 &&
rendition.fileSize < currentBestRendition.fileSize {
// If two renditions have the same content size, prefer
// the rendition with the smaller file size, e.g.
// prefer JPEG over GIF for stills.
bestRendition = rendition
} else if pickingStrategy == .smallerIsBetter {
// "Smaller is better"
if rendition.width < currentBestRendition.width {
bestRendition = rendition
}
} else {
// "Larger is better"
if rendition.width > currentBestRendition.width {
bestRendition = rendition
}
}
} else {
bestRendition = rendition
}
}
return bestRendition
}
}
@objc class GiphyAPI: NSObject {
// MARK: - Properties
static let sharedInstance = GiphyAPI()
// Force usage as a singleton
override private init() {
super.init()
SwiftSingletons.register(self)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private let kGiphyBaseURL = URL(string: "https://api.giphy.com/")!
private func giphyAPISessionManager() -> AFHTTPSessionManager {
return ContentProxy.jsonSessionManager(baseUrl: kGiphyBaseURL)
}
// MARK: Search
// This is the Signal iOS API key.
let kGiphyApiKey = "ZsUpUm2L6cVbvei347EQNp7HrROjbOdc"
let kGiphyPageSize = 100
public func trending() -> Promise<[GiphyImageInfo]> {
let sessionManager = giphyAPISessionManager()
let urlString = "/v1/gifs/trending?api_key=\(kGiphyApiKey)&limit=\(kGiphyPageSize)"
return Promise { resolver in
guard ContentProxy.configureSessionManager(sessionManager: sessionManager, forUrl: urlString) else {
throw OWSErrorMakeAssertionError("Could not configure trending")
}
sessionManager.get(urlString,
parameters: [:],
progress: nil,
success: { _, value in
Logger.info("pending request succeeded")
guard let imageInfos = self.parseGiphyImages(responseJson: value) else {
resolver.reject(OWSErrorMakeAssertionError("unable to parse trending images"))
return
}
resolver.fulfill(imageInfos)
},
failure: { _, error in
Logger.error("trending request failed: \(error)")
resolver.reject(error)
})
}
}
public func search(query: String, success: @escaping (([GiphyImageInfo]) -> Void), failure: @escaping ((NSError?) -> Void)) {
let sessionManager = giphyAPISessionManager()
let kGiphyPageOffset = 0
guard let queryEncoded = query.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
owsFailDebug("Could not URL encode query: \(query).")
failure(nil)
return
}
let urlString = "/v1/gifs/search?api_key=\(kGiphyApiKey)&offset=\(kGiphyPageOffset)&limit=\(kGiphyPageSize)&q=\(queryEncoded)"
guard ContentProxy.configureSessionManager(sessionManager: sessionManager, forUrl: urlString) else {
owsFailDebug("Could not configure query: \(query).")
failure(nil)
return
}
sessionManager.get(urlString,
parameters: [:],
progress: nil,
success: { _, value in
Logger.info("search request succeeded")
guard let imageInfos = self.parseGiphyImages(responseJson: value) else {
failure(nil)
return
}
success(imageInfos)
},
failure: { _, error in
Logger.error("search request failed: \(error)")
failure(error as NSError)
})
}
// MARK: Parse API Responses
private func parseGiphyImages(responseJson: Any?) -> [GiphyImageInfo]? {
guard let responseJson = responseJson else {
Logger.error("Missing response.")
return nil
}
guard let responseDict = responseJson as? [String: Any] else {
Logger.error("Invalid response.")
return nil
}
guard let imageDicts = responseDict["data"] as? [[String: Any]] else {
Logger.error("Invalid response data.")
return nil
}
return imageDicts.compactMap { imageDict in
return parseGiphyImage(imageDict: imageDict)
}
}
// Giphy API results are often incomplete or malformed, so we need to be defensive.
private func parseGiphyImage(imageDict: [String: Any]) -> GiphyImageInfo? {
guard let giphyId = imageDict["id"] as? String else {
Logger.warn("Image dict missing id.")
return nil
}
guard giphyId.count > 0 else {
Logger.warn("Image dict has invalid id.")
return nil
}
guard let renditionDicts = imageDict["images"] as? [String: Any] else {
Logger.warn("Image dict missing renditions.")
return nil
}
var renditions = [GiphyRendition]()
for (renditionName, renditionDict) in renditionDicts {
guard let renditionDict = renditionDict as? [String: Any] else {
Logger.warn("Invalid rendition dict.")
continue
}
guard let rendition = parseGiphyRendition(renditionName: renditionName,
renditionDict: renditionDict) else {
continue
}
renditions.append(rendition)
}
guard renditions.count > 0 else {
Logger.warn("Image has no valid renditions.")
return nil
}
guard let originalRendition = findOriginalRendition(renditions: renditions) else {
Logger.warn("Image has no original rendition.")
return nil
}
return GiphyImageInfo(giphyId: giphyId,
renditions: renditions,
originalRendition: originalRendition)
}
private func findOriginalRendition(renditions: [GiphyRendition]) -> GiphyRendition? {
for rendition in renditions where rendition.name == "original" {
return rendition
}
return nil
}
// Giphy API results are often incomplete or malformed, so we need to be defensive.
//
// We should discard renditions which are missing or have invalid properties.
private func parseGiphyRendition(renditionName: String,
renditionDict: [String: Any]) -> GiphyRendition? {
guard let width = parsePositiveUInt(dict: renditionDict, key: "width", typeName: "rendition") else {
return nil
}
guard let height = parsePositiveUInt(dict: renditionDict, key: "height", typeName: "rendition") else {
return nil
}
// Be lenient when parsing file sizes - we don't require them for stills.
let fileSize = parseLenientUInt(dict: renditionDict, key: "size")
guard let urlString = renditionDict["url"] as? String else {
return nil
}
guard urlString.count > 0 else {
Logger.warn("Rendition has invalid url.")
return nil
}
guard let url = NSURL(string: urlString) else {
Logger.warn("Rendition url could not be parsed.")
return nil
}
guard let fileExtension = url.pathExtension?.lowercased() else {
Logger.warn("Rendition url missing file extension.")
return nil
}
var format = GiphyFormat.gif
if fileExtension == "gif" {
format = .gif
} else if fileExtension == "jpg" {
format = .jpg
} else if fileExtension == "mp4" {
format = .mp4
} else if fileExtension == "webp" {
return nil
} else {
Logger.warn("Invalid file extension: \(fileExtension).")
return nil
}
return GiphyRendition(
format: format,
name: renditionName,
width: width,
height: height,
fileSize: fileSize,
url: url
)
}
private func parsePositiveUInt(dict: [String: Any], key: String, typeName: String) -> UInt? {
guard let value = dict[key] else {
return nil
}
guard let stringValue = value as? String else {
return nil
}
guard let parsedValue = UInt(stringValue) else {
return nil
}
guard parsedValue > 0 else {
Logger.verbose("\(typeName) has non-positive \(key): \(parsedValue).")
return nil
}
return parsedValue
}
private func parseLenientUInt(dict: [String: Any], key: String) -> UInt {
let defaultValue = UInt(0)
guard let value = dict[key] else {
return defaultValue
}
guard let stringValue = value as? String else {
return defaultValue
}
guard let parsedValue = UInt(stringValue) else {
return defaultValue
}
return parsedValue
}
}
| gpl-3.0 | 79d22de901e8f889e42ea32dca2aa2d6 | 36.224409 | 162 | 0.561185 | 5.568316 | false | false | false | false |
nathawes/swift | test/decl/protocol/special/coding/struct_codable_member_type_lookup.swift | 8 | 22620 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown
// A top-level CodingKeys type to fall back to in lookups below.
public enum CodingKeys : String, CodingKey {
case topLevel
}
// MARK: - Synthesized CodingKeys Enum
// Structs which get synthesized Codable implementations should have visible
// CodingKey enums during member type lookup.
struct SynthesizedStruct : Codable {
let value: String = "foo"
// expected-warning@-1 {{immutable property will not be decoded because it is declared with an initial value which cannot be overwritten}}
// expected-note@-2 {{set the initial value via the initializer or explicitly define a CodingKeys enum including a 'value' case to silence this warning}}
// expected-note@-3 {{make the property mutable instead}}{{3-6=var}}
// Qualified type lookup should always be unambiguous.
public func qualifiedFoo(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared public because its parameter uses a private type}}
internal func qualifiedBar(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared internal because its parameter uses a private type}}
fileprivate func qualfiedBaz(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
private func qualifiedQux(_ key: SynthesizedStruct.CodingKeys) {}
// Unqualified lookups should find the synthesized CodingKeys type instead
// of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) { // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.value) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
// Lookup within nested types should look outside of the type.
struct Nested {
// Qualified lookup should remain as-is.
public func qualifiedFoo(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared public because its parameter uses a private type}}
internal func qualifiedBar(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared internal because its parameter uses a private type}}
fileprivate func qualfiedBaz(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
private func qualifiedQux(_ key: SynthesizedStruct.CodingKeys) {}
// Unqualified lookups should find the SynthesizedStruct's synthesized
// CodingKeys type instead of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) { // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
print(CodingKeys.value) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.value) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { // expected-error {{method cannot be declared fileprivate because its parameter uses a private type}}
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
}
}
// MARK: - No CodingKeys Enum
// Structs which don't get synthesized Codable implementations should expose the
// appropriate CodingKeys type.
struct NonSynthesizedStruct : Codable { // expected-note 4 {{'NonSynthesizedStruct' declared here}}
// No synthesized type since we implemented both methods.
init(from decoder: Decoder) throws {}
func encode(to encoder: Encoder) throws {}
// Qualified type lookup should clearly fail -- we shouldn't get a synthesized
// type here.
public func qualifiedFoo(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of 'NonSynthesizedStruct'}}
internal func qualifiedBar(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of 'NonSynthesizedStruct'}}
fileprivate func qualfiedBaz(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of 'NonSynthesizedStruct'}}
private func qualifiedQux(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of 'NonSynthesizedStruct'}}
// Unqualified lookups should find the public top-level CodingKeys type.
public func unqualifiedFoo(_ key: CodingKeys) { print(CodingKeys.topLevel) }
internal func unqualifiedBar(_ key: CodingKeys) { print(CodingKeys.topLevel) }
fileprivate func unqualifiedBaz(_ key: CodingKeys) { print(CodingKeys.topLevel) }
private func unqualifiedQux(_ key: CodingKeys) { print(CodingKeys.topLevel) }
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on top-level type.
}
qux(CodingKeys.nested)
}
}
// MARK: - Explicit CodingKeys Enum
// Structs which explicitly define their own CodingKeys types should have
// visible CodingKey enums during member type lookup.
struct ExplicitStruct : Codable {
let value: String = "foo"
public enum CodingKeys {
case a
case b
case c
}
init(from decoder: Decoder) throws {}
func encode(to encoder: Encoder) throws {}
// Qualified type lookup should always be unambiguous.
public func qualifiedFoo(_ key: ExplicitStruct.CodingKeys) {}
internal func qualifiedBar(_ key: ExplicitStruct.CodingKeys) {}
fileprivate func qualfiedBaz(_ key: ExplicitStruct.CodingKeys) {}
private func qualifiedQux(_ key: ExplicitStruct.CodingKeys) {}
// Unqualified lookups should find the synthesized CodingKeys type instead
// of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
// Lookup within nested types should look outside of the type.
struct Nested {
// Qualified lookup should remain as-is.
public func qualifiedFoo(_ key: ExplicitStruct.CodingKeys) {}
internal func qualifiedBar(_ key: ExplicitStruct.CodingKeys) {}
fileprivate func qualfiedBaz(_ key: ExplicitStruct.CodingKeys) {}
private func qualifiedQux(_ key: ExplicitStruct.CodingKeys) {}
// Unqualified lookups should find the ExplicitStruct's synthesized
// CodingKeys type instead of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
}
}
// MARK: - CodingKeys Enums in Extensions
// Structs which get a CodingKeys type in an extension should be able to see
// that type during member type lookup.
struct ExtendedStruct : Codable {
let value: String = "foo"
// Don't get an auto-synthesized type.
init(from decoder: Decoder) throws {}
func encode(to encoder: Encoder) throws {}
// Qualified type lookup should always be unambiguous.
public func qualifiedFoo(_ key: ExtendedStruct.CodingKeys) {}
internal func qualifiedBar(_ key: ExtendedStruct.CodingKeys) {}
fileprivate func qualfiedBaz(_ key: ExtendedStruct.CodingKeys) {}
private func qualifiedQux(_ key: ExtendedStruct.CodingKeys) {}
// Unqualified lookups should find the synthesized CodingKeys type instead
// of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
// Lookup within nested types should look outside of the type.
struct Nested {
// Qualified lookup should remain as-is.
public func qualifiedFoo(_ key: ExtendedStruct.CodingKeys) {}
internal func qualifiedBar(_ key: ExtendedStruct.CodingKeys) {}
fileprivate func qualfiedBaz(_ key: ExtendedStruct.CodingKeys) {}
private func qualifiedQux(_ key: ExtendedStruct.CodingKeys) {}
// Unqualified lookups should find the ExtendedStruct's synthesized
// CodingKeys type instead of the top-level type above.
public func unqualifiedFoo(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
internal func unqualifiedBar(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
fileprivate func unqualifiedBaz(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
private func unqualifiedQux(_ key: CodingKeys) {
print(CodingKeys.a) // Not found on top-level.
}
// Unqualified lookups should find the most local CodingKeys type available.
public func nestedUnqualifiedFoo(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func foo(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
foo(CodingKeys.nested)
}
internal func nestedUnqualifiedBar(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func bar(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
bar(CodingKeys.nested)
}
fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func baz(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
baz(CodingKeys.nested)
}
private func nestedUnqualifiedQux(_ key: CodingKeys) {
enum CodingKeys : String, CodingKey {
case nested
}
// CodingKeys should refer to the local unqualified enum.
func qux(_ key: CodingKeys) {
print(CodingKeys.nested) // Not found on synthesized type or top-level type.
}
qux(CodingKeys.nested)
}
}
}
extension ExtendedStruct {
enum CodingKeys : String, CodingKey {
case a, b, c
}
}
struct A {
struct Inner : Codable {
var value: Int = 42
func foo() {
print(CodingKeys.value) // Not found on A.CodingKeys or top-level type.
}
}
}
extension A {
enum CodingKeys : String, CodingKey {
case a
}
}
struct B : Codable {
// So B conforms to Codable using CodingKeys.b below.
var b: Int = 0
struct Inner {
var value: Int = 42
func foo() {
print(CodingKeys.b) // Not found on top-level type.
}
}
}
extension B {
enum CodingKeys : String, CodingKey {
case b
}
}
struct C : Codable {
struct Inner : Codable {
var value: Int = 42
func foo() {
print(CodingKeys.value) // Not found on C.CodingKeys or top-level type.
}
}
}
extension C.Inner {
enum CodingKeys : String, CodingKey {
case value
}
}
struct GenericCodableStruct<T : Codable> : Codable {}
func foo(_: GenericCodableStruct<Int>.CodingKeys) // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
struct sr6886 {
struct Nested : Codable {}
let Nested: Nested // Don't crash with a coding key that is the same as a nested type name
}
// Don't crash if we have a static property with the same name as an ivar that
// we will encode. We check the actual codegen in a SILGen test.
struct StaticInstanceNameDisambiguation : Codable {
static let version: Float = 0.42
let version: Int = 42
// expected-warning@-1 {{immutable property will not be decoded because it is declared with an initial value which cannot be overwritten}}
// expected-note@-2 {{set the initial value via the initializer or explicitly define a CodingKeys enum including a 'version' case to silence this warning}}
// expected-note@-3 {{make the property mutable instead}}{{3-6=var}}
}
| apache-2.0 | 683e609ef0cf1f62cf82c20aa278696b | 32.811659 | 174 | 0.694209 | 4.764111 | false | false | false | false |
roambotics/swift | stdlib/public/Concurrency/AsyncThrowingStream.swift | 2 | 23896 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY
/// An asynchronous sequence generated from an error-throwing closure that
/// calls a continuation to produce new elements.
///
/// `AsyncThrowingStream` conforms to `AsyncSequence`, providing a convenient
/// way to create an asynchronous sequence without manually implementing an
/// asynchronous iterator. In particular, an asynchronous stream is well-suited
/// to adapt callback- or delegation-based APIs to participate with
/// `async`-`await`.
///
/// In contrast to `AsyncStream`, this type can throw an error from the awaited
/// `next()`, which terminates the stream with the thrown error.
///
/// You initialize an `AsyncThrowingStream` with a closure that receives an
/// `AsyncThrowingStream.Continuation`. Produce elements in this closure, then
/// provide them to the stream by calling the continuation's `yield(_:)` method.
/// When there are no further elements to produce, call the continuation's
/// `finish()` method. This causes the sequence iterator to produce a `nil`,
/// which terminates the sequence. If an error occurs, call the continuation's
/// `finish(throwing:)` method, which causes the iterator's `next()` method to
/// throw the error to the awaiting call point. The continuation is `Sendable`,
/// which permits calling it from concurrent contexts external to the iteration
/// of the `AsyncThrowingStream`.
///
/// An arbitrary source of elements can produce elements faster than they are
/// consumed by a caller iterating over them. Because of this, `AsyncThrowingStream`
/// defines a buffering behavior, allowing the stream to buffer a specific
/// number of oldest or newest elements. By default, the buffer limit is
/// `Int.max`, which means it's unbounded.
///
/// ### Adapting Existing Code to Use Streams
///
/// To adapt existing callback code to use `async`-`await`, use the callbacks
/// to provide values to the stream, by using the continuation's `yield(_:)`
/// method.
///
/// Consider a hypothetical `QuakeMonitor` type that provides callers with
/// `Quake` instances every time it detects an earthquake. To receive callbacks,
/// callers set a custom closure as the value of the monitor's
/// `quakeHandler` property, which the monitor calls back as necessary. Callers
/// can also set an `errorHandler` to receive asynchronous error notifications,
/// such as the monitor service suddenly becoming unavailable.
///
/// class QuakeMonitor {
/// var quakeHandler: ((Quake) -> Void)?
/// var errorHandler: ((Error) -> Void)?
///
/// func startMonitoring() {…}
/// func stopMonitoring() {…}
/// }
///
/// To adapt this to use `async`-`await`, extend the `QuakeMonitor` to add a
/// `quakes` property, of type `AsyncThrowingStream<Quake>`. In the getter for
/// this property, return an `AsyncThrowingStream`, whose `build` closure --
/// called at runtime to create the stream -- uses the continuation to
/// perform the following steps:
///
/// 1. Creates a `QuakeMonitor` instance.
/// 2. Sets the monitor's `quakeHandler` property to a closure that receives
/// each `Quake` instance and forwards it to the stream by calling the
/// continuation's `yield(_:)` method.
/// 3. Sets the monitor's `errorHandler` property to a closure that receives
/// any error from the monitor and forwards it to the stream by calling the
/// continuation's `finish(throwing:)` method. This causes the stream's
/// iterator to throw the error and terminate the stream.
/// 4. Sets the continuation's `onTermination` property to a closure that
/// calls `stopMonitoring()` on the monitor.
/// 5. Calls `startMonitoring` on the `QuakeMonitor`.
///
/// ```
/// extension QuakeMonitor {
///
/// static var throwingQuakes: AsyncThrowingStream<Quake, Error> {
/// AsyncThrowingStream { continuation in
/// let monitor = QuakeMonitor()
/// monitor.quakeHandler = { quake in
/// continuation.yield(quake)
/// }
/// monitor.errorHandler = { error in
/// continuation.finish(throwing: error)
/// }
/// continuation.onTermination = { @Sendable _ in
/// monitor.stopMonitoring()
/// }
/// monitor.startMonitoring()
/// }
/// }
/// }
/// ```
///
///
/// Because the stream is an `AsyncSequence`, the call point uses the
/// `for`-`await`-`in` syntax to process each `Quake` instance as produced by the stream:
///
/// do {
/// for try await quake in quakeStream {
/// print("Quake: \(quake.date)")
/// }
/// print("Stream done.")
/// } catch {
/// print("Error: \(error)")
/// }
///
@available(SwiftStdlib 5.1, *)
public struct AsyncThrowingStream<Element, Failure: Error> {
/// A mechanism to interface between synchronous code and an asynchronous
/// stream.
///
/// The closure you provide to the `AsyncThrowingStream` in
/// `init(_:bufferingPolicy:_:)` receives an instance of this type when
/// invoked. Use this continuation to provide elements to the stream by
/// calling one of the `yield` methods, then terminate the stream normally by
/// calling the `finish()` method. You can also use the continuation's
/// `finish(throwing:)` method to terminate the stream by throwing an error.
///
/// - Note: Unlike other continuations in Swift,
/// `AsyncThrowingStream.Continuation` supports escaping.
public struct Continuation: Sendable {
/// A type that indicates how the stream terminated.
///
/// The `onTermination` closure receives an instance of this type.
public enum Termination {
/// The stream finished as a result of calling the continuation's
/// `finish` method.
///
/// The associated `Failure` value provides the error that terminated
/// the stream. If no error occurred, this value is `nil`.
case finished(Failure?)
/// The stream finished as a result of cancellation.
case cancelled
}
/// A type that indicates the result of yielding a value to a client, by
/// way of the continuation.
///
/// The various `yield` methods of `AsyncThrowingStream.Continuation` return
/// this type to indicate the success or failure of yielding an element to
/// the continuation.
public enum YieldResult {
/// The stream successfully enqueued the element.
///
/// This value represents the successful enqueueing of an element, whether
/// the stream buffers the element or delivers it immediately to a pending
/// call to `next()`. The associated value `remaining` is a hint that
/// indicates the number of remaining slots in the buffer at the time of
/// the `yield` call.
///
/// - Note: From a thread safety perspective, `remaining` is a lower bound
/// on the number of remaining slots. This is because a subsequent call
/// that uses the `remaining` value could race on the consumption of
/// values from the stream.
case enqueued(remaining: Int)
/// The stream didn't enqueue the element because the buffer was full.
///
/// The associated element for this case is the element that the stream
/// dropped.
case dropped(Element)
/// The stream didn't enqueue the element because the stream was in a
/// terminal state.
///
/// This indicates the stream terminated prior to calling `yield`, either
/// because the stream finished normally or through cancellation, or
/// it threw an error.
case terminated
}
/// A strategy that handles exhaustion of a buffer’s capacity.
public enum BufferingPolicy {
/// Continue to add to the buffer, treating its capacity as infinite.
case unbounded
/// When the buffer is full, discard the newly received element.
///
/// This strategy enforces keeping the specified amount of oldest values.
case bufferingOldest(Int)
/// When the buffer is full, discard the oldest element in the buffer.
///
/// This strategy enforces keeping the specified amount of newest values.
case bufferingNewest(Int)
}
let storage: _Storage
/// Resume the task awaiting the next iteration point by having it return
/// normally from its suspension point with a given element.
///
/// - Parameter value: The value to yield from the continuation.
/// - Returns: A `YieldResult` that indicates the success or failure of the
/// yield operation.
///
/// If nothing is awaiting the next value, the method attempts to buffer the
/// result's element.
///
/// This can be called more than once and returns to the caller immediately
/// without blocking for any awaiting consumption from the iteration.
@discardableResult
public func yield(_ value: __owned Element) -> YieldResult {
storage.yield(value)
}
/// Resume the task awaiting the next iteration point by having it return
/// nil, which signifies the end of the iteration.
///
/// - Parameter error: The error to throw, or `nil`, to finish normally.
///
/// Calling this function more than once has no effect. After calling
/// finish, the stream enters a terminal state and doesn't produce any additional
/// elements.
public func finish(throwing error: __owned Failure? = nil) {
storage.finish(throwing: error)
}
/// A callback to invoke when canceling iteration of an asynchronous
/// stream.
///
/// If an `onTermination` callback is set, using task cancellation to
/// terminate iteration of an `AsyncThrowingStream` results in a call to this
/// callback.
///
/// Canceling an active iteration invokes the `onTermination` callback
/// first, and then resumes by yielding `nil` or throwing an error from the
/// iterator. This means that you can perform needed cleanup in the
/// cancellation handler. After reaching a terminal state, the
/// `AsyncThrowingStream` disposes of the callback.
public var onTermination: (@Sendable (Termination) -> Void)? {
get {
return storage.getOnTermination()
}
nonmutating set {
storage.setOnTermination(newValue)
}
}
}
final class _Context {
let storage: _Storage?
let produce: () async throws -> Element?
init(storage: _Storage? = nil, produce: @escaping () async throws -> Element?) {
self.storage = storage
self.produce = produce
}
deinit {
storage?.cancel()
}
}
let context: _Context
/// Constructs an asynchronous stream for an element type, using the
/// specified buffering policy and element-producing closure.
///
/// - Parameters:
/// - elementType: The type of element the `AsyncThrowingStream`
/// produces.
/// - limit: The maximum number of elements to
/// hold in the buffer. By default, this value is unlimited. Use a
/// `Continuation.BufferingPolicy` to buffer a specified number of oldest
/// or newest elements.
/// - build: A custom closure that yields values to the
/// `AsyncThrowingStream`. This closure receives an
/// `AsyncThrowingStream.Continuation` instance that it uses to provide
/// elements to the stream and terminate the stream when finished.
///
/// The `AsyncStream.Continuation` received by the `build` closure is
/// appropriate for use in concurrent contexts. It is thread safe to send and
/// finish; all calls are to the continuation are serialized. However, calling
/// this from multiple concurrent contexts could result in out-of-order
/// delivery.
///
/// The following example shows an `AsyncStream` created with this
/// initializer that produces 100 random numbers on a one-second interval,
/// calling `yield(_:)` to deliver each element to the awaiting call point.
/// When the `for` loop exits, the stream finishes by calling the
/// continuation's `finish()` method. If the random number is divisible by 5
/// with no remainder, the stream throws a `MyRandomNumberError`.
///
/// let stream = AsyncThrowingStream<Int, Error>(Int.self,
/// bufferingPolicy: .bufferingNewest(5)) { continuation in
/// Task.detached {
/// for _ in 0..<100 {
/// await Task.sleep(1 * 1_000_000_000)
/// let random = Int.random(in: 1...10)
/// if random % 5 == 0 {
/// continuation.finish(throwing: MyRandomNumberError())
/// return
/// } else {
/// continuation.yield(random)
/// }
/// }
/// continuation.finish()
/// }
/// }
///
/// // Call point:
/// do {
/// for try await random in stream {
/// print(random)
/// }
/// } catch {
/// print(error)
/// }
///
public init(
_ elementType: Element.Type = Element.self,
bufferingPolicy limit: Continuation.BufferingPolicy = .unbounded,
_ build: (Continuation) -> Void
) where Failure == Error {
let storage: _Storage = .create(limit: limit)
context = _Context(storage: storage, produce: storage.next)
build(Continuation(storage: storage))
}
/// Constructs an asynchronous throwing stream from a given element-producing
/// closure.
///
/// - Parameters:
/// - produce: A closure that asynchronously produces elements for the
/// stream.
///
/// Use this convenience initializer when you have an asynchronous function
/// that can produce elements for the stream, and don't want to invoke
/// a continuation manually. This initializer "unfolds" your closure into
/// a full-blown asynchronous stream. The created stream handles adherence to
/// the `AsyncSequence` protocol automatically. To terminate the stream with
/// an error, throw the error from your closure.
///
/// The following example shows an `AsyncThrowingStream` created with this
/// initializer that produces random numbers on a one-second interval. If the
/// random number is divisible by 5 with no remainder, the stream throws a
/// `MyRandomNumberError`.
///
/// let stream = AsyncThrowingStream<Int, Error> {
/// await Task.sleep(1 * 1_000_000_000)
/// let random = Int.random(in: 1...10)
/// if random % 5 == 0 {
/// throw MyRandomNumberError()
/// }
/// return random
/// }
///
/// // Call point:
/// do {
/// for try await random in stream {
/// print(random)
/// }
/// } catch {
/// print(error)
/// }
///
public init(
unfolding produce: @escaping () async throws -> Element?
) where Failure == Error {
let storage: _AsyncStreamCriticalStorage<Optional<() async throws -> Element?>>
= .create(produce)
context = _Context {
return try await withTaskCancellationHandler {
guard let result = try await storage.value?() else {
storage.value = nil
return nil
}
return result
} onCancel: {
storage.value = nil
}
}
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncThrowingStream: AsyncSequence {
/// The asynchronous iterator for iterating an asynchronous stream.
///
/// This type is not `Sendable`. Don't use it from multiple
/// concurrent contexts. It is a programmer error to invoke `next()` from a
/// concurrent context that contends with another such call, which
/// results in a call to `fatalError()`.
public struct Iterator: AsyncIteratorProtocol {
let context: _Context
/// The next value from the asynchronous stream.
///
/// When `next()` returns `nil`, this signifies the end of the
/// `AsyncThrowingStream`.
///
/// It is a programmer error to invoke `next()` from a concurrent context
/// that contends with another such call, which results in a call to
/// `fatalError()`.
///
/// If you cancel the task this iterator is running in while `next()` is
/// awaiting a value, the `AsyncThrowingStream` terminates. In this case,
/// `next()` may return `nil` immediately, or else return `nil` on
/// subsequent calls.
public mutating func next() async throws -> Element? {
return try await context.produce()
}
}
/// Creates the asynchronous iterator that produces elements of this
/// asynchronous sequence.
public func makeAsyncIterator() -> Iterator {
return Iterator(context: context)
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncThrowingStream.Continuation {
/// Resume the task awaiting the next iteration point by having it return
/// normally or throw, based on a given result.
///
/// - Parameter result: A result to yield from the continuation. In the
/// `.success(_:)` case, this returns the associated value from the
/// iterator's `next()` method. If the result is the `failure(_:)` case,
/// this call terminates the stream with the result's error, by calling
/// `finish(throwing:)`.
/// - Returns: A `YieldResult` that indicates the success or failure of the
/// yield operation.
///
/// If nothing is awaiting the next value and the result is success, this call
/// attempts to buffer the result's element.
///
/// If you call this method repeatedly, each call returns immediately, without
/// blocking for any awaiting consumption from the iteration.
@discardableResult
public func yield(
with result: Result<Element, Failure>
) -> YieldResult where Failure == Error {
switch result {
case .success(let val):
return storage.yield(val)
case .failure(let err):
storage.finish(throwing: err)
return .terminated
}
}
/// Resume the task awaiting the next iteration point by having it return
/// normally from its suspension point.
///
/// - Returns: A `YieldResult` that indicates the success or failure of the
/// yield operation.
///
/// Use this method with `AsyncThrowingStream` instances whose `Element`
/// type is `Void`. In this case, the `yield()` call unblocks the
/// awaiting iteration; there is no value to return.
///
/// If you call this method repeatedly, each call returns immediately,
/// without blocking for any awaiting consumption from the iteration.
@discardableResult
public func yield() -> YieldResult where Element == Void {
storage.yield(())
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncThrowingStream: @unchecked Sendable where Element: Sendable { }
#else
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public struct AsyncThrowingStream<Element, Failure: Error> {
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public struct Continuation: Sendable {
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public enum Termination {
case finished(Failure?)
case cancelled
}
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public enum YieldResult {
case enqueued(remaining: Int)
case dropped(Element)
case terminated
}
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public enum BufferingPolicy {
case unbounded
case bufferingOldest(Int)
case bufferingNewest(Int)
}
@discardableResult
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public func yield(_ value: __owned Element) -> YieldResult {
fatalError("Unavailable in task-to-thread concurrency model")
}
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public func finish(throwing error: __owned Failure? = nil) {
fatalError("Unavailable in task-to-thread concurrency model")
}
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public var onTermination: (@Sendable (Termination) -> Void)? {
get {
fatalError("Unavailable in task-to-thread concurrency model")
}
nonmutating set {
fatalError("Unavailable in task-to-thread concurrency model")
}
}
}
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public init(
_ elementType: Element.Type = Element.self,
bufferingPolicy limit: Continuation.BufferingPolicy = .unbounded,
_ build: (Continuation) -> Void
) where Failure == Error {
fatalError("Unavailable in task-to-thread concurrency model")
}
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public init(
unfolding produce: @escaping () async throws -> Element?
) where Failure == Error {
fatalError("Unavailable in task-to-thread concurrency model")
}
}
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
extension AsyncThrowingStream {
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public struct Iterator {
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public mutating func next() async throws -> Element? {
fatalError("Unavailable in task-to-thread concurrency model")
}
}
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public func makeAsyncIterator() -> Iterator {
fatalError("Unavailable in task-to-thread concurrency model")
}
}
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
extension AsyncThrowingStream.Continuation {
@discardableResult
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public func yield(
with result: Result<Element, Failure>
) -> YieldResult where Failure == Error {
fatalError("Unavailable in task-to-thread concurrency model")
}
@discardableResult
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public func yield() -> YieldResult where Element == Void {
fatalError("Unavailable in task-to-thread concurrency model")
}
}
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
extension AsyncThrowingStream: @unchecked Sendable where Element: Sendable { }
#endif
| apache-2.0 | 209ae09bbb3e7b8a88911696441f74a0 | 39.767918 | 110 | 0.659062 | 4.677893 | false | false | false | false |
EnderTan/ETNavBarTransparent | ETNavBarTransparentDemo/ETNavBarTransparentDemo/ProfileViewController.swift | 1 | 2951 | //
// ProfileViewController.swift
// ETNavBarTransparentDemo
//
// Created by Bing on 2017/3/1.
// Copyright © 2017年 tanyunbing. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
fileprivate var statusBarShouldLight = true
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
tableView.dataSource = self
tableView.delegate = self
self.navBarBgAlpha = 0
self.navBarTintColor = .white
}
override var preferredStatusBarStyle: UIStatusBarStyle {
if statusBarShouldLight {
return .lightContent
} else {
return .default
}
}
@IBAction func popWithCodeAction(_ sender: UIButton) {
_ = navigationController?.popViewController(animated: true)
}
@IBAction func popToRootAction(_ sender: UIButton) {
_ = navigationController?.popToRootViewController(animated: true)
}
}
extension ProfileViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "profileCell", for: indexPath)
cell.textLabel?.text = "第\(indexPath.row)行"
return cell
}
}
extension ProfileViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
//MARK:UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print(scrollView)
let contentOffsetY = scrollView.contentOffset.y
let showNavBarOffsetY = 200 - topLayoutGuide.length
//navigationBar alpha
if contentOffsetY > showNavBarOffsetY {
var navAlpha = (contentOffsetY - (showNavBarOffsetY)) / 40.0
if navAlpha > 1 {
navAlpha = 1
}
navBarBgAlpha = navAlpha
if navAlpha > 0.8 {
navBarTintColor = UIColor.defaultNavBarTintColor
statusBarShouldLight = false
}else{
navBarTintColor = UIColor.white
statusBarShouldLight = true
}
}else{
navBarBgAlpha = 0
navBarTintColor = UIColor.white
statusBarShouldLight = true
}
setNeedsStatusBarAppearanceUpdate()
}
}
| mit | a18d2c4fb954a320fde89c7ec808a173 | 24.6 | 100 | 0.600204 | 5.923541 | false | false | false | false |
YouareMylovelyGirl/Sina-Weibo | 新浪微博/新浪微博/Classes/View(视图和控制器)/Main/NewFeature/WelcomeView.swift | 1 | 3370 | //
// WelcomeView.swift
// 新浪微博
//
// Created by 阳光 on 2017/6/9.
// Copyright © 2017年 YG. All rights reserved.
//
import UIKit
import SDWebImage
///欢迎视图
class WelcomeView: UIView {
//头像
@IBOutlet weak var iconView: UIImageView!
//欢迎
@IBOutlet weak var tipLabel: UILabel!
//底部约束
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
class func welcome()->WelcomeView {
let nib = UINib(nibName: "WelcomeView", bundle: nil)
let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WelcomeView
//从xib中加载视图, 是600 x 600
//在这里设置大小
//注意层级不要覆盖了
v.frame = UIScreen.main.bounds
return v
}
// required init?(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
//
// //提示: initWithCoder, 只是刚刚从Xib的二进制文件将试图数据加载完成
// //还没有和代码连线建立起关系, 所以开发时, 千万不要在这个方法中处理UI
// print("initWithCoder+\(iconView)")
// }
override func awakeFromNib() {
//1. url
guard let urlString = NetManager.shareInstance.userAccount.avatar_large,
let url = URL(string: urlString) ,
let nameString = NetManager.shareInstance.userAccount.screen_name else {
return
}
tipLabel.text = nameString
//1. 设置头像- 如果不指定占位图像, 之前设置的图像会被清空
iconView.sd_setImage(with: url, placeholderImage: UIImage.init(named: "avatar_default_big"))
//如果这里设置没有作用, 需要设置约束的宽高
//设置圆角
iconView.layer.cornerRadius = iconView.bounds.width * 0.5
//切图
iconView.layer.masksToBounds = true
}
//自动布局系统更新完成约束后, 会自动调用此方法
//通常是对自视图布局进行修改
// override func layoutSubviews() {
//
// }
//didMoveToWindow 生命周期比 layoutSubView要早
//视图被添加到window 上, 表示视图已经显示
override func didMoveToWindow() {
super.didMoveToWindow()
//视图是使用自动布局来设置的, 知识设置了约束
//当视图被添加到窗口上时, 根据父视图的大小, 计算约束值, 更新控件位置
//如果控件们的frame还没有计算好, 调用layoutifneed, 会所有控件一起动画
//执行之后, 控件所在位置, 就是xib中布局的位置, 相当于先有了位置, 在此前调用这个方法didMoveToWindow 还没有frame
self.layoutIfNeeded()
UIView.animate(withDuration: 1.5, delay: 0.5, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
//更新约束
self.bottomConstraint.constant = self.bounds.size.height - 200
self.layoutIfNeeded()
}) { (_) in
UIView.animate(withDuration: 1.0, animations: {
self.tipLabel.alpha = 1
}, completion: { (_) in
//加载结束动画时候, 直接移除动画就好了
self.removeFromSuperview()
})
}
}
}
| apache-2.0 | e8aa80696b930842c7e76137d9e1cd61 | 26.622449 | 135 | 0.588105 | 3.834278 | false | false | false | false |
devnikor/Spinner | Pod/Classes/CircleIndicator.swift | 1 | 3100 | //
// CircleIndicator.swift
// Pods
//
// Created by Игорь Никитин on 05.02.16.
//
//
import UIKit
@IBDesignable
public class CircleIndicator: UIView {
private let circleLayer = CAShapeLayer()
// MARK: - Customization
@IBInspectable public var lineWidth: CGFloat = 5 {
didSet {
circleLayer.lineWidth = lineWidth
}
}
@IBInspectable public var lineCap: String = kCALineCapRound {
didSet {
circleLayer.lineCap = lineCap
}
}
@IBInspectable public var lineColor = UIColor.mainRedColor {
didSet {
circleLayer.strokeColor = lineColor.CGColor
}
}
@IBInspectable public var innerColor = UIColor.clearColor() {
didSet {
circleLayer.fillColor = innerColor.CGColor
}
}
@IBInspectable public var lineStart: CGFloat = 0.1 {
didSet {
circleLayer.strokeStart = lineStart
}
}
@IBInspectable public var lineEnd: CGFloat = 0.9 {
didSet {
circleLayer.strokeEnd = lineEnd
}
}
@IBInspectable public var revolutionDuration = 1.0
// MARK: - Initialization
override public init(frame: CGRect) {
super.init(frame: frame)
configureLayers()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureLayers()
}
private func configureLayers() {
layer.addSublayer(circleLayer)
circleLayer.fillColor = innerColor.CGColor
circleLayer.lineWidth = lineWidth
circleLayer.lineCap = lineCap
circleLayer.strokeColor = lineColor.CGColor
circleLayer.strokeStart = lineStart
circleLayer.strokeEnd = lineEnd
}
// MARK: - Layout
override public func layoutSubviews() {
super.layoutSubviews()
circleLayer.frame = bounds
circleLayer.path = spinnerPathWithRect(bounds)
}
private func spinnerPathWithRect(rect: CGRect) -> CGPath {
let minimumSide = min(rect.width, rect.height)
let originX = rect.width / 2 - minimumSide / 2 + lineWidth / 2
let originY = rect.height / 2 - minimumSide / 2 + lineWidth / 2
let side = minimumSide - lineWidth
let spinnerRect = CGRect(x: originX, y: originY, width: side, height: side)
return UIBezierPath(ovalInRect: spinnerRect).CGPath
}
// MARK: - Animation
public func beginAnimation() {
circleLayer.removeAllAnimations()
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.byValue = 2 * M_PI
rotationAnimation.duration = revolutionDuration
rotationAnimation.repeatCount = Float.infinity
circleLayer.addAnimation(rotationAnimation, forKey: "rotation")
}
public func endAnimation() {
circleLayer.removeAllAnimations()
}
}
extension CircleIndicator: SpinnerIndicator { }
| mit | 72cbc9b4e3e37fd50dc0755fa7f8fb78 | 25.393162 | 83 | 0.611399 | 5.260647 | false | false | false | false |
shridharmalimca/iOSDev | iOS/Components/MusicTransition/Pods/SRKUtility/SRKUtility-Source/Controls/ComboBoxVCtr.swift | 2 | 4188 | //
// ComboBoxVCtr.swift
//
import UIKit
@objc public protocol ComboBoxDelegate: NSObjectProtocol {
func comboBox(_ textField: ComboBox, didSelectRow row: Int)
func comboBoxNumberOfRows(_ textField: ComboBox) -> Int
func comboBox(_ textField: ComboBox, textForRow row: Int) -> String
func comboBoxPresentingViewController(_ textField: ComboBox) -> UIViewController
func comboBoxRectFromWhereToPresent(_ textField: ComboBox) -> CGRect
func comboBoxFromBarButton(_ textField: ComboBox) -> UIBarButtonItem?
func comboBoxTintColor(_ textField: ComboBox) -> UIColor
func comboBoxToolbarColor(_ textField: ComboBox) -> UIColor
func comboBoxDidTappedCancel(_ textField: ComboBox)
func comboBoxDidTappedDone(_ textField: ComboBox)
}
@objc open class ComboBox: UITextField {
open weak var delegateForComboBox: ComboBoxDelegate?
open var objComboBoxVCtr: ComboBoxVCtr?
open func showOptions() {
let podBundle = Bundle(for: self.classForCoder)
if let bundleURL = podBundle.url(forResource: "Controls", withExtension: "bundle") {
if let bundle = Bundle(url: bundleURL) {
self.objComboBoxVCtr = ComboBoxVCtr(nibName: "ComboBoxVCtr", bundle: bundle)
self.objComboBoxVCtr?.modalPresentationStyle = .popover
self.objComboBoxVCtr?.popoverPresentationController?.delegate = self.objComboBoxVCtr
self.objComboBoxVCtr?.refComboBox = self
if let btn = self.delegateForComboBox?.comboBoxFromBarButton(self) {
self.objComboBoxVCtr?.popoverPresentationController?.barButtonItem = btn
} else {
self.objComboBoxVCtr?.popoverPresentationController?.sourceView = self.delegateForComboBox?.comboBoxPresentingViewController(self).view
self.objComboBoxVCtr?.popoverPresentationController?.sourceRect = self.delegateForComboBox!.comboBoxRectFromWhereToPresent(self)
}
self.delegateForComboBox?.comboBoxPresentingViewController(self).present(self.objComboBoxVCtr!, animated: true, completion: nil)
} else {
assertionFailure("Could not load the bundle")
}
} else {
assertionFailure("Could not create a path to the bundle")
}
}
}
@objc open class ComboBoxVCtr: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UIPopoverPresentationControllerDelegate {
@IBOutlet open weak var pickerView: UIPickerView!
@IBOutlet open weak var toolBar: UIToolbar!
weak var refComboBox: ComboBox?
override open func viewDidLoad() {
super.viewDidLoad()
self.preferredContentSize = CGSize(width: 320, height: 260)
if let clr = self.refComboBox?.delegateForComboBox?.comboBoxTintColor(self.refComboBox!) {
self.toolBar.tintColor = clr
}
if let clr = self.refComboBox?.delegateForComboBox?.comboBoxToolbarColor(self.refComboBox!) {
self.toolBar.backgroundColor = clr
}
// self.refComboBox!.delegateForComboBox?.comboBox(self.refComboBox!, didSelectRow: 0)
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
open func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.refComboBox!.delegateForComboBox?.comboBox(self.refComboBox!, didSelectRow: row)
}
open func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return (self.refComboBox?.delegateForComboBox?.comboBoxNumberOfRows(self.refComboBox!))!
}
open func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.refComboBox?.delegateForComboBox?.comboBox(self.refComboBox!, textForRow: row)
}
open func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
@IBAction open func btnDoneTapped(_ sender: UIBarButtonItem) {
self.refComboBox?.delegateForComboBox?.comboBoxDidTappedDone(self.refComboBox!)
self.dismiss(animated: true, completion: nil)
}
@IBAction open func btnCancelTapped(_ sender: UIBarButtonItem) {
self.refComboBox?.delegateForComboBox?.comboBoxDidTappedCancel(self.refComboBox!)
self.dismiss(animated: true, completion: nil)
}
open func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.none
}
}
| apache-2.0 | f2dd52855116553c1bb40d97ede2b4f4 | 38.140187 | 140 | 0.776266 | 4.721533 | false | false | false | false |
steveEECSrubin/studies | iOS_development/udemy_ios8_adn_swift/swift_basics.swift | 1 | 2304 | //: Playground - noun: a place where people can play
import UIKit
//declare a variable not specifying the type
var str = "Hello, playground"
//changing the variable value
str = "Yo-yo"
//declare a variable specifying the type
var name:String = "Steve Rubin"
var integer:Int = 4
//declaring a double
var c:Double = 5/2
//cast an integer to a double
c * Double(integer)
//concatinating a string
var new_string = "My son is " + String(integer) + " years old"
//excercise
var x = 3.5
var y = 4
var z = 3.5*4
//arrays
var arr = [1, 2, 3, 4, 5, 6, 7]
//indexing starts with 0
arr[0]
//to find array size
var index = arr.count
//append an element at the end of an array
arr.append(8)
//remove
arr.removeAtIndex(0)
arr.removeLast()
arr.removeRange(1...3)
//craete an emoty array
var emptyArray:[Int]
//dictionary
var dict = ["first name": "Steve", "last name": "Rubin", "age": 24]
print(dict["last name"])
// ! means unwrap - the programmer is sure the value for "last name" exists
print(dict["last name"]!)
//add to a dictionary
dict["favorite color"] = "orange"
//remove a value from a key
dict["age"] = nil
//how to use an element of an dictionary
//var sentence = "My name is " + dict["first name"] // won't work
var first_name = "first name"
var sentence = "My name is \(dict[first_name]!)"
//some practice with arrays
var some_number = [2, 4, 6, 8]
some_number.removeFirst()
some_number.append(10)
//some practice with dictionaries
var my_info = ["name": "Steve Rubin", "age": 24]
var my_name = "name"
var my_age = "age"
var my_info_sentence = "my name is \(my_info[my_name]!) and my I am \(my_info[my_age]!) years old"
//IF statement
my_name = "Rob"
var time = 2
if(my_name == "Steve Rubin" && time < 12)
{
print("yo-yo")
}
else
{
print("oh, shit!")
}
//generate a randmo number
var random_number = arc4random_uniform(4)
//for loop
for var i = 0; i < 10; i++
{
//print(i)
//print("\n")
}
print("\n")
//iterate over an array
var arr2 = [2, 3, 4, 5, 7, 16, 7, 3]
for x in arr2
{
//print(x)
}
//mutate an array
for (index, element) in arr2.enumerate()
{
arr2[index] = element + 2
}
//while loop
var i = 1
while (i < 10)
{
print(i)
i++
}
//practice
var arr2_size = arr2.count
i = 0
while (i < arr2_size)
{
arr2[i] = arr2[i] - 1
i++
}
| unlicense | 45c4759501641b36b7a7ebb97413ea62 | 16.066667 | 98 | 0.639757 | 2.796117 | false | false | false | false |
freshOS/Komponents | Source/Button.swift | 1 | 4142 | //
// Button.swift
// Komponents
//
// Created by Sacha Durand Saint Omer on 11/05/2017.
// Copyright © 2017 freshOS. All rights reserved.
//
import Foundation
// support for selector / target
// public init(_ wording: String = "",
// image: UIImage? = nil,
// tap: (Selector, target: Any),
// style: ((UIButton) -> Void)? = nil,
// layout: ((UIButton) -> Void)? = nil,
// ref: UnsafeMutablePointer<UIButton>? = nil) {
// self.image = image
// self.wording = wording
// self.layoutBlock = layout
// self.styleBlock = style
// self.ref = ref
// registerTap = { button in
// button.addTarget(tap.target, action: tap.0, for: .touchUpInside)
// }
// }
//}
public struct Button: Node, Equatable {
public var uniqueIdentifier: Int = generateUniqueId()
public var propsHash: Int { return props.hashValue }
public let children = [IsNode]()
public var props: ButtonProps
public var layout: Layout
public let ref: UnsafeMutablePointer<UIButton>?
var registerTap: ((UIButton) -> Void)?
public init(_ wording: String = "",
image: UIImage? = nil,
tap: (() -> Void)? = nil,
props:((inout ButtonProps) -> Void)? = nil,
layout: Layout? = nil,
ref: UnsafeMutablePointer<UIButton>? = nil) {
var defaultProps = ButtonProps()
defaultProps.text = wording
defaultProps.image = image
if let p = props {
var prop = defaultProps
p(&prop)
self.props = prop
} else {
self.props = defaultProps
}
self.layout = layout ?? Layout()
self.ref = ref
registerTap = { button in
if let button = button as? BlockBasedUIButton, let tap = tap {
button.setCallback(tap)
}
}
}
func test() {
}
}
public func == (lhs: Button, rhs: Button) -> Bool {
return lhs.props == rhs.props
&& lhs.layout == rhs.layout
}
public struct ButtonProps: HasViewProps, Hashable, Equatable {
// HasViewProps
public var backgroundColor = UIColor.white
public var borderColor = UIColor.clear
public var borderWidth: CGFloat = 0
public var cornerRadius: CGFloat = 0
public var isHidden = false
public var alpha: CGFloat = 1
public var clipsToBounds = false
public var isUserInteractionEnabled = true
public init() {
text = ""
}
public var text: String
public var image: UIImage?
public var font: UIFont?
public var isEnabled = true
public mutating func setTitleColor(_ color: UIColor, for state: UIControl.State) {
if state == .normal {
titleColorForNormalState = color
}
if state == .highlighted {
titleColorForHighlightedState = color
}
}
internal var titleColorForNormalState: UIColor = .white
internal var titleColorForHighlightedState: UIColor = .white
public mutating func setBackgroundColor(_ color: UIColor, for state: UIControl.State) {
if state == .normal {
backgroundColorForNormalState = color
}
if state == .highlighted {
backgroundForHighlightedState = color
}
}
internal var backgroundColorForNormalState: UIColor?
internal var backgroundForHighlightedState: UIColor?
init(text: String = "") {
self.text = text
}
public var hashValue: Int {
return viewPropsHash
^ text.hashValue
^ titleColorForNormalState.hashValue
^ titleColorForHighlightedState.hashValue
^ isEnabled.hashValue
^ hashFor(backgroundColorForNormalState)
^ hashFor(backgroundForHighlightedState)
^ hashFor(image)
^ hashFor(font)
}
}
public func == (lhs: ButtonProps, rhs: ButtonProps) -> Bool {
return lhs.hashValue == rhs.hashValue
}
| mit | 763bf2a6cf71f532a595a5059b71f003 | 28.161972 | 91 | 0.576189 | 4.860329 | false | false | false | false |
zxpLearnios/MyProject | test_projectDemo1/GuideVC/Album/MyCollectionView.swift | 1 | 2716 | //
// MyCollectionView.swift
// test_projectDemo1
//
// Created by Jingnan Zhang on 16/7/21.
// Copyright © 2016年 Jingnan Zhang. All rights reserved.
// 暂时先不用
import UIKit
class MyCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var totalCount = 0
fileprivate let cellId = "MyCollectionViewCell"
class func getSelf() -> MyCollectionView{
let view = Bundle.main.loadNibNamed("MyCollectionView", owner: nil, options: nil)?.last as! MyCollectionView
// 改变布局
// view.collectionViewLayout = MyCollectionViewLayout.init()
return view
}
override func awakeFromNib() {
super.awakeFromNib()
// 必须设置,区别与OC, 或在getSelf设置
self.dataSource = self
self.delegate = self
// 数据不够一屏时,默认不滚动
self.alwaysBounceVertical = true
// 允许多选
self.allowsMultipleSelection = true
// 注册cell
self.register(UINib.init(nibName: cellId, bundle: nil), forCellWithReuseIdentifier: cellId)
// 添加返回按钮
let backBtn = UIButton.init()
backBtn.setImage(UIImage(named: "album_delete_btn"), for: UIControlState())
backBtn.width = 40
backBtn.height = 20
backBtn.center = CGPoint(x: 40, y: 30)
backBtn.addTarget(self, action: #selector(backAction), for: .touchUpInside)
self.addSubview(backBtn)
}
// 必须写,一确定cell的大小,否则就会用默认的; 每行展示3故 cell
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (kwidth - 4 * 20)/3
return CGSize(width: width, height: width)
}
// MARK: UICollectionViewDelegate, UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return totalCount + 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MyCollectionViewCell
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
debugPrint("点击了\(indexPath.item)")
}
// private
func backAction(_ btn:UIButton) {
// self.
}
}
| mit | 7205343a1fadc8b30b2b0bb0bb24ce00 | 30.280488 | 160 | 0.652242 | 5.13 | false | false | false | false |
cepages/CPSimpleHUD | Demo/SimpleHUD/ViewController.swift | 1 | 1710 | //
// ViewController.swift
// SimpleHUD
//
// Created by Carlos Pages on 28/08/2014.
// Copyright (c) 2014 Carlos Pages. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let INITIAL_REMAIN_TIME = 10
@IBOutlet weak var simpleHUDButton: UIButton!
var remainTime:Int = 0
var timer:NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func activateSimpleHUDToucheIn(sender: AnyObject) {
let buttonTouched = sender as UIButton
let hud = CPSimpleHUD.shareWaitingView
hud.loadingLabel.text = "Simple HUD"
hud.heightDarkViewContraint.constant = 250;
hud.widthDarkViewContraint.constant = 250;
// hud.waitingMode = .SmallCubesBorders
hud.show()
self.remainTime = INITIAL_REMAIN_TIME
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("timerFire:"), userInfo: nil, repeats: true)
}
func timerFire(timer: NSTimer){
self.remainTime--
//We update the button label
self.simpleHUDButton.setTitle("Time remaining \(self.remainTime)", forState:.Normal)
if self.remainTime == 0 {
CPSimpleHUD.shareWaitingView.hide()
self.simpleHUDButton.setTitle("Activate Simple HUD", forState:.Normal)
timer.invalidate()
}
}
}
| mit | 17910a0a23efb1a36350e95d2204e57e | 25.307692 | 140 | 0.62924 | 4.723757 | false | false | false | false |
ppth0608/BPStatusBarAlert | BPStatusBarAlert/Classes/DeviceDimensions.swift | 1 | 1293 | //
// DeviceDimensions.swift
//
//
// Created by Sameh Salama on 11/28/17.
//
import UIKit
internal struct DeviceDimensions {
fileprivate let iPhoneXMaxDeviceHeight: CGFloat = 2688
fileprivate let iPhoneXDeviceHeight:CGFloat = 2436
fileprivate let iPhoneXRDeviceHeight: CGFloat = 1792
fileprivate let paddingHeight:CGFloat = 15
fileprivate let nonPaddingHeight:CGFloat = 20
fileprivate var device:UIDevice {
return UIDevice.current
}
fileprivate var screen:UIScreen {
return UIScreen.main
}
var hasNotch : Bool
{
guard device.userInterfaceIdiom == .phone else {
return false
}
if #available(iOS 11.0, *),
let safeHeight = UIApplication.shared.keyWindow?.safeAreaInsets.top {
if safeHeight == 44
{
return true
}
}
if [iPhoneXDeviceHeight, iPhoneXMaxDeviceHeight, iPhoneXRDeviceHeight].contains(screen.nativeBounds.height)
{
return true
}
return false
}
var statusBarHeight: CGFloat {
if hasNotch
{
return paddingHeight
}else {
return nonPaddingHeight
}
}
}
| mit | bfade79282bab91b129ae734d722c3bc | 22.089286 | 115 | 0.583913 | 5.192771 | false | false | false | false |
changjianfeishui/iOS_Tutorials_Of_Swift | Custom View Controller Transitions/iLoveCatz/iLoveCatz/PinchInteractionController.swift | 1 | 1841 | //
// PinchInteractionController.swift
// iLoveCatz
//
// Created by XB on 16/5/17.
// Copyright © 2016年 XB. All rights reserved.
//
import UIKit
class PinchInteractionController: UIPercentDrivenInteractiveTransition {
var interactionInProgress:Bool = false
private var _shouldCompleteTransition:Bool = false
private var _viewController:UIViewController!
private var _startScale:CGFloat!
//This method allows you to attach the interaction controller to a view controller.
func wireToViewController(viewController:UIViewController) {
_viewController = viewController
self.prepareGestureRecognizerInView(viewController.view)
}
//This method adds a gesture recognizer to the view controller’s view to detect a pan.
func prepareGestureRecognizerInView(view:UIView) {
let gesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePan(_:)))
view.addGestureRecognizer(gesture)
}
func handlePan(pan:UIPinchGestureRecognizer) -> Void {
switch pan.state {
case .Began:
_startScale = pan.scale
print(_startScale)
self.interactionInProgress = true
_viewController.dismissViewControllerAnimated(true, completion: nil)
case .Changed:
let fraction = 1.0 - pan.scale/_startScale
_shouldCompleteTransition = (fraction > 0.5);
self.updateInteractiveTransition(fraction)
case .Ended,.Cancelled:
self.interactionInProgress = false
if !_shouldCompleteTransition||pan.state == UIGestureRecognizerState.Cancelled {
self.cancelInteractiveTransition()
}else{
self.finishInteractiveTransition()
}
default:
break
}
}
}
| mit | 66516cd0bde14469e75b4468be4a9e28 | 35 | 94 | 0.665033 | 5.513514 | false | false | false | false |
jarocht/iOS-AlarmDJ | AlarmDJ/AlarmDJ/RingtoneSelectorViewController.swift | 1 | 3937 | //
// RingtoneSelectorViewController.swift
// AlarmDJ
//
// Created by X Code User on 7/23/15.
// Copyright (c) 2015 Tim Jaroch, Morgan Heyboer, Andreas Plüss (TEAM E). All rights reserved.
//
import UIKit
import AudioToolbox
class RingtoneSelectorViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
var alarm: Alarm = Alarm()
var alarmIndex: Int = -1
@IBOutlet weak var pickerView: UIPickerView!
let ringtoneStringData = ["Alarm", "Anticipate", "Bloom", "Calypso", "Choo Choo", "Descent", "Fanfare", "Ladder", "Minuet", "News Flash", "Noir", "Sherwood Forest", "Spell", "Suspense", "Telegraph", "Tiptoes", "Typewriters", "Update", "Vibrate", "New Mail", "Mail Sent", "Voicemail", "Received Message", "Sent Message", "Lock", "Tock"]
let ringtoneValues = [1304,1305,1306,1320,1321,1322,1323,1324,1325,1326,1327,1328,1329,1330,1331,1332,1333,1334,1335,1336,4095,1000,1001,1002,1003,1004]
override func viewDidLoad() {
super.viewDidLoad()
pickerView.dataSource = self
var index = 0
for var i = 0; i < ringtoneValues.count; i++ {
if ringtoneValues[i] == alarm.ringtoneId {
index = i
}
}
pickerView.selectRow(index, inComponent: 0, animated: true)
pickerView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return ringtoneStringData.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return ringtoneStringData[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
alarm.ringtoneId = ringtoneValues[row]
// only rings if system sounds are avaible
// this is the case when the app is run on a
// arm architecture
#if (arch(i386) || arch(x86_64)) && os(iOS)
#else
AudioServicesPlaySystemSound(UInt32(ringtoneValues[row]))
#endif
}
@IBAction func saveBtnClicked(sender: AnyObject) {
var ldm = LocalDataManager()
var alarms = ldm.loadAlarms()
var alarm = Alarm(days: self.alarm.days, time: self.alarm.time, title: self.alarm.title, snooze: self.alarm.snooze, repeat: self.alarm.snooze, enabled: self.alarm.enabled, ringtoneId: self.alarm.ringtoneId)
alarms[alarmIndex] = alarm
ldm.saveAlarms(alarms: alarms)
navigationController!.popViewControllerAnimated(true)
}
}
/*
@IBAction func ringtonesButtonPressed(sender: UIButton) {
//Ringtone
let ringtone:String = self.ringtoneLabel.text!
var toneID:Int
switch ringtone {
case "Alarm":
toneID = 1304
case "Lock":
toneID = 1305
case "Tock":
toneID = 1306
case "Anticipate":
toneID = 1320
case "Bloom":
toneID = 1321
case "Calypso":
toneID = 1322
case "Choo Choo":
toneID = 1323
case "Descent":
toneID = 1324
case "Fanfare":
toneID = 1325
case "Ladder":
toneID = 1326
case "Minuet":
toneID = 1327
case "News Flash":
toneID = 1328
case "Noir":
toneID = 1329
case "Sherwood Forest":
toneID = 1330
case "Spell":
toneID = 1331
case "Suspense":
toneID = 1332
case "Telegraph":
toneID = 1333
case "Tiptoes":
toneID = 1334
case "Typewriters":
toneID = 1335
case "Update":
toneID = 1336
case "Vibrate":
toneID = 4095
case "New Mail":
toneID = 1000
case "Mail Sent":
toneID = 1001
case "Voicemail":
toneID = 1002
case "Received Message":
toneID = 1003
case "Sent Message":
toneID = 1004
default:
toneID = 1304
}
var toneIDSounf = UInt32(toneID)
AudioServicesPlaySystemSound(toneIDSounf)
}
*/
| mit | bb6fef48fd55ebc3a2847354a5e15f92 | 26.333333 | 339 | 0.670478 | 3.784615 | false | false | false | false |
benlangmuir/swift | stdlib/private/StdlibCollectionUnittest/LoggingWrappers.swift | 7 | 21969 | //===----------------------------------------------------------------------===//
//
// 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 StdlibUnittest
public protocol Wrapper {
associatedtype Base
init(wrapping base: Base)
var base: Base { get set }
}
public protocol LoggingType: Wrapper {
associatedtype Log : AnyObject
}
extension LoggingType {
public var log: Log.Type {
return Log.self
}
public var selfType: Any.Type {
return type(of: self)
}
}
//===----------------------------------------------------------------------===//
// Iterator
//===----------------------------------------------------------------------===//
public class IteratorLog {
public static func dispatchTester<I>(
_ iterator: I
) -> LoggingIterator<LoggingIterator<I>> {
return LoggingIterator(wrapping: LoggingIterator(wrapping: iterator))
}
public static var next = TypeIndexed(0)
}
public struct LoggingIterator<Base : IteratorProtocol> {
public var base: Base
}
extension LoggingIterator: LoggingType {
public typealias Log = IteratorLog
public init(wrapping base: Base) {
self.base = base
}
}
extension LoggingIterator: IteratorProtocol {
public mutating func next() -> Base.Element? {
Log.next[selfType] += 1
return base.next()
}
}
//===----------------------------------------------------------------------===//
// Sequence and Collection logs
//===----------------------------------------------------------------------===//
// FIXME: it's not clear if it's really worth this hierarchy. the
// test.log pattern requires all the static properties be at the top
// since Log is an associated type that cannot be refined in extensions
// that add functionality.
public class SequenceLogBase {
// Sequence
public static var makeIterator = TypeIndexed(0)
public static var underestimatedCount = TypeIndexed(0)
public static var dropFirst = TypeIndexed(0)
public static var dropLast = TypeIndexed(0)
public static var dropWhile = TypeIndexed(0)
public static var prefixWhile = TypeIndexed(0)
public static var prefixMaxLength = TypeIndexed(0)
public static var suffixMaxLength = TypeIndexed(0)
public static var withContiguousStorageIfAvailable = TypeIndexed(0)
public static var _customContainsEquatableElement = TypeIndexed(0)
public static var _copyToContiguousArray = TypeIndexed(0)
public static var _copyContents = TypeIndexed(0)
// Collection
public static var startIndex = TypeIndexed(0)
public static var endIndex = TypeIndexed(0)
public static var subscriptIndex = TypeIndexed(0)
public static var subscriptRange = TypeIndexed(0)
public static var _failEarlyRangeCheckIndex = TypeIndexed(0)
public static var _failEarlyRangeCheckRange = TypeIndexed(0)
public static var successor = TypeIndexed(0)
public static var formSuccessor = TypeIndexed(0)
public static var indices = TypeIndexed(0)
public static var isEmpty = TypeIndexed(0)
public static var count = TypeIndexed(0)
public static var _customIndexOfEquatableElement = TypeIndexed(0)
public static var advance = TypeIndexed(0)
public static var advanceLimit = TypeIndexed(0)
public static var distance = TypeIndexed(0)
// BidirectionalCollection
public static var predecessor = TypeIndexed(0)
public static var formPredecessor = TypeIndexed(0)
// MutableCollection
public static var subscriptIndexSet = TypeIndexed(0)
public static var subscriptRangeSet = TypeIndexed(0)
public static var partitionBy = TypeIndexed(0)
public static var _withUnsafeMutableBufferPointerIfSupported = TypeIndexed(0)
public static var _withUnsafeMutableBufferPointerIfSupportedNonNilReturns =
TypeIndexed(0)
public static var withContiguousMutableStorageIfAvailable = TypeIndexed(0)
public static var withContiguousMutableStorageIfAvailableNonNilReturns =
TypeIndexed(0)
// RangeReplaceableCollection
public static var init_ = TypeIndexed(0)
public static var initRepeating = TypeIndexed(0)
public static var initWithSequence = TypeIndexed(0)
public static var _customRemoveLast = TypeIndexed(0)
public static var _customRemoveLastN = TypeIndexed(0)
public static var append = TypeIndexed(0)
public static var appendContentsOf = TypeIndexed(0)
public static var insert = TypeIndexed(0)
public static var insertContentsOf = TypeIndexed(0)
public static var removeAll = TypeIndexed(0)
public static var removeAt = TypeIndexed(0)
public static var removeFirst = TypeIndexed(0)
public static var removeFirstN = TypeIndexed(0)
public static var removeSubrange = TypeIndexed(0)
public static var replaceSubrange = TypeIndexed(0)
public static var reserveCapacity = TypeIndexed(0)
}
public class SequenceLog : SequenceLogBase {
public static func dispatchTester<S>(
_ s: S
) -> LoggingSequence<LoggingSequence<S>> {
return LoggingSequence(wrapping: LoggingSequence(wrapping: s))
}
}
public class CollectionLog : SequenceLogBase {
public static func dispatchTester<C>(
_ c: C
) -> LoggingCollection<LoggingCollection<C>> {
return LoggingCollection(wrapping: LoggingCollection(wrapping: c))
}
}
public class BidirectionalCollectionLog : SequenceLogBase {
public static func dispatchTester<C>(
_ c: C
) -> LoggingBidirectionalCollection<LoggingBidirectionalCollection<C>> {
return LoggingBidirectionalCollection(
wrapping: LoggingBidirectionalCollection(wrapping: c))
}
}
public class MutableCollectionLog : SequenceLogBase {
public static func dispatchTester<C>(
_ c: C
) -> LoggingMutableCollection<LoggingMutableCollection<C>> {
return LoggingMutableCollection(
wrapping: LoggingMutableCollection(wrapping: c))
}
}
/// Data container to keep track of how many times each `Base` type calls methods
/// of `RangeReplaceableCollection`.
///
/// Each static variable is a mapping of Type -> Number of calls.
public class RangeReplaceableCollectionLog : SequenceLogBase {
public static func dispatchTester<C>(
_ rrc: C
) -> LoggingRangeReplaceableCollection<LoggingRangeReplaceableCollection<C>> {
return LoggingRangeReplaceableCollection(
wrapping: LoggingRangeReplaceableCollection(wrapping: rrc)
)
}
}
//===----------------------------------------------------------------------===//
// Sequence and Collection that count method calls
//===----------------------------------------------------------------------===//
/// Interposes between `Sequence` method calls to increment each method's
/// counter.
public struct LoggingSequence<Base : Sequence> {
public var base: Base
}
extension LoggingSequence: LoggingType {
// I know, I know. It doesn't matter though. The benefit of the whole logging
// class hierarchy is unclear...
public typealias Log = SequenceLog
public init(wrapping base: Base) {
self.base = base
}
}
extension LoggingSequence: Sequence {
public typealias Element = Base.Element
public typealias Iterator = LoggingIterator<Base.Iterator>
public func makeIterator() -> Iterator {
SequenceLog.makeIterator[selfType] += 1
return LoggingIterator(wrapping: base.makeIterator())
}
public var underestimatedCount: Int {
SequenceLog.underestimatedCount[selfType] += 1
return base.underestimatedCount
}
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
SequenceLog.withContiguousStorageIfAvailable[selfType] += 1
return try base.withContiguousStorageIfAvailable(body)
}
public func _customContainsEquatableElement(_ element: Element) -> Bool? {
SequenceLog._customContainsEquatableElement[selfType] += 1
return base._customContainsEquatableElement(element)
}
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
public func _copyToContiguousArray() -> ContiguousArray<Element> {
SequenceLog._copyToContiguousArray[selfType] += 1
return base._copyToContiguousArray()
}
/// Copy a Sequence into an array.
public func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
SequenceLog._copyContents[selfType] += 1
let (it,idx) = base._copyContents(initializing: buffer)
return (Iterator(wrapping: it),idx)
}
}
public typealias LoggingCollection<Base: Collection> = LoggingSequence<Base>
extension LoggingCollection: Collection {
public typealias Index = Base.Index
public typealias Indices = Base.Indices
public typealias SubSequence = Base.SubSequence
public var startIndex: Index {
CollectionLog.startIndex[selfType] += 1
return base.startIndex
}
public var endIndex: Index {
CollectionLog.endIndex[selfType] += 1
return base.endIndex
}
public subscript(position: Index) -> Element {
CollectionLog.subscriptIndex[selfType] += 1
return base[position]
}
public subscript(bounds: Range<Index>) -> SubSequence {
CollectionLog.subscriptRange[selfType] += 1
return base[bounds]
}
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
CollectionLog._failEarlyRangeCheckIndex[selfType] += 1
base._failEarlyRangeCheck(index, bounds: bounds)
}
public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {
CollectionLog._failEarlyRangeCheckRange[selfType] += 1
base._failEarlyRangeCheck(range, bounds: bounds)
}
public func index(after i: Index) -> Index {
CollectionLog.successor[selfType] += 1
return base.index(after: i)
}
public func formIndex(after i: inout Index) {
CollectionLog.formSuccessor[selfType] += 1
base.formIndex(after: &i)
}
public var indices: Indices {
CollectionLog.indices[selfType] += 1
return base.indices
}
public var isEmpty: Bool {
CollectionLog.isEmpty[selfType] += 1
return base.isEmpty
}
public var count: Int {
CollectionLog.count[selfType] += 1
return base.count
}
public func _customIndexOfEquatableElement(
_ element: Element
) -> Index?? {
CollectionLog._customIndexOfEquatableElement[selfType] += 1
return base._customIndexOfEquatableElement(element)
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
CollectionLog.advance[selfType] += 1
return base.index(i, offsetBy: n)
}
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
CollectionLog.advanceLimit[selfType] += 1
return base.index(i, offsetBy: n, limitedBy: limit)
}
public func distance(from start: Index, to end: Index) -> Int {
CollectionLog.distance[selfType] += 1
return base.distance(from: start, to: end)
}
}
public typealias LoggingBidirectionalCollection<
Base: BidirectionalCollection
> = LoggingCollection<Base>
extension LoggingBidirectionalCollection: BidirectionalCollection {
public func index(before i: Index) -> Index {
BidirectionalCollectionLog.predecessor[selfType] += 1
return base.index(before: i)
}
public func formIndex(before i: inout Index) {
BidirectionalCollectionLog.formPredecessor[selfType] += 1
base.formIndex(before: &i)
}
}
public typealias LoggingRandomAccessCollection<Base: RandomAccessCollection>
= LoggingBidirectionalCollection<Base>
extension LoggingRandomAccessCollection: RandomAccessCollection { }
public typealias LoggingMutableCollection<Base: MutableCollection>
= LoggingCollection<Base>
extension LoggingMutableCollection: MutableCollection {
public subscript(position: Index) -> Element {
get {
MutableCollectionLog.subscriptIndex[selfType] += 1
return base[position]
}
set {
MutableCollectionLog.subscriptIndexSet[selfType] += 1
base[position] = newValue
}
}
public subscript(bounds: Range<Index>) -> SubSequence {
get {
MutableCollectionLog.subscriptRange[selfType] += 1
return base[bounds]
}
set {
MutableCollectionLog.subscriptRangeSet[selfType] += 1
base[bounds] = newValue
}
}
public mutating func partition(
by belongsInSecondPartition: (Iterator.Element) throws -> Bool
) rethrows -> Index {
Log.partitionBy[selfType] += 1
return try base.partition(by: belongsInSecondPartition)
}
@available(*, deprecated, renamed: "withContiguousMutableStorageIfAvailable")
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
MutableCollectionLog._withUnsafeMutableBufferPointerIfSupported[selfType] += 1
let result = try base._withUnsafeMutableBufferPointerIfSupported(body)
if result != nil {
Log._withUnsafeMutableBufferPointerIfSupportedNonNilReturns[selfType] += 1
}
return result
}
public mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
MutableCollectionLog.withContiguousMutableStorageIfAvailable[selfType] += 1
let result = try base.withContiguousMutableStorageIfAvailable(body)
if result != nil {
Log.withContiguousMutableStorageIfAvailableNonNilReturns[selfType] += 1
}
return result
}
}
public typealias LoggingMutableBidirectionalCollection<
Base: MutableCollection & BidirectionalCollection
> = LoggingMutableCollection<Base>
public typealias LoggingMutableRandomAccessCollection<
Base: MutableCollection & RandomAccessCollection
> = LoggingMutableCollection<Base>
public typealias LoggingRangeReplaceableCollection<
Base: RangeReplaceableCollection
> = LoggingCollection<Base>
extension LoggingRangeReplaceableCollection: RangeReplaceableCollection {
public init() {
self.base = Base()
RangeReplaceableCollectionLog.init_[selfType] += 1
}
public init(repeating repeatedValue: Element, count: Int) {
self.base = Base(repeating: repeatedValue, count: count)
RangeReplaceableCollectionLog.initRepeating[selfType] += 1
}
public init<S : Sequence>(_ elements: S)
where S.Element == Element {
self.base = Base(elements)
RangeReplaceableCollectionLog.initWithSequence[selfType] += 1
}
public mutating func _customRemoveLast() -> Element? {
RangeReplaceableCollectionLog._customRemoveLast[selfType] += 1
return base._customRemoveLast()
}
public mutating func _customRemoveLast(_ n: Int) -> Bool {
RangeReplaceableCollectionLog._customRemoveLastN[selfType] += 1
return base._customRemoveLast(n)
}
public mutating func append(_ newElement: Element) {
RangeReplaceableCollectionLog.append[selfType] += 1
base.append(newElement)
}
public mutating func append<S : Sequence>(
contentsOf newElements: S
) where S.Element == Element {
RangeReplaceableCollectionLog.appendContentsOf[selfType] += 1
base.append(contentsOf: newElements)
}
public mutating func insert(
_ newElement: Element, at i: Index
) {
RangeReplaceableCollectionLog.insert[selfType] += 1
base.insert(newElement, at: i)
}
public mutating func insert<C : Collection>(
contentsOf newElements: C, at i: Index
) where C.Element == Element {
RangeReplaceableCollectionLog.insertContentsOf[selfType] += 1
base.insert(contentsOf: newElements, at: i)
}
public mutating func removeAll(keepingCapacity keepCapacity: Bool) {
RangeReplaceableCollectionLog.removeAll[selfType] += 1
base.removeAll(keepingCapacity: keepCapacity)
}
@discardableResult
public mutating func remove(at index: Index) -> Element {
RangeReplaceableCollectionLog.removeAt[selfType] += 1
return base.remove(at: index)
}
@discardableResult
public mutating func removeFirst() -> Element {
RangeReplaceableCollectionLog.removeFirst[selfType] += 1
return base.removeFirst()
}
public mutating func removeFirst(_ n: Int) {
RangeReplaceableCollectionLog.removeFirstN[selfType] += 1
base.removeFirst(n)
}
public mutating func removeSubrange(_ bounds: Range<Index>) {
RangeReplaceableCollectionLog.removeSubrange[selfType] += 1
base.removeSubrange(bounds)
}
public mutating func replaceSubrange<C : Collection>(
_ bounds: Range<Index>, with newElements: C
) where C.Element == Element {
RangeReplaceableCollectionLog.replaceSubrange[selfType] += 1
base.replaceSubrange(bounds, with: newElements)
}
public mutating func reserveCapacity(_ n: Int) {
RangeReplaceableCollectionLog.reserveCapacity[selfType] += 1
base.reserveCapacity(n)
}
}
public typealias LoggingRangeReplaceableBidirectionalCollection<
Base: BidirectionalCollection & RangeReplaceableCollection
> = LoggingRangeReplaceableCollection<Base>
public typealias LoggingRangeReplaceableRandomAccessCollection<
Base: RandomAccessCollection & RangeReplaceableCollection
> = LoggingRangeReplaceableCollection<Base>
//===----------------------------------------------------------------------===//
// Collections that count calls to `withContiguousMutableStorageIfAvailable`
//===----------------------------------------------------------------------===//
/// Interposes between `withContiguousMutableStorageIfAvailable` method calls
/// to increment a counter. Calls to this method from within dispatched methods
/// are uncounted by the standard logging collection wrapper.
public struct BufferAccessLoggingMutableCollection<
Base : MutableCollection
> {
public var base: Base
}
extension BufferAccessLoggingMutableCollection: LoggingType {
public typealias Log = MutableCollectionLog
public init(wrapping base: Base) {
self.base = base
}
}
extension BufferAccessLoggingMutableCollection: Sequence {
public typealias SubSequence = Base.SubSequence
public typealias Iterator = Base.Iterator
public typealias Element = Base.Element
public func makeIterator() -> Iterator {
return base.makeIterator()
}
}
extension BufferAccessLoggingMutableCollection: MutableCollection {
public typealias Index = Base.Index
public typealias Indices = Base.Indices
public var startIndex: Index {
return base.startIndex
}
public var endIndex: Index {
return base.endIndex
}
public var indices: Indices {
return base.indices
}
public subscript(position: Index) -> Element {
get {
return base[position]
}
set {
base[position] = newValue
}
}
public subscript(bounds: Range<Index>) -> SubSequence {
get {
return base[bounds]
}
set {
base[bounds] = newValue
}
}
public func index(after i: Index) -> Index {
return base.index(after: i)
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
return base.index(i, offsetBy: n)
}
public func distance(from start: Index, to end: Index) -> Int {
return base.distance(from: start, to: end)
}
@available(*, deprecated, renamed: "withContiguousMutableStorageIfAvailable")
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
Log._withUnsafeMutableBufferPointerIfSupported[selfType] += 1
let result = try base._withUnsafeMutableBufferPointerIfSupported(body)
if result != nil {
Log._withUnsafeMutableBufferPointerIfSupportedNonNilReturns[selfType] += 1
}
return result
}
public mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
Log.withContiguousMutableStorageIfAvailable[selfType] += 1
let result = try base.withContiguousMutableStorageIfAvailable(body)
if result != nil {
Log.withContiguousMutableStorageIfAvailableNonNilReturns[selfType] += 1
}
return result
}
}
public typealias BufferAccessLoggingMutableBidirectionalCollection<
Base: MutableCollection & BidirectionalCollection
> = BufferAccessLoggingMutableCollection<Base>
extension BufferAccessLoggingMutableBidirectionalCollection: BidirectionalCollection {
public func index(before i: Index) -> Index {
return base.index(before: i)
}
}
public typealias BufferAccessLoggingMutableRandomAccessCollection<
Base: MutableCollection & RandomAccessCollection
> = BufferAccessLoggingMutableCollection<Base>
//===----------------------------------------------------------------------===//
// Custom assertions
//===----------------------------------------------------------------------===//
public func expectCustomizable<T : LoggingType>(
_: T, _ counters: TypeIndexed<Int>,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) where
T.Base : LoggingType,
T.Log == T.Base.Log {
let newTrace = stackTrace.pushIf(showFrame, file: file, line: line)
expectNotEqual(0, counters[T.self], message(), stackTrace: newTrace)
expectEqual(
counters[T.self], counters[T.Base.self], message(), stackTrace: newTrace)
}
public func expectNotCustomizable<T : LoggingType>(
_: T, _ counters: TypeIndexed<Int>,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) where
T.Base : LoggingType,
T.Log == T.Base.Log {
let newTrace = stackTrace.pushIf(showFrame, file: file, line: line)
expectNotEqual(0, counters[T.self], message(), stackTrace: newTrace)
expectEqual(0, counters[T.Base.self], message(), stackTrace: newTrace)
}
| apache-2.0 | a30175376f150f47df4dd7f24a23e93a | 31.594955 | 86 | 0.709045 | 5.152205 | false | false | false | false |
deekshithbellare/Tweelight | Tweelight/Tweelight/Utility/TWNetwork.swift | 1 | 7590 | //
// TWNetwork.swift
// Tweelight
//
// Created by Deekshith Bellare on 22/08/15.
// Copyright © 2015 deekshithbellare. All rights reserved.
//
import Foundation
//
// TWNetwork.swift
// TwitterApp
// Created by Deekshith N M on 21/08/15.
// Copyright © 2015 Deekshith N M. All rights reserved.
//
import Foundation
import Accounts
import Social
let homeTimeineURL = "https://api.twitter.com/1.1/statuses/home_timeline.json"
let userProfileURL = "https://api.twitter.com/1.1/users/show.json"
let friendsListURL = "https://api.twitter.com/1.1/friends/list.json"
let followersListURL = "https://api.twitter.com/1.1/followers/list.json"
let followURL = "https://api.twitter.com/1.1/friendships/create.json"
let unfollowURL = "https://api.twitter.com/1.1/friendships/destroy.json"
let myErrorDomain = "com.deekshith.twitterAPP"
enum TWErrorCodes:Int {
case TwitterNoAccountsFound = 899
case JSONParsingError
}
/// Every netwrok response will will be sucessful or fail. This is a convinent enum which encapsulates network response or failure.
public enum TWNetworkResponse {
case Success(response:AnyObject)
case Error(error:NSError)
}
/// # TWNetworkProtocol
///
/// TWNetwork must adopt this protocol. It allows the class to perfrom a request based on the enum value of TWNetwork and fetch the data and return the result
/// - Returns: completionHandler which is of type TWNetworkResponse
protocol TWNetworkProtocol {
func performRequest(completionHandler:(TWNetworkResponse) -> ())
}
/// # Network Manager
///
/// The TWNetwork object encapsulates the fetching of data and related operations, providing a convenient template for you to make requests.
/// You send a request to fetch related services provided by the twitter API and get back the results using completion handler.
enum TWNetwork :TWNetworkProtocol
{
static var account :ACAccount?
case RequestAccess
case Timeline(parameters:Dictionary<String,String>)
case Profile(screenName:String)
case FriendsList(screenName:String,nextCursor:String)
case FollowersList(screenName:String,nextCursor:String)
case Follow(userName:String)
case UnFollow(userName:String)
func performRequest(completionHandler: (TWNetworkResponse) -> ()) {
switch self {
case .RequestAccess:
requestAccess(completionHandler)
case .Timeline(let parameters):
performSLRequest(homeTimeineURL, parameters: parameters, requestMethod:.GET, completionHandler: completionHandler)
case .Profile(let screenName):
performSLRequest(userProfileURL, parameters:
["screen_name":screenName],
requestMethod:.GET,
completionHandler: completionHandler)
case .FriendsList(let screenName,let nextCursor):
performSLRequest(friendsListURL,
parameters:["screen_name":screenName,"cursor":nextCursor],
requestMethod:.GET, completionHandler: completionHandler)
case .FollowersList(let screenName,let nextCursor):
performSLRequest(followersListURL, parameters:
["screen_name":screenName,"cursor":nextCursor],
requestMethod:.GET,
completionHandler: completionHandler)
case Follow(let userName):
performSLRequest(followURL,
parameters: ["screen_name":userName],
requestMethod:.POST,
completionHandler: completionHandler)
case UnFollow(let userName):
performSLRequest(unfollowURL,
parameters: ["screen_name":userName],
requestMethod:.POST,
completionHandler: completionHandler)
}
}
}
/// # Request Grant
///
/// Asks for the permission to access the twitter account stored in settings
/// - Returns: the handler to call when the request has completed. It rerurns the last account stored in settings.
/// If access to use single sign-on twitter is not provided, an error is returned.
/// If permission is given to access single sign-on and if no accounts are found, then TwitterNoAccountsFound custom NSError is returned
/// - Warning: It returns the last account even if more accoonts are present in the settings.
func requestAccess(completionHandler: (TWNetworkResponse) -> ()) {
let accountStore = ACAccountStore()
let accountType = accountStore.accountTypeWithAccountTypeIdentifier(
ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccountsWithType(accountType, options: nil) { (success, error) -> Void in
if success
{
let twitterAccounts = accountStore.accountsWithAccountType(accountType)
if twitterAccounts?.isEmpty == false {
let twitterAccount = twitterAccounts.last as! ACAccount
let myAccount = TWNetworkResponse.Success(response:twitterAccount)
TWNetwork.account = twitterAccount
completionHandler(myAccount)
}
else
{
let errorDictionary = [NSLocalizedDescriptionKey: "No twitter Account found. Please add in settings"]
let noAccountsFoundError = NSError(domain: myErrorDomain, code:TWErrorCodes.TwitterNoAccountsFound.rawValue,userInfo: errorDictionary)
completionHandler(TWNetworkResponse.Error(error:noAccountsFoundError))
}
}
else
{
completionHandler(TWNetworkResponse.Error(error: error))
}
}
}
/// # Timeline Fetch
/// [Twitter developer Website:Timeline](https://dev.twitter.com/rest/reference/get/statuses/user_timeline)
///
/// Returns a collection of the most recent Tweets posted by the user indicated by the screen_name or user_id parameters.
/// - Parameter parameters Dictionary containg the value for screenname and other options as sepcified in website
/// - Returns: the handler to call when the request has completed. It will either has timeline of tweets or NSError object
func performSLRequest(urlString:String,parameters:[String:String],requestMethod:SLRequestMethod,completionHandler: (TWNetworkResponse) -> ())
{
let url = NSURL(string: urlString)
let socailRequest =
SLRequest(forServiceType: SLServiceTypeTwitter,
requestMethod:requestMethod,
URL:url,
parameters:parameters)
socailRequest.account = TWNetwork.account
socailRequest.performRequestWithHandler { (data, response, error) -> Void in
if (error != nil) {
completionHandler(TWNetworkResponse.Error(error: error))
}
else
{
do {
let jsonResponse:AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options:.AllowFragments)
completionHandler(TWNetworkResponse.Success(response:jsonResponse!))
}
catch let caught as NSError {
completionHandler(TWNetworkResponse.Error(error: caught))
}
catch
{
let errorDictionary = [NSLocalizedDescriptionKey: "Parsing was unsucessful"]
let parserError = NSError(domain: myErrorDomain, code:TWErrorCodes.TwitterNoAccountsFound.rawValue,userInfo: errorDictionary)
completionHandler(TWNetworkResponse.Error(error:parserError))
}
}
}
} | mit | cbab7f160d76614a57ce0bc2f09222d6 | 39.153439 | 158 | 0.675145 | 5.120108 | false | false | false | false |
wireapp/wire-ios-sync-engine | Tests/Source/Integration/TextSearchTests.swift | 1 | 7848 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
import WireTesting
private class MockSearchDelegate: TextSearchQueryDelegate {
var results = [TextQueryResult]()
func textSearchQueryDidReceive(result: TextQueryResult) {
results.append(result)
}
}
class TextSearchTests: ConversationTestsBase {
func testThatItFindsAMessageSendRemotely() {
// Given
XCTAssertTrue(login())
let firstClient = user1.clients.anyObject() as! MockUserClient
let selfClient = selfUser.clients.anyObject() as! MockUserClient
// When
mockTransportSession.performRemoteChanges { _ in
let genericMessage = GenericMessage(content: Text(content: "Hello there!"))
do {
self.selfToUser1Conversation.encryptAndInsertData(from: firstClient, to: selfClient, data: try genericMessage.serializedData())
} catch {
XCTFail()
}
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
guard let convo = conversation(for: selfToUser1Conversation) else { return XCTFail("Undable to get conversation") }
let lastMessage = convo.lastMessage
XCTAssertEqual(lastMessage?.textMessageData?.messageText, "Hello there!")
// Then
verifyThatItCanSearch(for: "There", in: convo, andFinds: lastMessage as! ZMMessage)
}
func testThatItFindsAMessageEditedRemotely() {
// Given
XCTAssertTrue(login())
let firstClient = user1.clients.anyObject() as! MockUserClient
let selfClient = selfUser.clients.anyObject() as! MockUserClient
let nonce = UUID.create()
// When
mockTransportSession.performRemoteChanges { _ in
let genericMessage = GenericMessage(content: Text(content: "Hello there!"), nonce: nonce)
do {
self.selfToUser1Conversation.encryptAndInsertData(from: firstClient, to: selfClient, data: try genericMessage.serializedData())
} catch {
XCTFail()
}
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
guard let convo = conversation(for: selfToUser1Conversation) else { return XCTFail("Undable to get conversation") }
guard let lastMessage = convo.lastMessage else { return XCTFail("Undable to get message") }
XCTAssertEqual(lastMessage.textMessageData?.messageText, "Hello there!")
// And when
mockTransportSession.performRemoteChanges { _ in
let genericMessage = GenericMessage(content: MessageEdit(replacingMessageID: nonce, text: Text(content: "This is an edit!!")))
do {
self.selfToUser1Conversation.encryptAndInsertData(from: firstClient, to: selfClient, data: try genericMessage.serializedData())
} catch {
XCTFail()
}
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
guard let editedMessage = convo.lastMessage else { return XCTFail("Undable to get message") }
XCTAssertEqual(editedMessage.textMessageData?.messageText, "This is an edit!!")
// Then
verifyThatItCanSearch(for: "edit", in: convo, andFinds: editedMessage as! ZMMessage)
verifyThatItCanSearch(for: "Hello", in: convo, andFinds: nil)
}
func testThatItDoesFindAnEphemeralMessageSentRemotely() {
// Given
XCTAssertTrue(login())
let firstClient = user1.clients.anyObject() as! MockUserClient
let selfClient = selfUser.clients.anyObject() as! MockUserClient
let text = "This is an ephemeral message"
// When
mockTransportSession.performRemoteChanges { _ in
let genericMessage = GenericMessage(content: Text(content: text), expiresAfterTimeInterval: 300)
do {
self.selfToUser1Conversation.encryptAndInsertData(from: firstClient, to: selfClient, data: try genericMessage.serializedData())
} catch {
XCTFail()
}
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
guard let convo = conversation(for: selfToUser1Conversation) else { return XCTFail("Undable to get conversation") }
let lastMessage = convo.lastMessage
XCTAssertEqual(lastMessage?.textMessageData?.messageText, text)
// Then
verifyThatItCanSearch(for: "ephemeral", in: convo, andFinds: lastMessage as! ZMMessage)
}
func testThatItDoesNotFindAMessageDeletedRemotely() {
// Given
XCTAssertTrue(login())
let firstClient = user1.clients.anyObject() as! MockUserClient
let selfClient = selfUser.clients.anyObject() as! MockUserClient
let nonce = UUID.create()
// When
mockTransportSession.performRemoteChanges { _ in
let genericMessage = GenericMessage(content: Text(content: "Hello there!"), nonce: nonce)
do {
self.selfToUser1Conversation.encryptAndInsertData(from: firstClient, to: selfClient, data: try genericMessage.serializedData())
} catch {
XCTFail()
}
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
guard let convo = conversation(for: selfToUser1Conversation) else { return XCTFail("Undable to get conversation") }
let lastMessage = convo.lastMessage
XCTAssertEqual(lastMessage?.textMessageData?.messageText, "Hello there!")
// Then
verifyThatItCanSearch(for: "Hello", in: convo, andFinds: lastMessage as! ZMMessage)
// And when
mockTransportSession.performRemoteChanges { _ in
let genericMessage = GenericMessage(content: MessageDelete(messageId: nonce))
do {
self.selfToUser1Conversation.encryptAndInsertData(from: firstClient, to: selfClient, data: try genericMessage.serializedData())
} catch {
XCTFail()
}
}
// Then
verifyThatItCanSearch(for: "Hello", in: convo, andFinds: nil)
}
func verifyThatItCanSearch(for query: String, in conversation: ZMConversation, andFinds message: ZMMessage?, file: StaticString = #file, line: UInt = #line) {
// Given
let delegate = MockSearchDelegate()
let searchQuery = TextSearchQuery(conversation: conversation, query: query, delegate: delegate)
// When
searchQuery?.execute()
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5), file: file, line: line)
// Then
guard let result = delegate.results.last else { return XCTFail("No search result found", file: file, line: line) }
if let message = message {
XCTAssertEqual(result.matches.count, 1, file: file, line: line)
guard let match = result.matches.first else { return XCTFail("No match found", file: file, line: line) }
XCTAssertEqual(match.textMessageData?.messageText, message.textMessageData?.messageText, file: file, line: line)
} else {
XCTAssert(result.matches.isEmpty, file: file, line: line)
}
}
}
| gpl-3.0 | 4c5049dcb9b09b29d6ff264d865ca10c | 38.837563 | 162 | 0.661315 | 5.306288 | false | false | false | false |
ArtemGordinsky/Spotifree | Spotifree/DataManager.swift | 1 | 2930 | //
// DataManager.swift
// Spotifree
//
// Created by Eneas Rotterdam on 29.12.15.
// Copyright © 2015 Eneas Rotterdam. All rights reserved.
//
import Cocoa
let KEY_MENU_BAR_ICON_HIDDEN = "SFMenuBarIconHidden"
let KEY_SHOW_NOTIFICATIONS = "SFShowNotifications"
let KEY_POLLING_RATE = "SFPollingRate"
class DataManager : NSObject {
static let sharedData = DataManager()
private let appleScriptCmds = NSDictionary(contentsOfFile: Bundle.main.path(forResource: "AppleScriptCmds", ofType: "plist")!)!
override init() {
super.init()
if isInLoginItems() && !isLoginItemPathCorrect() {
removeLoginItem()
addLoginItem()
}
let defaults = [KEY_MENU_BAR_ICON_HIDDEN : false, KEY_SHOW_NOTIFICATIONS : false, KEY_POLLING_RATE : 0.3] as [String : Any]
UserDefaults.standard.register(defaults: defaults)
if !UserDefaults.standard.bool(forKey: "SUHasLaunchedBefore") {
addLoginItem()
}
}
func pollingRate() -> Double {
return UserDefaults.standard.double(forKey: KEY_POLLING_RATE)
}
func isMenuBarIconHidden() -> Bool {
return UserDefaults.standard.bool(forKey: KEY_MENU_BAR_ICON_HIDDEN)
}
func setMenuBarIconHidden(_ hidden : Bool) {
UserDefaults.standard.set(hidden, forKey: KEY_MENU_BAR_ICON_HIDDEN)
UserDefaults.standard.synchronize()
}
func toggleLoginItem() {
isInLoginItems() ? removeLoginItem() : addLoginItem()
}
func addLoginItem() {
NSAppleScript(source: String(format: appleScriptCmds["addLoginItem"] as! String, Bundle.main.bundlePath))?.executeAndReturnError(nil)
}
func removeLoginItem() {
NSAppleScript(source: appleScriptCmds["removeLoginItem"] as! String)?.executeAndReturnError(nil)
}
func isInLoginItems() -> Bool{
var isInItems = true
let desc = NSAppleScript(source: appleScriptCmds["isInLoginItems"] as! String)?.executeAndReturnError(nil)
if let desc = desc {
isInItems = desc.booleanValue
}
return isInItems
}
func isLoginItemPathCorrect() -> Bool {
var isCorrect = true
let desc = NSAppleScript(source: String(format: appleScriptCmds["isLoginItemPathCorrect"] as! String, Bundle.main.bundlePath))?.executeAndReturnError(nil)
if let desc = desc {
isCorrect = desc.booleanValue
}
return isCorrect
}
func toggleShowNotifications() {
let showNotifications = UserDefaults.standard.bool(forKey: KEY_SHOW_NOTIFICATIONS)
UserDefaults.standard.set(!showNotifications, forKey: KEY_SHOW_NOTIFICATIONS)
UserDefaults.standard.synchronize()
}
func shouldShowNofifications() -> Bool {
return UserDefaults.standard.bool(forKey: KEY_SHOW_NOTIFICATIONS)
}
}
| mit | bb52a5f6461801d28c752cff97278043 | 31.910112 | 162 | 0.651758 | 4.562305 | false | false | false | false |
cafielo/iOS_BigNerdRanch_5th | Chap6_WorldTrotter/WorldTrotter/MapViewController.swift | 1 | 1842 | //
// MapViewController.swift
// WorldTrotter
//
// Created by Joonwon Lee on 7/20/16.
// Copyright © 2016 Joonwon Lee. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController {
var mapView: MKMapView!
override func loadView() {
super.loadView()
mapView = MKMapView()
view = mapView
let segmentedControl = UISegmentedControl(items: ["Standard", "Hybrid", "Satellite"])
segmentedControl.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self, action: #selector(mapTypeChanged), forControlEvents: .ValueChanged)
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(segmentedControl)
// Constraint
let topConstraint = segmentedControl.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor, constant: 8)
let margins = view.layoutMarginsGuide
let leadingConstraint = segmentedControl.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)
let trailingConstraint = segmentedControl.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor)
topConstraint.active = true
leadingConstraint.active = true
trailingConstraint.active = true
}
func mapTypeChanged(segmentedControl: UISegmentedControl) {
switch segmentedControl.selectedSegmentIndex {
case 0:
mapView.mapType = .Standard
case 1:
mapView.mapType = .Hybrid
case 2:
mapView.mapType = .Satellite
default:
break
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
| mit | 16581c90a21ec9ed7fec393e909fe2a4 | 29.683333 | 120 | 0.66377 | 6.055921 | false | false | false | false |
AEvgeniy/Sample | Sample/Library/Controls/TextField.swift | 1 | 1962 | //
// TextField.swift
// Authentication
//
// Created by Evgeniy Abashkin on 7/23/17.
// Copyright © 2017 com.evgeniy. All rights reserved.
//
import UIKit
@IBDesignable
class TextField: UITextField {
private var underlineView: UIView!
@IBInspectable var underlineWidth: CGFloat = 1
@IBInspectable var insetLeft: CGFloat = 0
@IBInspectable var insetRight: CGFloat = 0
@IBInspectable var underlineColor: UIColor = UIColor.black {
didSet {
updateUnderline()
}
}
@IBInspectable var underlineColorError: UIColor = UIColor.red
override init(frame: CGRect) {
super.init(frame: frame)
prepare()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepare()
}
private func prepare() {
underlineView = UIView(frame: CGRect.zero)
addSubview(underlineView)
updateUnderline()
}
private func updateUnderline() {
underlineView.backgroundColor = isHighlightedError ? underlineColorError : underlineColor
underlineView.frame = CGRect(x: 0,
y: frame.height - underlineWidth,
width: frame.width,
height: underlineWidth)
}
override func layoutSubviews() {
super.layoutSubviews()
updateUnderline()
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return textInsets(forBounds: bounds)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return textInsets(forBounds: bounds)
}
private func textInsets(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + insetLeft, y: 0,
width: bounds.width - insetLeft - insetRight, height: bounds.height)
}
var isHighlightedError = false {
didSet {
updateUnderline()
}
}
}
| mit | c67676e951c01cef91abf791b376850d | 24.467532 | 97 | 0.611423 | 5.080311 | false | false | false | false |
steelwheels/KiwiControls | Source/Graphics/KCVertices.swift | 1 | 1197 | /**
* @file KCVertices.swift
* @brief Define KCVertices data structure
* @par Copyright
* Copyright (C) 2016 Steel Wheels Project
*/
#if os(iOS)
import UIKit
#endif
import Foundation
public struct KCVertices
{
private var mVertices : Array<CGPoint>
private var mBounds : CGRect
public init(){
mVertices = []
mBounds = CGRect.zero
}
public var vertices: Array<CGPoint> { return mVertices }
public init(veritces vs: Array<CGPoint>){
if vs.count > 0 {
mVertices = vs
mBounds = KCVertices.allocateBoundRect(vertices: vs)
} else {
mVertices = []
mBounds = CGRect.zero
}
}
private static func allocateBoundRect(vertices vs: Array<CGPoint>) -> CGRect {
if vs.count == 0 {
return CGRect.zero
}
/* Check 1st point */
let o0 = vs[0]
var xmin = o0.x
var xmax = xmin
var ymin = o0.y
var ymax = ymin
/* Check 2nd, 3rd, ... */
let count = vs.count
for i in 1..<count {
let on = vs[i]
if on.x < xmin {
xmin = on.x
} else if xmax < on.x {
xmax = on.x
}
if on.y < ymin {
ymin = on.y
} else if ymax < on.y {
ymax = on.y
}
}
return CGRect(x: xmin, y: ymin, width: xmax-xmin, height: ymax-ymin)
}
}
| lgpl-2.1 | 2bdf378227e5bae745bba56edc7389a6 | 18.306452 | 79 | 0.615706 | 2.764434 | false | false | false | false |
loudnate/LoopKit | LoopKit/KeychainManager.swift | 1 | 9277 | //
// KeychainManager.swift
// Loop
//
// Created by Nate Racklyeft on 6/26/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
import Security
public enum KeychainManagerError: Error {
case add(OSStatus)
case copy(OSStatus)
case delete(OSStatus)
case unknownResult
}
/**
Influenced by https://github.com/marketplacer/keychain-swift
*/
public struct KeychainManager {
typealias Query = [String: NSObject]
public init() { }
var accessibility: CFString = kSecAttrAccessibleAfterFirstUnlock
var accessGroup: String?
public struct InternetCredentials: Equatable {
public let username: String
public let password: String
public let url: URL
public init(username: String, password: String, url: URL) {
self.username = username
self.password = password
self.url = url
}
}
// MARK: - Convenience methods
private func query(by class: CFString) -> Query {
var query: Query = [kSecClass as String: `class`]
if let accessGroup = accessGroup {
query[kSecAttrAccessGroup as String] = accessGroup as NSObject?
}
return query
}
private func queryForGenericPassword(by service: String) -> Query {
var query = self.query(by: kSecClassGenericPassword)
query[kSecAttrService as String] = service as NSObject?
return query
}
private func queryForInternetPassword(account: String? = nil, url: URL? = nil, label: String? = nil) -> Query {
var query = self.query(by: kSecClassInternetPassword)
if let account = account {
query[kSecAttrAccount as String] = account as NSObject?
}
if let url = url, let components = URLComponents(url: url, resolvingAgainstBaseURL: true) {
for (key, value) in components.keychainAttributes {
query[key] = value
}
}
if let label = label {
query[kSecAttrLabel as String] = label as NSObject?
}
return query
}
private func updatedQuery(_ query: Query, withPassword password: String) throws -> Query {
var query = query
guard let value = password.data(using: String.Encoding.utf8) else {
throw KeychainManagerError.add(errSecDecode)
}
query[kSecValueData as String] = value as NSObject?
query[kSecAttrAccessible as String] = accessibility
return query
}
func delete(_ query: Query) throws {
let statusCode = SecItemDelete(query as CFDictionary)
guard statusCode == errSecSuccess || statusCode == errSecItemNotFound else {
throw KeychainManagerError.delete(statusCode)
}
}
// MARK: – Generic Passwords
public func replaceGenericPassword(_ password: String?, forService service: String) throws {
var query = queryForGenericPassword(by: service)
try delete(query)
guard let password = password else {
return
}
query = try updatedQuery(query, withPassword: password)
let statusCode = SecItemAdd(query as CFDictionary, nil)
guard statusCode == errSecSuccess else {
throw KeychainManagerError.add(statusCode)
}
}
public func getGenericPasswordForService(_ service: String) throws -> String {
var query = queryForGenericPassword(by: service)
query[kSecReturnData as String] = kCFBooleanTrue
query[kSecMatchLimit as String] = kSecMatchLimitOne
var result: AnyObject?
let statusCode = SecItemCopyMatching(query as CFDictionary, &result)
guard statusCode == errSecSuccess else {
throw KeychainManagerError.copy(statusCode)
}
guard let passwordData = result as? Data, let password = String(data: passwordData, encoding: String.Encoding.utf8) else {
throw KeychainManagerError.unknownResult
}
return password
}
// MARK – Internet Passwords
public func setInternetPassword(_ password: String, account: String, atURL url: URL, label: String? = nil) throws {
var query = try updatedQuery(queryForInternetPassword(account: account, url: url, label: label), withPassword: password)
query[kSecAttrAccount as String] = account as NSObject?
if let components = URLComponents(url: url, resolvingAgainstBaseURL: true) {
for (key, value) in components.keychainAttributes {
query[key] = value
}
}
if let label = label {
query[kSecAttrLabel as String] = label as NSObject?
}
let statusCode = SecItemAdd(query as CFDictionary, nil)
guard statusCode == errSecSuccess else {
throw KeychainManagerError.add(statusCode)
}
}
public func replaceInternetCredentials(_ credentials: InternetCredentials?, forAccount account: String) throws {
let query = queryForInternetPassword(account: account)
try delete(query)
if let credentials = credentials {
try setInternetPassword(credentials.password, account: credentials.username, atURL: credentials.url)
}
}
public func replaceInternetCredentials(_ credentials: InternetCredentials?, forLabel label: String) throws {
let query = queryForInternetPassword(label: label)
try delete(query)
if let credentials = credentials {
try setInternetPassword(credentials.password, account: credentials.username, atURL: credentials.url, label: label)
}
}
public func replaceInternetCredentials(_ credentials: InternetCredentials?, forURL url: URL) throws {
let query = queryForInternetPassword(url: url)
try delete(query)
if let credentials = credentials {
try setInternetPassword(credentials.password, account: credentials.username, atURL: credentials.url)
}
}
public func getInternetCredentials(account: String? = nil, url: URL? = nil, label: String? = nil) throws -> InternetCredentials {
var query = queryForInternetPassword(account: account, url: url, label: label)
query[kSecReturnData as String] = kCFBooleanTrue
query[kSecReturnAttributes as String] = kCFBooleanTrue
query[kSecMatchLimit as String] = kSecMatchLimitOne
var result: AnyObject?
let statusCode: OSStatus = SecItemCopyMatching(query as CFDictionary, &result)
guard statusCode == errSecSuccess else {
throw KeychainManagerError.copy(statusCode)
}
if let result = result as? [AnyHashable: Any], let passwordData = result[kSecValueData as String] as? Data,
let password = String(data: passwordData, encoding: String.Encoding.utf8),
let url = URLComponents(keychainAttributes: result)?.url,
let username = result[kSecAttrAccount as String] as? String
{
return InternetCredentials(username: username, password: password, url: url)
}
throw KeychainManagerError.unknownResult
}
}
private enum SecurityProtocol {
case http
case https
init?(scheme: String?) {
switch scheme?.lowercased() {
case "http"?:
self = .http
case "https"?:
self = .https
default:
return nil
}
}
init?(secAttrProtocol: CFString) {
if secAttrProtocol == kSecAttrProtocolHTTP {
self = .http
} else if secAttrProtocol == kSecAttrProtocolHTTPS {
self = .https
} else {
return nil
}
}
var scheme: String {
switch self {
case .http:
return "http"
case .https:
return "https"
}
}
var secAttrProtocol: CFString {
switch self {
case .http:
return kSecAttrProtocolHTTP
case .https:
return kSecAttrProtocolHTTPS
}
}
}
private extension URLComponents {
init?(keychainAttributes: [AnyHashable: Any]) {
self.init()
if let secAttProtocol = keychainAttributes[kSecAttrProtocol as String] {
scheme = SecurityProtocol(secAttrProtocol: secAttProtocol as! CFString)?.scheme
}
host = keychainAttributes[kSecAttrServer as String] as? String
if let port = keychainAttributes[kSecAttrPort as String] as? Int, port > 0 {
self.port = port
}
if let path = keychainAttributes[kSecAttrPath as String] as? String {
self.path = path
}
}
var keychainAttributes: [String: NSObject] {
var query: [String: NSObject] = [:]
if let `protocol` = SecurityProtocol(scheme: scheme) {
query[kSecAttrProtocol as String] = `protocol`.secAttrProtocol
}
if let host = host {
query[kSecAttrServer as String] = host as NSObject
}
if let port = port {
query[kSecAttrPort as String] = port as NSObject
}
if !path.isEmpty {
query[kSecAttrPath as String] = path as NSObject
}
return query
}
}
| mit | c55f2194bede4123be4c9a2070839582 | 28.338608 | 133 | 0.630676 | 5.173549 | false | false | false | false |
erkie/ApiModel | Source/FormDataEncoding.swift | 1 | 2511 | //
// FormDataEncoding.swift
// ApiModel
//
// Created by Erik Rothoff Andersson on 2015-26-09.
//
//
import Foundation
import Alamofire
open class FileUpload {
open var fileName: String
open var mimeType: String
open var data: Data
public init(fileName: String, mimeType: String, data: Data) {
self.fileName = fileName
self.mimeType = mimeType
self.data = data
}
}
open class FormDataEncoding: ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
let formData = MultipartFormData()
addParametersToData(parameters ?? [:], formData: formData)
let fullData = try formData.encode()
request.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")
request.setValue(String(formData.contentLength), forHTTPHeaderField: "Content-Length")
request.httpBody = fullData
request.httpShouldHandleCookies = true
return request
}
}
func addParametersToData(_ parameters: [String:Any], formData: MultipartFormData, keyPrefix: String = "") {
for (key, value) in parameters {
let formKey = keyPrefix.isEmpty ? key : "\(keyPrefix)[\(key)]"
// FileUpload
if let fileUpload = value as? FileUpload {
formData.append(fileUpload.data, withName: formKey, fileName: fileUpload.fileName, mimeType: fileUpload.mimeType)
// NSData
} else if let valueData = value as? Data {
formData.append(valueData, withName: formKey, fileName: "data.dat", mimeType: "application/octet-stream")
// Nested hash
} else if let nestedParameters = value as? [String:AnyObject] {
addParametersToData(nestedParameters, formData: formData, keyPrefix: formKey)
// Nested array
} else if let arrayData = value as? [AnyObject] {
var asHash: [String:AnyObject] = [:]
for (index, arrayValue) in arrayData.enumerated() {
asHash[String(index)] = arrayValue
}
addParametersToData(asHash, formData: formData, keyPrefix: formKey)
// Anything else, cast it to a string
} else if let dataString = String(describing: value).data(using: String.Encoding.utf8) {
formData.append(dataString, withName: key)
}
}
}
| mit | 04f8aafff7c753ab675aefdfd7d70c20 | 34.366197 | 125 | 0.633214 | 4.866279 | false | false | false | false |
groovelab/SwiftBBS | SwiftBBS/SwiftBBS Server/UserRepository.swift | 1 | 6828 | //
// UserRepository.swift
// SwiftBBS
//
// Created by Takeo Namba on 2016/01/09.
// Copyright GrooveLab
//
import PerfectLib
import MySQL
enum UserProvider : String {
case Github = "github"
case Facebook = "facebook"
case Google = "google"
case Line = "line"
}
// MARK: entity
struct UserEntity {
var id: UInt?
var name: String
var password: String?
var provider: UserProvider?
var providerUserId: String?
var providerUserName: String?
var apnsDeviceToken: String?
var createdAt: String?
var updatedAt: String?
init(id: UInt?, name: String, password: String?) {
self.id = id
self.name = name
self.password = password
}
init(id: UInt?, provider: UserProvider, providerUserId: String, providerUserName: String) {
self.id = id
self.name = provider.rawValue + "@" + providerUserName
self.password = ""
self.provider = provider
self.providerUserId = providerUserId
self.providerUserName = providerUserName
}
init(id: UInt?, name: String, password: String?, provider: UserProvider?, providerUserId: String?, providerUserName: String?, apnsDeviceToken: String?, createdAt: String?, updatedAt: String?) {
self.id = id
self.name = name
self.password = password
self.provider = provider
self.providerUserId = providerUserId
self.providerUserName = providerUserName
self.apnsDeviceToken = apnsDeviceToken
self.createdAt = createdAt
self.updatedAt = updatedAt
}
func toDictionary() -> [String: Any] {
return [
"id": id ?? 0,
"name": name,
"password": "",// exclude password
"provider": provider?.rawValue ?? "",
"provider_user_id": providerUserId ?? "",
"provider_user_name": providerUserName ?? "",
"createdAt": createdAt ?? "",
"updatedAt": updatedAt ?? "",
]
}
}
// MARK: - repository
class UserRepository : Repository {
func insert(entity: UserEntity) throws -> UInt {
let sql = "INSERT INTO user (name, \(entity.password != nil ? "password," : "") "
+ "\(entity.provider != nil ? "provider," : "") \(entity.providerUserId != nil ? "provider_user_id," : "") \(entity.providerUserName != nil ? "provider_user_name," : "") "
+ "created_at, updated_at) VALUES "
+ "(?, \(entity.password != nil ? "?," : "") "
+ "\(entity.provider != nil ? "?," : "") \(entity.providerUserId != nil ? "?," : "") \(entity.providerUserName != nil ? "?," : "") \(nowSql), \(nowSql))"
var params: Params = [ entity.name ]
if let password = entity.password {
params.append(password.sha1)
}
if let provider = entity.provider {
params.append(provider.rawValue)
}
if let providerUserId = entity.providerUserId {
params.append(providerUserId)
}
if let providerUserName = entity.providerUserName {
params.append(providerUserName)
}
return try executeInsertSql(sql, params: params)
}
func update(entity: UserEntity) throws -> UInt {
guard let id = entity.id else {
return 0
}
let sql = "UPDATE user SET name = ?, \(!String.isEmpty(entity.password) ? "password = ?," : "") \(!String.isEmpty(entity.apnsDeviceToken) ? "apns_device_token = ?," : "") updated_at = \(nowSql) WHERE id = ?"
var params: Params = [ entity.name ]
if let password = entity.password where !String.isEmpty(entity.password) {
params.append(password.sha1)
}
if let apnsDeviceToken = entity.apnsDeviceToken where !String.isEmpty(entity.apnsDeviceToken) {
params.append(apnsDeviceToken)
}
params.append(id)
return try executeUpdateSql(sql, params: params)
}
func delete(entity: UserEntity) throws -> UInt {
guard let id = entity.id else {
return 0
}
let sql = "DELETE FROM user WHERE id = ?"
return try executeDeleteSql(sql, params: [ id ])
}
func findById(id: UInt) throws -> UserEntity? {
let sql = "SELECT id, name, provider, provider_user_id, provider_user_name, apns_device_token, created_at, updated_at FROM user WHERE id = ?"
let rows = try executeSelectSql(sql, params: [ id ])
guard let row = rows.first else {
return nil
}
return createEntityFromRow(row)
}
func findByName(name: String, password: String) throws -> UserEntity? {
let sql = "SELECT id, name, provider, provider_user_id, provider_user_name, apns_device_token, created_at, updated_at FROM user WHERE name = ? AND password = ?"
let rows = try executeSelectSql(sql, params: [ name, password.sha1 ])
guard let row = rows.first else {
return nil
}
return createEntityFromRow(row)
}
func findByProviderId(providerId: String, provider: UserProvider) throws -> UserEntity? {
let sql = "SELECT id, name, provider, provider_user_id, provider_user_name, apns_device_token, created_at, updated_at FROM user WHERE provider = ? AND provider_user_id = ?"
let rows = try executeSelectSql(sql, params: [ provider.rawValue, providerId ])
guard let row: Row = rows.first else {
return nil
}
return createEntityFromRow(row)
}
func selectByIds(ids: Set<UInt>) throws -> [UserEntity] {
let formatedIdsString = ids.map { String($0) }.joinWithSeparator(",")
let sql = "SELECT id, name, provider, provider_user_id, provider_user_name, apns_device_token, created_at, updated_at FROM user WHERE id IN (\(formatedIdsString))"
let rows = try executeSelectSql(sql)
return rows.map { row in
return createEntityFromRow(row)
}
}
// row contains
// id, name, provider, provider_user_id, provider_user_name, apns_device_token, created_at, updated_at
private func createEntityFromRow(row: Row) -> UserEntity {
let createdAt = row[6] as? String
return UserEntity(
id: UInt(row[0] as! UInt32),
name: row[1] as! String,
password: "",
provider: (row[2] as? String) != nil ? UserProvider(rawValue: (row[2] as? String)!) : nil,
providerUserId: row[3] as? String,
providerUserName: row[4] as? String,
apnsDeviceToken: row[5] as? String,
// createdAt: row[6] as? String,
createdAt: createdAt, // work around for linux
updatedAt: row[7] as? String
)
}
}
| mit | 05ff226c988d955be7eef79a68063f81 | 36.516484 | 215 | 0.59007 | 4.297042 | false | false | false | false |
Ataluer/ASRoam | ASRoam/ASRoam/Class/Home/View/PageContentView.swift | 1 | 5958 | //
// PageContentView.swift
// ASRoam
//
// Created by Yanfei Yu on 2017/6/5.
// Copyright © 2017年 Ataluer. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate: class {
func pageContentView(progress: CGFloat, currentIndex: Int, targetIndex: Int)
}
class PageContentView: UIView, UICollectionViewDataSource, UICollectionViewDelegate{
weak var delegate: PageContentViewDelegate?
//MARK: -定义属性
fileprivate var childVcs: [UIViewController]
fileprivate var parentVc: UIViewController
//开始的偏移量
fileprivate var startOfSetX: CGFloat = 0
fileprivate var signWeatherIsDraw:Bool = false
// //MARK: -懒加载collectionView
fileprivate lazy var collectionView: UICollectionView = {[weak self] in
//1.创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
//2.创建UICollectionView
let collectionView = UICollectionView(frame: (self?.bounds)!, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.backgroundColor = UIColor.white
//注册单元格
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "HomePageCell")
return collectionView
}();
//MARK: -重写构造函数
init(frame: CGRect, childVcs: [UIViewController], parentViewController: UIViewController) {
self.childVcs = childVcs
self.parentVc = parentViewController
super.init(frame: frame)
//setupUI
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageContentView {
fileprivate func setupUI() {
//1.将子控制器添加到父控制器
for childVc in childVcs {
parentVc.addChildViewController(childVc)
}
//2.添加UICollectionView
addSubview(collectionView)
collectionView.delegate = self as UICollectionViewDelegate
collectionView.dataSource = self as UICollectionViewDataSource
// collectionView.decelerationRate = 01
}
}
//MARK: -遵守UICollectionViewDatasource
extension PageContentView {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomePageCell", for: indexPath)
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVc = childVcs[indexPath.row]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
//MARK: -遵守UICollectionViewDelegate
extension PageContentView {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
startOfSetX = scrollView.contentOffset.x
// print("startOfSetX****\(startOfSetX)")
signWeatherIsDraw = true
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if signWeatherIsDraw == false {
return
}
//1.定义需要的数据
var progress: CGFloat = 0
var sourceIndex: Int = 0
var targetIndex: Int = 0
//2.判断是左滑还是右滑
let currentOfSetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
// print("****\(currentOfSetX)")
//越界直接返回
if currentOfSetX < 0 {
sourceIndex = 0
targetIndex = 0
return
}else if currentOfSetX > scrollViewW*CGFloat(self.childVcs.count - 1){
sourceIndex = self.childVcs.count - 1
targetIndex = self.childVcs.count - 1
return
}
if currentOfSetX > startOfSetX {//左滑
//1.计算progress
progress = currentOfSetX/scrollViewW - floor(currentOfSetX/scrollViewW)
//2.sourceIndex
sourceIndex = Int(currentOfSetX/scrollViewW)
//3.targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= self.childVcs.count {
targetIndex = self.childVcs.count - 1
}
if currentOfSetX - startOfSetX == scrollViewW {
progress = 1
targetIndex = sourceIndex
}
}else{//右hua
//1.计算progress
progress = 1 - currentOfSetX/scrollViewW + floor(currentOfSetX/scrollViewW)
//2.targetIndex
targetIndex = Int(currentOfSetX/scrollViewW)
//3.sourceIndex
sourceIndex = targetIndex + 1
if sourceIndex >= self.childVcs.count {
sourceIndex = self.childVcs.count - 1
}
}
// print("sourceIndex:\(sourceIndex) targetIndex:\(targetIndex) /n \(progress)")
delegate?.pageContentView(progress: progress, currentIndex: sourceIndex, targetIndex: targetIndex)
}
}
//MARK: -对外暴露的方法
extension PageContentView {
func setCurrentIndex(currentIndex: Int) {
signWeatherIsDraw = false
let indexPath = IndexPath(row: currentIndex, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
}
}
| mit | b60245f9723f217f382073cb954721e9 | 28.080402 | 121 | 0.620874 | 5.612997 | false | false | false | false |
e-how/kingTrader | kingTrader/Pods/CryptoSwift/CryptoSwift/UInt8Extension.swift | 20 | 2428 | //
// ByteExtension.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 07/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import Foundation
/** casting */
extension UInt8 {
/** cast because UInt8(<UInt32>) because std initializer crash if value is > byte */
static func withValue(v:UInt64) -> UInt8 {
let tmp = v & 0xFF
return UInt8(tmp)
}
static func withValue(v:UInt32) -> UInt8 {
let tmp = v & 0xFF
return UInt8(tmp)
}
static func withValue(v:UInt16) -> UInt8 {
let tmp = v & 0xFF
return UInt8(tmp)
}
}
/** Bits */
extension UInt8 {
init(bits: [Bit]) {
self.init(integerFromBitsArray(bits) as UInt8)
}
/** array of bits */
func bits() -> [Bit] {
let totalBitsCount = sizeofValue(self) * 8
var bitsArray = [Bit](count: totalBitsCount, repeatedValue: Bit.Zero)
for j in 0..<totalBitsCount {
let bitVal:UInt8 = 1 << UInt8(totalBitsCount - 1 - j)
let check = self & bitVal
if (check != 0) {
bitsArray[j] = Bit.One;
}
}
return bitsArray
}
func bits() -> String {
var s = String()
let arr:[Bit] = self.bits()
for (idx,b) in arr.enumerate() {
s += (b == Bit.One ? "1" : "0")
if ((idx + 1) % 8 == 0) { s += " " }
}
return s
}
}
/** Shift bits */
extension UInt8 {
/** Shift bits to the right. All bits are shifted (including sign bit) */
mutating func shiftRight(count: UInt8) -> UInt8 {
if (self == 0) {
return self;
}
let bitsCount = UInt8(sizeof(UInt8) * 8)
if (count >= bitsCount) {
return 0
}
let maxBitsForValue = UInt8(floor(log2(Double(self) + 1)))
let shiftCount = Swift.min(count, maxBitsForValue - 1)
var shiftedValue:UInt8 = 0;
for bitIdx in 0..<bitsCount {
let byte = 1 << bitIdx
if ((self & byte) == byte) {
shiftedValue = shiftedValue | (byte >> shiftCount)
}
}
self = shiftedValue
return self
}
}
/** shift right and assign with bits truncation */
func &>> (lhs: UInt8, rhs: UInt8) -> UInt8 {
var l = lhs;
l.shiftRight(rhs)
return l
} | apache-2.0 | bfb2c467a6c4848baec464f811fcd195 | 23.049505 | 88 | 0.514003 | 3.787832 | false | false | false | false |
xuzhou524/Convenient-Swift | Pods/Alamofire/Source/ServerTrustEvaluation.swift | 3 | 27331 | //
// ServerTrustPolicy.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for managing the mapping of `ServerTrustEvaluating` values to given hosts.
open class ServerTrustManager {
/// Determines whether all hosts for this `ServerTrustManager` must be evaluated. `true` by default.
public let allHostsMustBeEvaluated: Bool
/// The dictionary of policies mapped to a particular host.
public let evaluators: [String: ServerTrustEvaluating]
/// Initializes the `ServerTrustManager` instance with the given evaluators.
///
/// Since different servers and web services can have different leaf certificates, intermediate and even root
/// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
/// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
/// pinning for host3 and disabling evaluation for host4.
///
/// - Parameters:
/// - allHostsMustBeEvaluated: The value determining whether all hosts for this instance must be evaluated. `true`
/// by default.
/// - evaluators: A dictionary of evaluators mappend to hosts.
public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String: ServerTrustEvaluating]) {
self.allHostsMustBeEvaluated = allHostsMustBeEvaluated
self.evaluators = evaluators
}
/// Returns the `ServerTrustEvaluating` value for the given host, if one is set.
///
/// By default, this method will return the policy that perfectly matches the given host. Subclasses could override
/// this method and implement more complex mapping implementations such as wildcards.
///
/// - Parameter host: The host to use when searching for a matching policy.
///
/// - Returns: The `ServerTrustEvaluating` value for the given host if found, `nil` otherwise.
/// - Throws: `AFError.serverTrustEvaluationFailed` if `allHostsMustBeEvaluated` is `true` and no matching
/// evaluators are found.
open func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? {
guard let evaluator = evaluators[host] else {
if allHostsMustBeEvaluated {
throw AFError.serverTrustEvaluationFailed(reason: .noRequiredEvaluator(host: host))
}
return nil
}
return evaluator
}
}
/// A protocol describing the API used to evaluate server trusts.
public protocol ServerTrustEvaluating {
#if os(Linux)
// Implement this once Linux has API for evaluating server trusts.
#else
/// Evaluates the given `SecTrust` value for the given `host`.
///
/// - Parameters:
/// - trust: The `SecTrust` value to evaluate.
/// - host: The host for which to evaluate the `SecTrust` value.
///
/// - Returns: A `Bool` indicating whether the evaluator considers the `SecTrust` value valid for `host`.
func evaluate(_ trust: SecTrust, forHost host: String) throws
#endif
}
// MARK: - Server Trust Evaluators
/// An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the
/// host provided by the challenge. Applications are encouraged to always validate the host in production environments
/// to guarantee the validity of the server's certificate chain.
public final class DefaultTrustEvaluator: ServerTrustEvaluating {
private let validateHost: Bool
/// Creates a `DefaultTrustEvalutor`.
///
/// - Parameter validateHost: Determines whether or not the evaluator should validate the host. `true` by default.
public init(validateHost: Bool = true) {
self.validateHost = validateHost
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
if validateHost {
try trust.af.performValidation(forHost: host)
}
try trust.af.performDefaultValidation(forHost: host)
}
}
/// An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate
/// the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates.
/// Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS
/// 10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production
/// environments to guarantee the validity of the server's certificate chain.
public final class RevocationTrustEvaluator: ServerTrustEvaluating {
/// Represents the options to be use when evaluating the status of a certificate.
/// Only Revocation Policy Constants are valid, and can be found in [Apple's documentation](https://developer.apple.com/documentation/security/certificate_key_and_trust_services/policies/1563600-revocation_policy_constants).
public struct Options: OptionSet {
/// Perform revocation checking using the CRL (Certification Revocation List) method.
public static let crl = Options(rawValue: kSecRevocationCRLMethod)
/// Consult only locally cached replies; do not use network access.
public static let networkAccessDisabled = Options(rawValue: kSecRevocationNetworkAccessDisabled)
/// Perform revocation checking using OCSP (Online Certificate Status Protocol).
public static let ocsp = Options(rawValue: kSecRevocationOCSPMethod)
/// Prefer CRL revocation checking over OCSP; by default, OCSP is preferred.
public static let preferCRL = Options(rawValue: kSecRevocationPreferCRL)
/// Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a
/// "best attempt" basis, where failure to reach the server is not considered fatal.
public static let requirePositiveResponse = Options(rawValue: kSecRevocationRequirePositiveResponse)
/// Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the
/// certificate and the value of `preferCRL`.
public static let any = Options(rawValue: kSecRevocationUseAnyAvailableMethod)
/// The raw value of the option.
public let rawValue: CFOptionFlags
/// Creates an `Options` value with the given `CFOptionFlags`.
///
/// - Parameter rawValue: The `CFOptionFlags` value to initialize with.
public init(rawValue: CFOptionFlags) {
self.rawValue = rawValue
}
}
private let performDefaultValidation: Bool
private let validateHost: Bool
private let options: Options
/// Creates a `RevocationTrustEvaluator`.
///
/// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use
/// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates.
///
/// - Parameters:
/// - performDefaultValidation: Determines whether default validation should be performed in addition to
/// evaluating the pinned certificates. `true` by default.
/// - validateHost: Determines whether or not the evaluator should validate the host, in addition
/// to performing the default evaluation, even if `performDefaultValidation` is
/// `false`. `true` by default.
/// - options: The `Options` to use to check the revocation status of the certificate. `.any`
/// by default.
public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any) {
self.performDefaultValidation = performDefaultValidation
self.validateHost = validateHost
self.options = options
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
if performDefaultValidation {
try trust.af.performDefaultValidation(forHost: host)
}
if validateHost {
try trust.af.performValidation(forHost: host)
}
try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in
AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options))
}
}
}
/// Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned
/// certificates match one of the server certificates. By validating both the certificate chain and host, certificate
/// pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks.
/// Applications are encouraged to always validate the host and require a valid certificate chain in production
/// environments.
public final class PinnedCertificatesTrustEvaluator: ServerTrustEvaluating {
private let certificates: [SecCertificate]
private let acceptSelfSignedCertificates: Bool
private let performDefaultValidation: Bool
private let validateHost: Bool
/// Creates a `PinnedCertificatesTrustEvaluator`.
///
/// - Parameters:
/// - certificates: The certificates to use to evalute the trust. All `cer`, `crt`, and `der`
/// certificates in `Bundle.main` by default.
/// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaulation, allowing
/// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE
/// FALSE IN PRODUCTION!
/// - performDefaultValidation: Determines whether default validation should be performed in addition to
/// evaluating the pinned certificates. `true` by default.
/// - validateHost: Determines whether or not the evaluator should validate the host, in addition
/// to performing the default evaluation, even if `performDefaultValidation` is
/// `false`. `true` by default.
public init(certificates: [SecCertificate] = Bundle.main.af.certificates,
acceptSelfSignedCertificates: Bool = false,
performDefaultValidation: Bool = true,
validateHost: Bool = true) {
self.certificates = certificates
self.acceptSelfSignedCertificates = acceptSelfSignedCertificates
self.performDefaultValidation = performDefaultValidation
self.validateHost = validateHost
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
guard !certificates.isEmpty else {
throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound)
}
if acceptSelfSignedCertificates {
try trust.af.setAnchorCertificates(certificates)
}
if performDefaultValidation {
try trust.af.performDefaultValidation(forHost: host)
}
if validateHost {
try trust.af.performValidation(forHost: host)
}
let serverCertificatesData = Set(trust.af.certificateData)
let pinnedCertificatesData = Set(certificates.af.data)
let pinnedCertificatesInServerData = !serverCertificatesData.isDisjoint(with: pinnedCertificatesData)
if !pinnedCertificatesInServerData {
throw AFError.serverTrustEvaluationFailed(reason: .certificatePinningFailed(host: host,
trust: trust,
pinnedCertificates: certificates,
serverCertificates: trust.af.certificates))
}
}
}
/// Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned
/// public keys match one of the server certificate public keys. By validating both the certificate chain and host,
/// public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks.
/// Applications are encouraged to always validate the host and require a valid certificate chain in production
/// environments.
public final class PublicKeysTrustEvaluator: ServerTrustEvaluating {
private let keys: [SecKey]
private let performDefaultValidation: Bool
private let validateHost: Bool
/// Creates a `PublicKeysTrustEvaluator`.
///
/// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use
/// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates.
///
/// - Parameters:
/// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all
/// certificates included in the main bundle.
/// - performDefaultValidation: Determines whether default validation should be performed in addition to
/// evaluating the pinned certificates. `true` by default.
/// - validateHost: Determines whether or not the evaluator should validate the host, in addition to
/// performing the default evaluation, even if `performDefaultValidation` is `false`.
/// `true` by default.
public init(keys: [SecKey] = Bundle.main.af.publicKeys,
performDefaultValidation: Bool = true,
validateHost: Bool = true) {
self.keys = keys
self.performDefaultValidation = performDefaultValidation
self.validateHost = validateHost
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
guard !keys.isEmpty else {
throw AFError.serverTrustEvaluationFailed(reason: .noPublicKeysFound)
}
if performDefaultValidation {
try trust.af.performDefaultValidation(forHost: host)
}
if validateHost {
try trust.af.performValidation(forHost: host)
}
let pinnedKeysInServerKeys: Bool = {
for serverPublicKey in trust.af.publicKeys {
for pinnedPublicKey in keys {
if serverPublicKey == pinnedPublicKey {
return true
}
}
}
return false
}()
if !pinnedKeysInServerKeys {
throw AFError.serverTrustEvaluationFailed(reason: .publicKeyPinningFailed(host: host,
trust: trust,
pinnedKeys: keys,
serverKeys: trust.af.publicKeys))
}
}
}
/// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the
/// evaluators consider it valid.
public final class CompositeTrustEvaluator: ServerTrustEvaluating {
private let evaluators: [ServerTrustEvaluating]
/// Creates a `CompositeTrustEvaluator`.
///
/// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust.
public init(evaluators: [ServerTrustEvaluating]) {
self.evaluators = evaluators
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
try evaluators.evaluate(trust, forHost: host)
}
}
/// Disables all evaluation which in turn will always consider any server trust as valid.
///
/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!**
public final class DisabledEvaluator: ServerTrustEvaluating {
/// Creates an instance.
public init() {}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {}
}
// MARK: - Extensions
public extension Array where Element == ServerTrustEvaluating {
#if os(Linux)
// Add this same convenience method for Linux.
#else
/// Evaluates the given `SecTrust` value for the given `host`.
///
/// - Parameters:
/// - trust: The `SecTrust` value to evaluate.
/// - host: The host for which to evaluate the `SecTrust` value.
///
/// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`.
func evaluate(_ trust: SecTrust, forHost host: String) throws {
for evaluator in self {
try evaluator.evaluate(trust, forHost: host)
}
}
#endif
}
extension Bundle: AlamofireExtended {}
public extension AlamofireExtension where ExtendedType: Bundle {
/// Returns all valid `cer`, `crt`, and `der` certificates in the bundle.
var certificates: [SecCertificate] {
return paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in
guard
let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData,
let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil }
return certificate
}
}
/// Returns all public keys for the valid certificates in the bundle.
var publicKeys: [SecKey] {
return certificates.af.publicKeys
}
/// Returns all pathnames for the resources identified by the provided file extensions.
///
/// - Parameter types: The filename extensions locate.
///
/// - Returns: All pathnames for the given filename extensions.
func paths(forResourcesOfTypes types: [String]) -> [String] {
return Array(Set(types.flatMap { type.paths(forResourcesOfType: $0, inDirectory: nil) }))
}
}
extension SecTrust: AlamofireExtended {}
public extension AlamofireExtension where ExtendedType == SecTrust {
/// Attempts to validate `self` using the policy provided and transforming any error produced using the closure passed.
///
/// - Parameters:
/// - policy: The `SecPolicy` used to evaluate `self`.
/// - errorProducer: The closure used transform the failed `OSStatus` and `SecTrustResultType`.
/// - Throws: Any error from applying the `policy`, or the result of `errorProducer` if validation fails.
func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws {
try apply(policy: policy).af.validate(errorProducer: errorProducer)
}
/// Applies a `SecPolicy` to `self`, throwing if it fails.
///
/// - Parameter policy: The `SecPolicy`.
///
/// - Returns: `self`, with the policy applied.
/// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.policyApplicationFailed` reason.
func apply(policy: SecPolicy) throws -> SecTrust {
let status = SecTrustSetPolicies(type, policy)
guard status.af.isSuccess else {
throw AFError.serverTrustEvaluationFailed(reason: .policyApplicationFailed(trust: type,
policy: policy,
status: status))
}
return type
}
/// Validate `self`, passing any failure values through `errorProducer`.
///
/// - Parameter errorProducer: The closure used to transform the failed `OSStatus` and `SecTrustResultType` into an
/// `Error`.
/// - Throws: The `Error` produced by the `errorProducer` closure.
func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws {
var result = SecTrustResultType.invalid
let status = SecTrustEvaluate(type, &result)
guard status.af.isSuccess && result.af.isSuccess else {
throw errorProducer(status, result)
}
}
/// Sets a custom certificate chain on `self`, allowing full validation of a self-signed certificate and its chain.
///
/// - Parameter certificates: The `SecCertificate`s to add to the chain.
/// - Throws: Any error produced when applying the new certificate chain.
func setAnchorCertificates(_ certificates: [SecCertificate]) throws {
// Add additional anchor certificates.
let status = SecTrustSetAnchorCertificates(type, certificates as CFArray)
guard status.af.isSuccess else {
throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: status,
certificates: certificates))
}
// Reenable system anchor certificates.
let systemStatus = SecTrustSetAnchorCertificatesOnly(type, true)
guard systemStatus.af.isSuccess else {
throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: systemStatus,
certificates: certificates))
}
}
/// The public keys contained in `self`.
var publicKeys: [SecKey] {
return certificates.af.publicKeys
}
/// The `SecCertificate`s contained i `self`.
var certificates: [SecCertificate] {
return (0..<SecTrustGetCertificateCount(type)).compactMap { index in
SecTrustGetCertificateAtIndex(type, index)
}
}
/// The `Data` values for all certificates contained in `self`.
var certificateData: [Data] {
return certificates.af.data
}
/// Validates `self` after applying `SecPolicy.af.default`. This evaluation does not validate the hostname.
///
/// - Parameter host: The hostname, used only in the error output if validation fails.
/// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason.
func performDefaultValidation(forHost host: String) throws {
try validate(policy: SecPolicy.af.default) { status, result in
AFError.serverTrustEvaluationFailed(reason: .defaultEvaluationFailed(output: .init(host, type, status, result)))
}
}
/// Validates `self` after applying `SecPolicy.af.hostname(host)`, which performs the default validation as well as
/// hostname validation.
///
/// - Parameter host: The hostname to use in the validation.
/// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason.
func performValidation(forHost host: String) throws {
try validate(policy: SecPolicy.af.hostname(host)) { status, result in
AFError.serverTrustEvaluationFailed(reason: .hostValidationFailed(output: .init(host, type, status, result)))
}
}
}
extension SecPolicy: AlamofireExtended {}
public extension AlamofireExtension where ExtendedType == SecPolicy {
/// Creates a `SecPolicy` instance which will validate server certificates but not require a host name match.
static let `default` = SecPolicyCreateSSL(true, nil)
/// Creates a `SecPolicy` instance which will validate server certificates and much match the provided hostname.
///
/// - Parameter hostname: The hostname to validate against.
///
/// - Returns: The `SecPolicy`.
static func hostname(_ hostname: String) -> SecPolicy {
return SecPolicyCreateSSL(true, hostname as CFString)
}
/// Creates a `SecPolicy` which checks the revocation of certificates.
///
/// - Parameter options: The `RevocationTrustEvaluator.Options` for evaluation.
///
/// - Returns: The `SecPolicy`.
/// - Throws: An `AFError.serverTrustEvaluationFailed` error with reason `.revocationPolicyCreationFailed`
/// if the policy cannot be created.
static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy {
guard let policy = SecPolicyCreateRevocation(options.rawValue) else {
throw AFError.serverTrustEvaluationFailed(reason: .revocationPolicyCreationFailed)
}
return policy
}
}
extension Array: AlamofireExtended {}
public extension AlamofireExtension where ExtendedType == [SecCertificate] {
/// All `Data` values for the contained `SecCertificate`s.
var data: [Data] {
return type.map { SecCertificateCopyData($0) as Data }
}
/// All public `SecKey` values for the contained `SecCertificate`s.
var publicKeys: [SecKey] {
return type.compactMap { $0.af.publicKey }
}
}
extension SecCertificate: AlamofireExtended {}
public extension AlamofireExtension where ExtendedType == SecCertificate {
/// The public key for `self`, if it can be extracted.
var publicKey: SecKey? {
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
let trustCreationStatus = SecTrustCreateWithCertificates(type, policy, &trust)
guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil }
return SecTrustCopyPublicKey(createdTrust)
}
}
extension OSStatus: AlamofireExtended {}
public extension AlamofireExtension where ExtendedType == OSStatus {
/// Returns whether `self` is `errSecSuccess`.
var isSuccess: Bool { return type == errSecSuccess }
}
extension SecTrustResultType: AlamofireExtended {}
public extension AlamofireExtension where ExtendedType == SecTrustResultType {
/// Returns whether `self is `.unspecified` or `.proceed`.
var isSuccess: Bool {
return (type == .unspecified || type == .proceed)
}
}
| mit | a7c36ad0842efbdc4c4b1f6b0e1141be | 47.631673 | 228 | 0.658849 | 5.429281 | false | false | false | false |
icharny/CommonUtils | CommonUtils/UIViewExtensions.swift | 1 | 5438 | public struct InnerShadowDirection: OptionSet {
public init(rawValue: Int) {
self.rawValue = rawValue
}
public let rawValue: Int
public static let north = InnerShadowDirection(rawValue: 1 << 0)
public static let east = InnerShadowDirection(rawValue: 1 << 1)
public static let south = InnerShadowDirection(rawValue: 1 << 2)
public static let west = InnerShadowDirection(rawValue: 1 << 3)
}
public extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor? {
get {
if let borderColor = layer.borderColor {
return UIColor(cgColor: borderColor)
} else {
return nil
}
}
set {
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable var shadowColor: UIColor? {
get {
if let shadowColor = layer.shadowColor {
return UIColor(cgColor: shadowColor)
} else {
return nil
}
}
set {
layer.shadowColor = newValue?.cgColor
}
}
@IBInspectable var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = max(0, min(1, newValue)) // bound within [0, 1]
}
}
@IBInspectable var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
@IBInspectable var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
@IBInspectable var masksToBounds: Bool {
get {
return layer.masksToBounds
}
set {
layer.masksToBounds = newValue
}
}
private static let innerShadowViewTag = 4_663_774
func removeInnerShadow() {
subviews.filter { $0.tag == UIView.innerShadowViewTag }
.first?
.removeFromSuperview()
}
func addInnerShadow(radius: CGFloat,
color: UIColor,
fade: Bool = true,
directions: InnerShadowDirection) {
removeInnerShadow()
addSubview(createShadowView(radius: radius,
color: color,
fade: fade,
directions: directions))
}
private func createShadowView(radius: CGFloat,
color: UIColor,
fade: Bool,
directions: InnerShadowDirection) -> UIView {
let shadowView = PassThroughView(frame: bounds)
shadowView.backgroundColor = UIColor.clear
shadowView.tag = UIView.innerShadowViewTag
var shadow: CAGradientLayer
let colors = [color.cgColor, fade ? UIColor.clear.cgColor : color.cgColor]
if directions.contains(.north) {
shadow = CAGradientLayer()
shadow.colors = colors
shadow.startPoint = CGPoint(x: 0.5, y: 0.0)
shadow.endPoint = CGPoint(x: 0.5, y: 1.0)
shadow.frame = CGRect(x: 0, y: 0, width: bounds.size.width, height: radius)
shadowView.layer.addSublayer(shadow)
}
if directions.contains(.east) {
shadow = CAGradientLayer()
shadow.colors = colors
shadow.startPoint = CGPoint(x: 1.0, y: 0.5)
shadow.endPoint = CGPoint(x: 0.0, y: 0.5)
shadow.frame = CGRect(x: bounds.size.width - radius, y: 0, width: radius, height: bounds.size.height)
shadowView.layer.addSublayer(shadow)
}
if directions.contains(.south) {
shadow = CAGradientLayer()
shadow.colors = colors
shadow.startPoint = CGPoint(x: 0.5, y: 1.0)
shadow.endPoint = CGPoint(x: 0.5, y: 0.0)
shadow.frame = CGRect(x: 0, y: bounds.size.height - radius, width: bounds.size.width, height: radius)
shadowView.layer.addSublayer(shadow)
}
if directions.contains(.west) {
shadow = CAGradientLayer()
shadow.colors = colors
shadow.startPoint = CGPoint(x: 0.0, y: 0.5)
shadow.endPoint = CGPoint(x: 1.0, y: 0.5)
shadow.frame = CGRect(x: 0, y: 0, width: radius, height: bounds.size.height)
shadowView.layer.addSublayer(shadow)
}
return shadowView
}
var isShown: Bool {
get {
return !isHidden
}
set {
isHidden = !newValue
}
}
func loadViewFromNib() -> UIView? {
return loadViewFromNib(type: type(of: self))
}
func loadViewFromNib(type: AnyClass) -> UIView? {
let nib = UINib(nibName: String(describing: type), bundle: Bundle(for: type))
let view = nib.instantiate(withOwner: self, options: nil).first as? UIView
return view
}
}
| mit | ac096fddb555d4467f3070f504bd3cfa | 28.879121 | 113 | 0.535123 | 4.912376 | false | false | false | false |
eoger/firefox-ios | Sync/BookmarkPayload.swift | 2 | 16684 | /* 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 Storage
import XCGLogger
import SwiftyJSON
private let log = Logger.syncLogger
public protocol MirrorItemable {
func toMirrorItem(_ modified: Timestamp) -> BookmarkMirrorItem
}
extension BookmarkMirrorItem {
func asPayload() -> BookmarkBasePayload {
return BookmarkType.somePayloadFromJSON(self.asJSON())
}
func asPayloadWithChildren(_ children: [GUID]?) -> BookmarkBasePayload {
let remappedChildren: [GUID]?
if let children = children {
if BookmarkRoots.RootGUID == self.guid {
// Only the root contains roots, and so only its children
// need to be translated.
remappedChildren = children.map(BookmarkRoots.translateOutgoingRootGUID)
} else {
remappedChildren = children
}
} else {
remappedChildren = nil
}
let json = self.asJSONWithChildren(remappedChildren)
return BookmarkType.somePayloadFromJSON(json)
}
}
/**
* Hierarchy:
* - BookmarkBasePayload
* \_ FolderPayload
* \_ LivemarkPayload
* \_ SeparatorPayload
* \_ BookmarkPayload
* \_ BookmarkQueryPayload
*/
public enum BookmarkType: String {
case livemark
case separator
case folder
case bookmark
case query
case microsummary // Dead: now a bookmark.
// The result might be invalid, but it won't be nil.
public static func somePayloadFromJSON(_ json: JSON) -> BookmarkBasePayload {
return payloadFromJSON(json) ?? BookmarkBasePayload(json)
}
public static func payloadFromJSON(_ json: JSON) -> BookmarkBasePayload? {
if json["deleted"].bool ?? false {
// Deleted records won't have a type.
return BookmarkBasePayload(json)
}
guard let typeString = json["type"].string else {
return nil
}
guard let type = BookmarkType(rawValue: typeString) else {
return nil
}
switch type {
case microsummary:
fallthrough
case bookmark:
return BookmarkPayload(json)
case folder:
return FolderPayload(json)
case livemark:
return LivemarkPayload(json)
case separator:
return SeparatorPayload(json)
case query:
return BookmarkQueryPayload(json)
}
}
public static func isValid(_ type: String?) -> Bool {
guard let type = type else {
return false
}
return BookmarkType(rawValue: type) != nil
}
}
open class LivemarkPayload: BookmarkBasePayload {
open var feedURI: String? {
return self["feedUri"].string
}
open var siteURI: String? {
return self["siteUri"].string
}
override open func isValid() -> Bool {
if !super.isValid() {
return false
}
return self.hasRequiredStringFields(["feedUri", "siteUri"])
}
override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool {
guard let p = obj as? LivemarkPayload else {
return false
}
if !super.equalPayloads(p) {
return false
}
if self.deleted {
return true
}
if self.feedURI != p.feedURI {
return false
}
if self.siteURI != p.siteURI {
return false
}
return true
}
override open func toMirrorItem(_ modified: Timestamp) -> BookmarkMirrorItem {
if self.deleted {
return BookmarkMirrorItem.deleted(.livemark, guid: self.id, modified: modified)
}
return BookmarkMirrorItem.livemark(
self.id,
dateAdded: self["dateAdded"].uInt64,
modified: modified,
hasDupe: self.hasDupe,
// TODO: these might need to be weakened if real-world data is dirty.
parentID: self["parentid"].stringValue,
parentName: self["parentName"].string,
title: self["title"].string,
description: self["description"].string,
feedURI: self.feedURI!,
siteURI: self.siteURI!
)
}
}
open class SeparatorPayload: BookmarkBasePayload {
override open func isValid() -> Bool {
if !super.isValid() {
return false
}
if !self["pos"].isInt() {
log.warning("Separator \(self.id) missing pos.")
return false
}
return true
}
override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool {
guard let p = obj as? SeparatorPayload else {
return false
}
if !super.equalPayloads(p) {
return false
}
if self.deleted {
return true
}
if self["pos"].int != p["pos"].int {
return false
}
return true
}
override open func toMirrorItem(_ modified: Timestamp) -> BookmarkMirrorItem {
if self.deleted {
return BookmarkMirrorItem.deleted(.separator, guid: self.id, modified: modified)
}
return BookmarkMirrorItem.separator(
self.id,
dateAdded: self["dateAdded"].uInt64,
modified: modified,
hasDupe: self.hasDupe,
// TODO: these might need to be weakened if real-world data is dirty.
parentID: self["parentid"].string!,
parentName: self["parentName"].string,
pos: self["pos"].int!
)
}
}
open class FolderPayload: BookmarkBasePayload {
fileprivate var childrenAreValid: Bool {
return self.hasStringArrayField("children")
}
override open func isValid() -> Bool {
if !super.isValid() {
return false
}
if !self.hasRequiredStringFields(["title"]) {
log.warning("Folder \(self.id) missing title.")
return false
}
if !self.hasOptionalStringFields(["description"]) {
log.warning("Folder \(self.id) missing string description.")
return false
}
if !self.childrenAreValid {
log.warning("Folder \(self.id) has invalid children.")
return false
}
return true
}
open var children: [String] {
return self["children"].arrayValue.map { $0.string! }
}
override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool {
guard let p = obj as? FolderPayload else {
return false
}
if !super.equalPayloads(p) {
return false
}
if self.deleted {
return true
}
if self["title"].string != p["title"].string {
return false
}
if self["description"].string != p["description"].string {
return false
}
if self.children != p.children {
return false
}
return true
}
override open func toMirrorItem(_ modified: Timestamp) -> BookmarkMirrorItem {
if self.deleted {
return BookmarkMirrorItem.deleted(.folder, guid: self.id, modified: modified)
}
return BookmarkMirrorItem.folder(
self.id,
dateAdded: self["dateAdded"].uInt64,
modified: modified,
hasDupe: self.hasDupe,
// TODO: these might need to be weakened if real-world data is dirty.
parentID: self["parentid"].string!,
parentName: self["parentName"].string,
title: self["title"].string!,
description: self["description"].string,
children: self.children
)
}
}
open class BookmarkPayload: BookmarkBasePayload {
fileprivate static let requiredBookmarkStringFields = ["bmkUri"]
// Title *should* be required, but can be missing for queries. Great.
fileprivate static let optionalBookmarkStringFields = ["title", "keyword", "description"]
fileprivate static let optionalBookmarkBooleanFields = ["loadInSidebar"]
override open func isValid() -> Bool {
if !super.isValid() {
return false
}
if !self.hasRequiredStringFields(BookmarkPayload.requiredBookmarkStringFields) {
log.warning("Bookmark \(self.id) missing required string field.")
return false
}
if !self.hasStringArrayField("tags") {
log.warning("Bookmark \(self.id) missing tags array. We'll replace with an empty array.")
// Ignore.
}
if !self.hasOptionalStringFields(BookmarkPayload.optionalBookmarkStringFields) {
return false
}
return self.hasOptionalBooleanFields(BookmarkPayload.optionalBookmarkBooleanFields)
}
override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool {
guard let p = obj as? BookmarkPayload else {
return false
}
if !super.equalPayloads(p) {
return false
}
if self.deleted {
return true
}
if !BookmarkPayload.requiredBookmarkStringFields.every({ p[$0].string! == self[$0].string! }) {
return false
}
// TODO: compare optional fields.
if Set(self.tags) != Set(p.tags) {
return false
}
if self["loadInSidebar"].bool != p["loadInSidebar"].bool {
return false
}
return true
}
lazy var tags: [String] = {
return self["tags"].arrayValue.compactMap { $0.string }
}()
lazy var tagsString: String = {
if self["tags"].isArray() {
return self["tags"].stringValue() ?? "[]"
}
return "[]"
}()
override open func toMirrorItem(_ modified: Timestamp) -> BookmarkMirrorItem {
if self.deleted {
return BookmarkMirrorItem.deleted(.bookmark, guid: self.id, modified: modified)
}
return BookmarkMirrorItem.bookmark(
self.id,
dateAdded: self["dateAdded"].uInt64,
modified: modified,
hasDupe: self.hasDupe,
// TODO: these might need to be weakened if real-world data is dirty.
parentID: self["parentid"].string!,
parentName: self["parentName"].string,
title: self["title"].string ?? "",
description: self["description"].string,
URI: self["bmkUri"].string!,
tags: self.tagsString, // Stringify it so we can put the array in the DB.
keyword: self["keyword"].string
)
}
}
open class BookmarkQueryPayload: BookmarkPayload {
override open func isValid() -> Bool {
if !super.isValid() {
return false
}
if !self.hasOptionalStringFields(["queryId", "folderName"]) {
log.warning("Query \(self.id) missing queryId or folderName.")
return false
}
return true
}
override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool {
guard let p = obj as? BookmarkQueryPayload else {
return false
}
if !super.equalPayloads(p) {
return false
}
if self.deleted {
return true
}
if self["folderName"].string != p["folderName"].string {
return false
}
if self["queryId"].string != p["queryId"].string {
return false
}
return true
}
override open func toMirrorItem(_ modified: Timestamp) -> BookmarkMirrorItem {
if self.deleted {
return BookmarkMirrorItem.deleted(.query, guid: self.id, modified: modified)
}
return BookmarkMirrorItem.query(
self.id,
dateAdded: self["dateAdded"].uInt64,
modified: modified,
hasDupe: self.hasDupe,
parentID: self["parentid"].string!,
parentName: self["parentName"].string,
title: self["title"].string ?? "",
description: self["description"].string,
URI: self["bmkUri"].string!,
tags: self.tagsString, // Stringify it so we can put the array in the DB.
keyword: self["keyword"].string,
folderName: self["folderName"].string,
queryID: self["queryID"].string
)
}
}
open class BookmarkBasePayload: CleartextPayloadJSON, MirrorItemable {
fileprivate static let requiredStringFields: [String] = ["parentid", "type"]
fileprivate static let optionalBooleanFields: [String] = ["hasDupe"]
static func deletedPayload(_ guid: GUID) -> BookmarkBasePayload {
let remappedGUID = BookmarkRoots.translateOutgoingRootGUID(guid)
return BookmarkBasePayload(JSON(["id": remappedGUID, "deleted": true]))
}
func hasStringArrayField(_ name: String) -> Bool {
guard let arr = self[name].array else {
return false
}
return arr.every { $0.isString() }
}
func hasRequiredStringFields(_ fields: [String]) -> Bool {
return fields.every { self[$0].isString() }
}
func hasOptionalStringFields(_ fields: [String]) -> Bool {
return fields.every { field in
let val = self[field]
// Yup, 404 is not found, so this means "string or nothing".
let valid = val.isString() || val.isNull() || val.isError()
if !valid {
log.debug("Field \(field) is invalid: \(val).")
}
return valid
}
}
func hasOptionalBooleanFields(_ fields: [String]) -> Bool {
return fields.every { field in
let val = self[field]
// Yup, 404 is not found, so this means "boolean or nothing".
let valid = val.isBool() || val.isNull() || val.error?.code == 404
if !valid {
log.debug("Field \(field) is invalid: \(val).")
}
return valid
}
}
override open func isValid() -> Bool {
if !super.isValid() {
return false
}
if self["deleted"].bool ?? false {
return true
}
// If not deleted, we must be a specific, known, type!
if !BookmarkType.isValid(self["type"].string) {
return false
}
if !(self["parentName"].isString() || self.id == "places") {
if self["parentid"].string! == "places" {
log.debug("Accepting root with missing parent name.")
} else {
// Bug 1318414.
log.warning("Accepting bookmark with missing parent name.")
}
}
if !self.hasRequiredStringFields(BookmarkBasePayload.requiredStringFields) {
log.warning("Item missing required string field.")
return false
}
return self.hasOptionalBooleanFields(BookmarkBasePayload.optionalBooleanFields)
}
open var hasDupe: Bool {
return self["hasDupe"].bool ?? false
}
/**
* This only makes sense for valid payloads.
*/
override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool {
guard let p = obj as? BookmarkBasePayload else {
return false
}
if !super.equalPayloads(p) {
return false
}
if self.deleted {
return true
}
if p.deleted {
return self.deleted == p.deleted
}
// If either record is deleted, these other fields might be missing.
// But we just checked, so we're good to roll on.
let same: (String) -> Bool = { field in
let left = self[field].string
let right = p[field].string
return left == right
}
if !BookmarkBasePayload.requiredStringFields.every(same) {
return false
}
if p["parentName"].string != self["parentName"].string {
return false
}
return self.hasDupe == p.hasDupe
}
// This goes here because extensions cannot override methods yet.
open func toMirrorItem(_ modified: Timestamp) -> BookmarkMirrorItem {
precondition(self.deleted, "Non-deleted items should have a specific type.")
return BookmarkMirrorItem.deleted(.bookmark, guid: self.id, modified: modified)
}
}
| mpl-2.0 | 51f262a76fa70353b02be59aa8a16348 | 28.218914 | 103 | 0.570367 | 5.02833 | false | false | false | false |
Msr-B/FanFan-iOS | WeCenterMobile/View/Publishment/FFPublishmentStepCell.swift | 2 | 3317 | //
// FFPublishmentStepCell.swift
// WeCenterMobile
//
// Created by Darren Liu on 15/7/4.
// Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import UIKit
import EAColourfulProgressView
class FFPublishmentStepCell: UITableViewCell, UITextViewDelegate {
@IBOutlet weak var stepIndexLabel: UILabel!
@IBOutlet weak var titleImageView: UIImageView!
@IBOutlet weak var titleImageButton: UIButton!
@IBOutlet weak var progressView: EAColourfulProgressView!
@IBOutlet weak var textView: MSRTextView!
@IBOutlet weak var separator: UIView!
override func awakeFromNib() {
super.awakeFromNib()
let theme = SettingsManager.defaultManager.currentTheme
stepIndexLabel.textColor = theme.subtitleTextColor
textView.backgroundColor = theme.backgroundColorB
textView.msr_borderColor = theme.borderColorA
textView.textColor = theme.bodyTextColor
textView.attributedPlaceholder = NSAttributedString(string: textView.placeholder ?? "",
attributes: [
NSForegroundColorAttributeName: theme.footnoteTextColor,
NSFontAttributeName: textView.font!])
separator.backgroundColor = theme.borderColorA
titleImageButton.tintColor = theme.backgroundColorA
titleImageButton.msr_borderColor = theme.borderColorA
msr_scrollView?.delaysContentTouches = false
msr_scrollView?.msr_setTouchesShouldCancel(true, inContentViewWhichIsKindOfClass: UIButton.self)
}
func update(step step: FFStepObject) {
let theme = SettingsManager.defaultManager.currentTheme
textView.text = step.text
if let image = step.image {
titleImageView.image = image
titleImageButton.setImage(nil, forState: .Normal)
} else {
titleImageView.image = nil
titleImageButton.msr_setBackgroundImageWithColor(theme.backgroundColorB)
titleImageButton.setImage(UIImage(named: "Publishment-Camera"), forState: .Normal)
progressView.hidden = true
}
updateProgress(step: step)
setNeedsLayout()
layoutIfNeeded()
}
func updateProgress(step step: FFStepObject) {
if let _ = step.image {
if step.uploadingProgresses < FFStepObject.maxProgress {
progressView.hidden = false
titleImageButton.msr_setBackgroundImageWithColor(UIColor.blackColor().colorWithAlphaComponent(0.5))
progressView.updateToCurrentValue(FFStepObject.maxProgress - step.uploadingProgresses, animated: false)
} else {
progressView.hidden = true
titleImageButton.setBackgroundImage(nil, forState: .Normal)
}
}
}
override func prepareForReuse() {
super.prepareForReuse()
update(step: FFStepObject())
}
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
let theme = SettingsManager.defaultManager.currentTheme
titleImageButton.enabled = !editing
textView.editable = !editing
textView.backgroundColor = editing ? UIColor.clearColor() : theme.backgroundColorB
}
}
| gpl-2.0 | 0a46d1aa5da792817e23e1dae97c4afd | 39.426829 | 119 | 0.682655 | 5.562081 | false | false | false | false |
DAloG/BlueCap | BlueCap/Beacon/BeaconRegionsViewController.swift | 1 | 10202 | //
// BeaconRegionsViewController.swift
// BlueCap
//
// Created by Troy Stribling on 9/16/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
import BlueCapKit
class BeaconRegionsViewController: UITableViewController {
var stopScanBarButtonItem : UIBarButtonItem!
var startScanBarButtonItem : UIBarButtonItem!
var beaconRegions = [String:BeaconRegion]()
struct MainStoryBoard {
static let beaconRegionCell = "BeaconRegionCell"
static let beaconsSegue = "Beacons"
static let beaconRegionAddSegue = "BeaconRegionAdd"
static let beaconRegionEditSegue = "BeaconRegionEdit"
}
required init?(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
self.stopScanBarButtonItem = UIBarButtonItem(barButtonSystemItem:.Stop, target:self, action:"toggleMonitoring:")
self.startScanBarButtonItem = UIBarButtonItem(title:"Scan", style:UIBarButtonItemStyle.Plain, target:self, action:"toggleMonitoring:")
self.styleUIBarButton(self.startScanBarButtonItem)
}
override func viewDidLoad() {
super.viewDidLoad()
self.styleNavigationBar()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
self.navigationItem.title = "Beacon Regions"
self.setScanButton()
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
self.navigationItem.title = ""
}
override func prepareForSegue(segue:UIStoryboardSegue, sender:AnyObject!) {
if segue.identifier == MainStoryBoard.beaconsSegue {
let selectedIndexPath = sender as! NSIndexPath
let beaconsViewController = segue.destinationViewController as! BeaconsViewController
let beaconName = BeaconStore.getBeaconNames()[selectedIndexPath.row]
if let beaconRegion = self.beaconRegions[beaconName] {
beaconsViewController.beaconRegion = beaconRegion
}
} else if segue.identifier == MainStoryBoard.beaconRegionAddSegue {
} else if segue.identifier == MainStoryBoard.beaconRegionEditSegue {
let selectedIndexPath = sender as! NSIndexPath
let viewController = segue.destinationViewController as! BeaconRegionViewController
viewController.regionName = BeaconStore.getBeaconNames()[selectedIndexPath.row]
}
}
func toggleMonitoring(sender:AnyObject) {
if CentralManager.sharedInstance.isScanning == false {
let beaconManager = BeaconManager.sharedInstance
if beaconManager.isRanging {
beaconManager.stopRangingAllBeacons()
beaconManager.stopMonitoringAllRegions()
self.beaconRegions.removeAll(keepCapacity:false)
self.setScanButton()
} else {
self.startMonitoring()
}
self.tableView.reloadData()
} else {
self.presentViewController(UIAlertController.alertWithMessage("Central scan is active. Cannot scan and monitor simutaneously. Stop scan to start monitoring"), animated:true, completion:nil)
}
}
func setScanButton() {
if BeaconManager.sharedInstance.isRanging {
self.navigationItem.setLeftBarButtonItem(self.stopScanBarButtonItem, animated:false)
} else {
self.navigationItem.setLeftBarButtonItem(self.startScanBarButtonItem, animated:false)
}
}
func startMonitoring() {
for (name, uuid) in BeaconStore.getBeacons() {
let beacon = BeaconRegion(proximityUUID:uuid, identifier:name)
let regionFuture = BeaconManager.sharedInstance.startMonitoringForRegion(beacon, authorization:.AuthorizedAlways)
let beaconFuture = regionFuture.flatmap {status -> FutureStream<[Beacon]> in
switch status {
case .Inside:
let beaconManager = BeaconManager.sharedInstance
if !beaconManager.isRangingRegion(beacon.identifier) {
self.updateDisplay()
Notify.withMessage("Entering region '\(name)'. Started ranging beacons.")
return beaconManager.startRangingBeaconsInRegion(beacon)
} else {
let errorPromise = StreamPromise<[Beacon]>()
errorPromise.failure(BCAppError.rangingBeacons)
return errorPromise.future
}
case .Outside:
BeaconManager.sharedInstance.stopRangingBeaconsInRegion(beacon)
self.updateWhenActive()
Notify.withMessage("Exited region '\(name)'. Stoped ranging beacons.")
let errorPromise = StreamPromise<[Beacon]>()
errorPromise.failure(BCAppError.outOfRegion)
return errorPromise.future
case .Start:
Logger.debug("started monitoring region \(name)")
self.navigationItem.setLeftBarButtonItem(self.stopScanBarButtonItem, animated:false)
return BeaconManager.sharedInstance.startRangingBeaconsInRegion(beacon)
}
}
beaconFuture.onSuccess {beacons in
self.setScanButton()
for beacon in beacons {
Logger.debug("major:\(beacon.major), minor: \(beacon.minor), rssi: \(beacon.rssi)")
}
self.updateWhenActive()
if UIApplication.sharedApplication().applicationState == .Active && beacons.count > 0 {
NSNotificationCenter.defaultCenter().postNotificationName(BlueCapNotification.didUpdateBeacon, object:beacon)
}
}
regionFuture.onFailure {error in
self.setScanButton()
BeaconManager.sharedInstance.stopRangingBeaconsInRegion(beacon)
self.updateWhenActive()
self.presentViewController(UIAlertController.alertOnError(error), animated:true, completion:nil)
}
self.beaconRegions[name] = beacon
}
}
func updateDisplay() {
if UIApplication.sharedApplication().applicationState == .Active {
self.tableView.reloadData()
}
}
func didResignActive() {
Logger.debug()
}
func didBecomeActive() {
Logger.debug()
self.tableView.reloadData()
}
// UITableViewDataSource
override func numberOfSectionsInTableView(tableView:UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return BeaconStore.getBeacons().count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryBoard.beaconRegionCell, forIndexPath: indexPath) as! BeaconRegionCell
let name = BeaconStore.getBeaconNames()[indexPath.row]
let beaconRegions = BeaconStore.getBeacons()
if let beaconRegionUUID = beaconRegions[name] {
cell.nameLabel.text = name
cell.uuidLabel.text = beaconRegionUUID.UUIDString
}
cell.nameLabel.textColor = UIColor.blackColor()
cell.beaconsLabel.text = "0"
cell.nameLabel.textColor = UIColor.lightGrayColor()
cell.statusLabel.textColor = UIColor.lightGrayColor()
if BeaconManager.sharedInstance.isRangingRegion(name) {
if let region = BeaconManager.sharedInstance.beaconRegion(name) {
if region.beacons.count == 0 {
cell.statusLabel.text = "Monitoring"
} else {
cell.nameLabel.textColor = UIColor.blackColor()
cell.beaconsLabel.text = "\(region.beacons.count)"
cell.statusLabel.text = "Ranging"
cell.statusLabel.textColor = UIColor(red:0.1, green:0.7, blue:0.1, alpha:0.5)
}
}
} else if CentralManager.sharedInstance.isScanning {
cell.statusLabel.text = "Monitoring"
} else {
cell.statusLabel.text = "Idle"
}
return cell
}
override func tableView(tableView:UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
let name = BeaconStore.getBeaconNames()[indexPath.row]
return !BeaconManager.sharedInstance.isRangingRegion(name)
}
override func tableView(tableView:UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath:NSIndexPath) {
if editingStyle == .Delete {
let name = BeaconStore.getBeaconNames()[indexPath.row]
BeaconStore.removeBeacon(name)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation:.Fade)
}
}
// UITableViewDelegate
override func tableView(tableView:UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {
let name = BeaconStore.getBeaconNames()[indexPath.row]
if BeaconManager.sharedInstance.isRangingRegion(name) {
if let beaconRegion = self.beaconRegions[name] {
if beaconRegion.beacons.count > 0 {
self.performSegueWithIdentifier(MainStoryBoard.beaconsSegue, sender:indexPath)
}
}
} else {
self.performSegueWithIdentifier(MainStoryBoard.beaconRegionEditSegue, sender:indexPath)
}
}
}
| mit | bb0d323d150f51c347e7bf50ded70adc | 44.141593 | 201 | 0.641541 | 5.927949 | false | false | false | false |
rnystrom/GitHawk | Classes/Repository/RepositoryBranches/GitHubClient+RepositoryBranches.swift | 1 | 1636 | //
// GitHubClient+RepoBranches.swift
// Freetime
//
// Created by B_Litwin on 9/25/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import GitHubAPI
import Apollo
private extension FetchRepositoryBranchesQuery.Data {
func branches() -> [String] {
var branches: [String] = []
repository?.refs.map { edges in
edges.edges.map { edge in
branches += edge.compactMap {
$0?.node?.name
}
}
}
return branches
}
func nextPageToken() -> String? {
guard repository?.refs?.pageInfo.hasNextPage == true else { return nil }
return repository?.refs?.pageInfo.endCursor
}
}
extension GithubClient {
struct RepositoryBranchesPayload {
let branches: [String]
let nextPage: String?
}
func fetchRepositoryBranches(owner: String,
repo: String,
nextPage: String?,
completion: @escaping (Result<RepositoryBranchesPayload>) -> Void
) {
let query = FetchRepositoryBranchesQuery(owner: owner, name: repo, after: nextPage)
client.query(query, result: { $0 }, completion: { result in
switch result {
case .failure(let error):
completion(.error(error))
case .success(let data):
let payload = RepositoryBranchesPayload(
branches: data.branches(),
nextPage: data.nextPageToken()
)
completion(.success(payload))
}
})
}
}
| mit | f3436216b207ebbeee8faff9b04f02fc | 25.803279 | 98 | 0.548012 | 4.89521 | false | false | false | false |
ben-ng/swift | test/Sema/accessibility.swift | 1 | 34932 | // RUN: %target-typecheck-verify-swift
public protocol PublicProto {
func publicReq()
}
// expected-note@+1 * {{type declared here}}
internal protocol InternalProto {
func internalReq()
}
fileprivate protocol FilePrivateProto {
func filePrivateReq()
}
// expected-note@+1 * {{type declared here}}
private protocol PrivateProto {
func privateReq()
}
public struct PublicStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto {
private func publicReq() {} // expected-error {{method 'publicReq()' must be declared public because it matches a requirement in public protocol 'PublicProto'}} {{3-10=public}}
private func internalReq() {} // expected-error {{method 'internalReq()' must be declared internal because it matches a requirement in internal protocol 'InternalProto'}} {{3-10=internal}}
private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{3-10=fileprivate}}
private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{3-10=fileprivate}}
public var publicVar = 0
}
// expected-note@+1 * {{type declared here}}
internal struct InternalStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto {
private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{3-10=internal}}
private func internalReq() {} // expected-error {{method 'internalReq()' must be declared internal because it matches a requirement in internal protocol 'InternalProto'}} {{3-10=internal}}
private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{3-10=fileprivate}}
private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{3-10=fileprivate}}
public var publicVar = 0
}
// expected-note@+1 * {{type declared here}}
fileprivate struct FilePrivateStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto {
private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{3-10=fileprivate}}
private func internalReq() {} // expected-error {{method 'internalReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'InternalProto'}} {{3-10=fileprivate}}
private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{3-10=fileprivate}}
private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{3-10=fileprivate}}
public var publicVar = 0
}
// expected-note@+1 * {{type declared here}}
private struct PrivateStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto {
private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{3-10=fileprivate}}
private func internalReq() {} // expected-error {{method 'internalReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'InternalProto'}} {{3-10=fileprivate}}
private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{3-10=fileprivate}}
private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{3-10=fileprivate}}
public var publicVar = 0
}
extension PublicStruct {
public init(x: Int) { self.init() }
}
extension InternalStruct {
public init(x: Int) { self.init() }
}
extension FilePrivateStruct {
public init(x: Int) { self.init() }
}
extension PrivateStruct {
public init(x: Int) { self.init() }
}
public extension PublicStruct {
public func extMemberPublic() {}
private func extImplPublic() {}
}
internal extension PublicStruct {
public func extMemberInternal() {} // expected-warning {{declaring a public instance method in an internal extension}} {{3-9=internal}}
private func extImplInternal() {}
}
private extension PublicStruct {
public func extMemberPrivate() {} // expected-warning {{declaring a public instance method in a private extension}} {{3-9=private}}
private func extImplPrivate() {}
}
fileprivate extension PublicStruct {
public func extMemberFilePrivate() {} // expected-warning {{declaring a public instance method in a fileprivate extension}} {{3-9=fileprivate}}
private func extImplFilePrivate() {}
}
public extension InternalStruct { // expected-error {{extension of internal struct cannot be declared public}} {{1-8=}}
public func extMemberPublic() {}
private func extImplPublic() {}
}
internal extension InternalStruct {
public func extMemberInternal() {} // expected-warning {{declaring a public instance method in an internal extension}} {{3-9=internal}}
private func extImplInternal() {}
}
fileprivate extension InternalStruct {
public func extMemberFilePrivate() {} // expected-warning {{declaring a public instance method in a fileprivate extension}} {{3-9=fileprivate}}
private func extImplFilePrivate() {}
}
private extension InternalStruct {
public func extMemberPrivate() {} // expected-warning {{declaring a public instance method in a private extension}} {{3-9=private}}
private func extImplPrivate() {}
}
public extension FilePrivateStruct { // expected-error {{extension of fileprivate struct cannot be declared public}} {{1-8=}}
public func extMemberPublic() {}
private func extImplPublic() {}
}
internal extension FilePrivateStruct { // expected-error {{extension of fileprivate struct cannot be declared internal}} {{1-10=}}
public func extMemberInternal() {} // expected-warning {{declaring a public instance method in an internal extension}} {{3-9=internal}}
private func extImplInternal() {}
}
fileprivate extension FilePrivateStruct {
public func extMemberFilePrivate() {} // expected-warning {{declaring a public instance method in a fileprivate extension}} {{3-9=fileprivate}}
private func extImplFilePrivate() {}
}
private extension FilePrivateStruct {
public func extMemberPrivate() {} // expected-warning {{declaring a public instance method in a private extension}} {{3-9=private}}
private func extImplPrivate() {}
}
public extension PrivateStruct { // expected-error {{extension of private struct cannot be declared public}} {{1-8=}}
public func extMemberPublic() {}
private func extImplPublic() {}
}
internal extension PrivateStruct { // expected-error {{extension of private struct cannot be declared internal}} {{1-10=}}
public func extMemberInternal() {} // expected-warning {{declaring a public instance method in an internal extension}} {{3-9=internal}}
private func extImplInternal() {}
}
fileprivate extension PrivateStruct { // expected-error {{extension of private struct cannot be declared fileprivate}} {{1-13=}}
public func extMemberFilePrivate() {} // expected-warning {{declaring a public instance method in a fileprivate extension}} {{3-9=fileprivate}}
private func extImplFilePrivate() {}
}
private extension PrivateStruct {
public func extMemberPrivate() {} // expected-warning {{declaring a public instance method in a private extension}} {{3-9=private}}
private func extImplPrivate() {}
}
public struct PublicStructDefaultMethods: PublicProto, InternalProto, PrivateProto {
func publicReq() {} // expected-error {{method 'publicReq()' must be declared public because it matches a requirement in public protocol 'PublicProto'}} {{3-3=public }}
func internalReq() {}
func privateReq() {}
}
public class Base {
required public init() {}
// expected-note@+1 * {{overridden declaration is here}}
public func foo() {}
// expected-note@+1 * {{overridden declaration is here}}
public internal(set) var bar: Int = 0
// expected-note@+1 * {{overridden declaration is here}}
public subscript () -> () { return () }
}
public class PublicSub: Base {
required init() {} // expected-error {{'required' initializer must be as accessible as its enclosing type}} {{12-12=public }}
override func foo() {} // expected-error {{overriding instance method must be as accessible as the declaration it overrides}} {{12-12=public }}
override var bar: Int { // expected-error {{overriding var must be as accessible as the declaration it overrides}} {{12-12=public }}
get { return 0 }
set {}
}
override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as the declaration it overrides}} {{12-12=public }}
}
internal class InternalSub: Base {
required private init() {} // expected-error {{'required' initializer must be as accessible as its enclosing type}} {{12-19=internal}}
private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=internal}}
private override var bar: Int { // expected-error {{overriding var must be as accessible as its enclosing type}} {{3-10=internal}}
get { return 0 }
set {}
}
private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=internal}}
}
internal class InternalSubGood: Base {
required init() {} // no-warning
override func foo() {}
override var bar: Int {
get { return 0 }
set {}
}
override subscript () -> () { return () }
}
internal class InternalSubPrivateSet: Base {
required init() {}
private(set) override var bar: Int { // expected-error {{overriding var must be as accessible as its enclosing type}} {{3-16=}}
get { return 0 }
set {}
}
private(set) override subscript () -> () { // okay; read-only in base class
get { return () }
set {}
}
}
fileprivate class FilePrivateSub: Base {
required private init() {} // expected-error {{'required' initializer must be as accessible as its enclosing type}} {{12-19=fileprivate}}
private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=fileprivate}}
private override var bar: Int { // expected-error {{overriding var must be as accessible as its enclosing type}} {{3-10=fileprivate}}
get { return 0 }
set {}
}
private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=fileprivate}}
}
fileprivate class FilePrivateSubGood: Base {
required init() {} // no-warning
override func foo() {}
override var bar: Int {
get { return 0 }
set {}
}
override subscript () -> () { return () }
}
fileprivate class FilePrivateSubGood2: Base {
fileprivate required init() {} // no-warning
fileprivate override func foo() {}
fileprivate override var bar: Int {
get { return 0 }
set {}
}
fileprivate override subscript () -> () { return () }
}
fileprivate class FilePrivateSubPrivateSet: Base {
required init() {}
private(set) override var bar: Int { // expected-error {{overriding var must be as accessible as its enclosing type}} {{3-10=fileprivate}}
get { return 0 }
set {}
}
private(set) override subscript () -> () { // okay; read-only in base class
get { return () }
set {}
}
}
private class PrivateSub: Base {
required private init() {} // expected-error {{'required' initializer must be as accessible as its enclosing type}} {{12-19=fileprivate}}
private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=fileprivate}}
private override var bar: Int { // expected-error {{overriding var must be as accessible as its enclosing type}} {{3-10=fileprivate}}
get { return 0 }
set {}
}
private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=fileprivate}}
}
private class PrivateSubGood: Base {
required fileprivate init() {}
fileprivate override func foo() {}
fileprivate override var bar: Int {
get { return 0 }
set {}
}
fileprivate override subscript () -> () { return () }
}
private class PrivateSubPrivateSet: Base {
required fileprivate init() {}
fileprivate override func foo() {}
private(set) override var bar: Int { // expected-error {{setter of overriding var must be as accessible as its enclosing type}}
get { return 0 }
set {}
}
private(set) override subscript () -> () { // okay; read-only in base class
get { return () }
set {}
}
}
public typealias PublicTA1 = PublicStruct
public typealias PublicTA2 = InternalStruct // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
public typealias PublicTA3 = FilePrivateStruct // expected-error {{type alias cannot be declared public because its underlying type uses a fileprivate type}}
public typealias PublicTA4 = PrivateStruct // expected-error {{type alias cannot be declared public because its underlying type uses a private type}}
// expected-note@+1 {{type declared here}}
internal typealias InternalTA1 = PublicStruct
internal typealias InternalTA2 = InternalStruct
internal typealias InternalTA3 = FilePrivateStruct // expected-error {{type alias cannot be declared internal because its underlying type uses a fileprivate type}}
internal typealias InternalTA4 = PrivateStruct // expected-error {{type alias cannot be declared internal because its underlying type uses a private type}}
public typealias PublicFromInternal = InternalTA1 // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
typealias FunctionType1 = (PrivateStruct) -> PublicStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias FunctionType2 = (PublicStruct) -> PrivateStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias FunctionType3 = (PrivateStruct) -> PrivateStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias ArrayType = [PrivateStruct] // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias DictType = [String : PrivateStruct] // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias GenericArgs = Optional<PrivateStruct> // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
public protocol HasAssocType {
associatedtype Inferred
func test(input: Inferred)
}
public struct AssocTypeImpl: HasAssocType {
public func test(input: Bool) {}
}
public let _: AssocTypeImpl.Inferred?
public let x: PrivateStruct = PrivateStruct() // expected-error {{constant cannot be declared public because its type uses a private type}}
public var a: PrivateStruct?, b: PrivateStruct? // expected-error 2 {{variable cannot be declared public because its type uses a private type}}
public var (c, d): (PrivateStruct?, PrivateStruct?) // expected-error {{variable cannot be declared public because its type uses a private type}}
var internalVar: PrivateStruct? // expected-error {{variable must be declared private or fileprivate because its type uses a private type}}
let internalConstant = PrivateStruct() // expected-error {{constant must be declared private or fileprivate because its type 'PrivateStruct' uses a private type}}
public let publicConstant = [InternalStruct]() // expected-error {{constant cannot be declared public because its type '[InternalStruct]' uses an internal type}}
public struct Properties {
public let x: PrivateStruct = PrivateStruct() // expected-error {{property cannot be declared public because its type uses a private type}}
public var a: PrivateStruct?, b: PrivateStruct? // expected-error 2 {{property cannot be declared public because its type uses a private type}}
public var (c, d): (PrivateStruct?, PrivateStruct?) // expected-error {{property cannot be declared public because its type uses a private type}}
let y = PrivateStruct() // expected-error {{property must be declared fileprivate because its type 'PrivateStruct' uses a private type}}
}
public struct Subscripts {
subscript (a: PrivateStruct) -> Int { return 0 } // expected-error {{subscript must be declared fileprivate because its index uses a private type}}
subscript (a: Int) -> PrivateStruct { return PrivateStruct() } // expected-error {{subscript must be declared fileprivate because its element type uses a private type}}
public subscript (a: PrivateStruct, b: Int) -> Int { return 0 } // expected-error {{subscript cannot be declared public because its index uses a private type}}
public subscript (a: Int, b: PrivateStruct) -> Int { return 0 } // expected-error {{subscript cannot be declared public because its index uses a private type}}
public subscript (a: InternalStruct, b: PrivateStruct) -> InternalStruct { return InternalStruct() } // expected-error {{subscript cannot be declared public because its index uses a private type}}
public subscript (a: PrivateStruct, b: InternalStruct) -> PrivateStruct { return PrivateStruct() } // expected-error {{subscript cannot be declared public because its index uses a private type}}
public subscript (a: Int, b: Int) -> InternalStruct { return InternalStruct() } // expected-error {{subscript cannot be declared public because its element type uses an internal type}}
}
public struct Methods {
func foo(a: PrivateStruct) -> Int { return 0 } // expected-error {{method must be declared fileprivate because its parameter uses a private type}}
func bar(a: Int) -> PrivateStruct { return PrivateStruct() } // expected-error {{method must be declared fileprivate because its result uses a private type}}
public func a(a: PrivateStruct, b: Int) -> Int { return 0 } // expected-error {{method cannot be declared public because its parameter uses a private type}}
public func b(a: Int, b: PrivateStruct) -> Int { return 0 } // expected-error {{method cannot be declared public because its parameter uses a private type}}
public func c(a: InternalStruct, b: PrivateStruct) -> InternalStruct { return InternalStruct() } // expected-error {{method cannot be declared public because its parameter uses a private type}}
public func d(a: PrivateStruct, b: InternalStruct) -> PrivateStruct { return PrivateStruct() } // expected-error {{method cannot be declared public because its parameter uses a private type}}
public func e(a: Int, b: Int) -> InternalStruct { return InternalStruct() } // expected-error {{method cannot be declared public because its result uses an internal type}}
}
func privateParam(a: PrivateStruct) {} // expected-error {{function must be declared private or fileprivate because its parameter uses a private type}}
public struct Initializers {
init(a: PrivateStruct) {} // expected-error {{initializer must be declared fileprivate because its parameter uses a private type}}
public init(a: PrivateStruct, b: Int) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
public init(a: Int, b: PrivateStruct) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
public init(a: InternalStruct, b: PrivateStruct) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
public init(a: PrivateStruct, b: InternalStruct) { } // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
}
public class PublicClass {}
// expected-note@+1 * {{type declared here}}
internal class InternalClass {}
// expected-note@+1 * {{type declared here}}
private class PrivateClass {}
public protocol AssocTypes {
associatedtype Foo
associatedtype Internal: InternalClass // expected-error {{associated type in a public protocol uses an internal type in its requirement}}
associatedtype InternalConformer: InternalProto // expected-error {{associated type in a public protocol uses an internal type in its requirement}}
associatedtype PrivateConformer: PrivateProto // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype PI: PrivateProto, InternalProto // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype IP: InternalProto, PrivateProto // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype PrivateDefault = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its default definition}}
associatedtype PublicDefault = PublicStruct
associatedtype PrivateDefaultConformer: PublicProto = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its default definition}}
associatedtype PublicDefaultConformer: PrivateProto = PublicStruct // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype PrivatePrivateDefaultConformer: PrivateProto = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype PublicPublicDefaultConformer: PublicProto = PublicStruct
}
public protocol RequirementTypes {
var x: PrivateStruct { get } // expected-error {{property cannot be declared public because its type uses a private type}}
subscript(x: Int) -> InternalStruct { get set } // expected-error {{subscript cannot be declared public because its element type uses an internal type}}
func foo() -> PrivateStruct // expected-error {{method cannot be declared public because its result uses a private type}}
init(x: PrivateStruct) // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
}
protocol DefaultRefinesPrivate : PrivateProto {} // expected-error {{protocol must be declared private or fileprivate because it refines a private protocol}}
public protocol PublicRefinesPrivate : PrivateProto {} // expected-error {{public protocol cannot refine a private protocol}}
public protocol PublicRefinesInternal : InternalProto {} // expected-error {{public protocol cannot refine an internal protocol}}
public protocol PublicRefinesPI : PrivateProto, InternalProto {} // expected-error {{public protocol cannot refine a private protocol}}
public protocol PublicRefinesIP : InternalProto, PrivateProto {} // expected-error {{public protocol cannot refine a private protocol}}
// expected-note@+1 * {{type declared here}}
private typealias PrivateInt = Int
enum DefaultRawPrivate : PrivateInt { // expected-error {{enum must be declared private or fileprivate because its raw type uses a private type}}
case A
}
public enum PublicRawPrivate : PrivateInt { // expected-error {{enum cannot be declared public because its raw type uses a private type}}
case A
}
public enum MultipleConformance : PrivateProto, PrivateInt { // expected-error {{enum cannot be declared public because its raw type uses a private type}} expected-error {{must appear first}} {{35-35=PrivateInt, }} {{47-59=}}
case A
func privateReq() {}
}
public class PublicSubclassPublic : PublicClass {}
public class PublicSubclassInternal : InternalClass {} // expected-error {{class cannot be declared public because its superclass is internal}}
public class PublicSubclassPrivate : PrivateClass {} // expected-error {{class cannot be declared public because its superclass is private}}
class DefaultSubclassPublic : PublicClass {}
class DefaultSubclassInternal : InternalClass {}
class DefaultSubclassPrivate : PrivateClass {} // expected-error {{class must be declared private or fileprivate because its superclass is private}}
public enum PublicEnumPrivate {
case A(PrivateStruct) // expected-error {{enum case in a public enum uses a private type}}
}
enum DefaultEnumPrivate {
case A(PrivateStruct) // expected-error {{enum case in an internal enum uses a private type}}
}
public enum PublicEnumPI {
case A(InternalStruct) // expected-error {{enum case in a public enum uses an internal type}}
case B(PrivateStruct, InternalStruct) // expected-error {{enum case in a public enum uses a private type}}
case C(InternalStruct, PrivateStruct) // expected-error {{enum case in a public enum uses a private type}}
}
enum DefaultEnumPublic {
case A(PublicStruct) // no-warning
}
struct DefaultGeneric<T> {}
struct DefaultGenericPrivate<T: PrivateProto> {} // expected-error {{generic struct must be declared private or fileprivate because its generic parameter uses a private type}}
struct DefaultGenericPrivate2<T: PrivateClass> {} // expected-error {{generic struct must be declared private or fileprivate because its generic parameter uses a private type}}
struct DefaultGenericPrivateReq<T> where T == PrivateClass {} // expected-error {{same-type requirement makes generic parameter 'T' non-generic}}
// expected-error@-1 {{generic struct must be declared private or fileprivate because its generic requirement uses a private type}}
struct DefaultGenericPrivateReq2<T> where T: PrivateProto {} // expected-error {{generic struct must be declared private or fileprivate because its generic requirement uses a private type}}
public struct PublicGenericInternal<T: InternalProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses an internal type}}
public struct PublicGenericPI<T: PrivateProto, U: InternalProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}}
public struct PublicGenericIP<T: InternalProto, U: PrivateProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}}
public struct PublicGenericPIReq<T: PrivateProto> where T: InternalProto {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}}
public struct PublicGenericIPReq<T: InternalProto> where T: PrivateProto {} // expected-error {{generic struct cannot be declared public because its generic requirement uses a private type}}
public func genericFunc<T: InternalProto>(_: T) {} // expected-error {{function cannot be declared public because its generic parameter uses an internal type}} {}
public class GenericClass<T: InternalProto> { // expected-error {{generic class cannot be declared public because its generic parameter uses an internal type}}
public init<T: PrivateProto>(_: T) {} // expected-error {{initializer cannot be declared public because its generic parameter uses a private type}}
public func genericMethod<T: PrivateProto>(_: T) {} // expected-error {{instance method cannot be declared public because its generic parameter uses a private type}}
}
public enum GenericEnum<T: InternalProto> { // expected-error {{generic enum cannot be declared public because its generic parameter uses an internal type}}
case A
}
public protocol PublicMutationOperations {
var size: Int { get set }
subscript (_: Int) -> Int { get set }
}
internal protocol InternalMutationOperations {
var size: Int { get set }
subscript (_: Int) -> Int { get set }
}
public struct AccessorsControl : InternalMutationOperations {
private var size = 0 // expected-error {{property 'size' must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{3-10=internal}}
private subscript (_: Int) -> Int { // expected-error {{subscript must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{3-10=internal}}
get { return 42 }
set {}
}
}
public struct PrivateSettersPublic : InternalMutationOperations {
// Please don't change the formatting here; it's a precise fix-it test.
public private(set) var size = 0 // expected-error {{setter for property 'size' must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{10-17=internal}}
public private(set) subscript (_: Int) -> Int { // expected-error {{subscript setter must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{10-17=internal}}
get { return 42 }
set {}
}
}
internal struct PrivateSettersInternal : PublicMutationOperations {
// Please don't change the formatting here; it's a precise fix-it test.
private(set)var size = 0 // expected-error {{setter for property 'size' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicMutationOperations'}} {{3-15=}}
internal private(set)subscript (_: Int) -> Int { // expected-error {{subscript setter must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicMutationOperations'}} {{12-24=}}
get { return 42 }
set {}
}
}
public protocol PublicReadOnlyOperations {
var size: Int { get }
subscript (_: Int) -> Int { get }
}
internal struct PrivateSettersForReadOnlyInternal : PublicReadOnlyOperations {
public private(set) var size = 0
internal private(set) subscript (_: Int) -> Int { // no-warning
get { return 42 }
set {}
}
}
public struct PrivateSettersForReadOnlyPublic : PublicReadOnlyOperations {
public private(set) var size = 0 // no-warning
internal private(set) subscript (_: Int) -> Int { // expected-error {{subscript must be declared public because it matches a requirement in public protocol 'PublicReadOnlyOperations'}} {{3-11=public}}
get { return 42 }
set {}
}
}
public protocol PublicOperatorProto {
static prefix func !(_: Self) -> Self
}
internal protocol InternalOperatorProto {
static prefix func !(_: Self) -> Self
}
fileprivate protocol FilePrivateOperatorProto {
static prefix func !(_: Self) -> Self
}
private protocol PrivateOperatorProto {
static prefix func !(_: Self) -> Self
}
public struct PublicOperatorAdopter : PublicOperatorProto {
fileprivate struct Inner : PublicOperatorProto {
}
}
private prefix func !(input: PublicOperatorAdopter) -> PublicOperatorAdopter { // expected-error {{method '!' must be declared public because it matches a requirement in public protocol 'PublicOperatorProto'}} {{1-8=public}}
return input
}
private prefix func !(input: PublicOperatorAdopter.Inner) -> PublicOperatorAdopter.Inner {
return input
}
public struct InternalOperatorAdopter : InternalOperatorProto {
fileprivate struct Inner : InternalOperatorProto {
}
}
private prefix func !(input: InternalOperatorAdopter) -> InternalOperatorAdopter { // expected-error {{method '!' must be declared internal because it matches a requirement in internal protocol 'InternalOperatorProto'}} {{1-8=internal}}
return input
}
private prefix func !(input: InternalOperatorAdopter.Inner) -> InternalOperatorAdopter.Inner {
return input
}
public struct FilePrivateOperatorAdopter : FilePrivateOperatorProto {
fileprivate struct Inner : FilePrivateOperatorProto {
}
}
private prefix func !(input: FilePrivateOperatorAdopter) -> FilePrivateOperatorAdopter {
return input
}
private prefix func !(input: FilePrivateOperatorAdopter.Inner) -> FilePrivateOperatorAdopter.Inner {
return input
}
public struct PrivateOperatorAdopter : PrivateOperatorProto {
fileprivate struct Inner : PrivateOperatorProto {
}
}
private prefix func !(input: PrivateOperatorAdopter) -> PrivateOperatorAdopter {
return input
}
private prefix func !(input: PrivateOperatorAdopter.Inner) -> PrivateOperatorAdopter.Inner {
return input
}
public protocol Equatablish {
static func ==(lhs: Self, rhs: Self) /* -> bool */ // expected-note {{protocol requires function '=='}}
}
fileprivate struct EquatablishOuter {
internal struct Inner : Equatablish {}
}
private func ==(lhs: EquatablishOuter.Inner, rhs: EquatablishOuter.Inner) {}
// expected-note@-1 {{candidate has non-matching type}}
fileprivate struct EquatablishOuter2 {
internal struct Inner : Equatablish {
fileprivate static func ==(lhs: Inner, rhs: Inner) {}
// expected-note@-1 {{candidate has non-matching type}}
}
}
fileprivate struct EquatablishOuterProblem {
internal struct Inner : Equatablish { // expected-error {{type 'EquatablishOuterProblem.Inner' does not conform to protocol 'Equatablish'}}
private static func ==(lhs: Inner, rhs: Inner) {}
}
}
internal struct EquatablishOuterProblem2 {
public struct Inner : Equatablish {
fileprivate static func ==(lhs: Inner, rhs: Inner) {} // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{5-16=internal}}
// expected-note@-1 {{candidate has non-matching type}}
}
}
internal struct EquatablishOuterProblem3 {
public struct Inner : Equatablish {
}
}
private func ==(lhs: EquatablishOuterProblem3.Inner, rhs: EquatablishOuterProblem3.Inner) {} // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{1-8=internal}}
// expected-note@-1 {{candidate has non-matching type}}
public protocol AssocTypeProto {
associatedtype Assoc
}
fileprivate struct AssocTypeOuter {
internal struct Inner : AssocTypeProto {
fileprivate typealias Assoc = Int
}
}
fileprivate struct AssocTypeOuterProblem {
internal struct Inner : AssocTypeProto {
private typealias Assoc = Int // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{5-12=fileprivate}}
}
}
internal struct AssocTypeOuterProblem2 {
public struct Inner : AssocTypeProto {
fileprivate typealias Assoc = Int // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{5-16=internal}}
}
}
| apache-2.0 | f5f9fdf1c9da77f2c2cf41e9d92637a6 | 53.666667 | 246 | 0.74834 | 4.899986 | false | true | false | false |
frootloops/swift | test/SILGen/protocols.swift | 1 | 22335 | // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
//===----------------------------------------------------------------------===//
// Calling Existential Subscripts
//===----------------------------------------------------------------------===//
protocol SubscriptableGet {
subscript(a : Int) -> Int { get }
}
protocol SubscriptableGetSet {
subscript(a : Int) -> Int { get set }
}
var subscriptableGet : SubscriptableGet
var subscriptableGetSet : SubscriptableGetSet
func use_subscript_rvalue_get(_ i : Int) -> Int {
return subscriptableGet[i]
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_rvalue_get
// CHECK: bb0(%0 : @trivial $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @_T09protocols16subscriptableGetAA013SubscriptableC0_pvp : $*SubscriptableGet
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*SubscriptableGet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*SubscriptableGet to $*[[OPENED:@opened(.*) SubscriptableGet]]
// CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: end_access [[READ]] : $*SubscriptableGet
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGet.subscript!getter.1
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[ALLOCSTACK]])
// CHECK-NEXT: destroy_addr [[ALLOCSTACK]]
// CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: return [[RESULT]]
func use_subscript_lvalue_get(_ i : Int) -> Int {
return subscriptableGetSet[i]
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_lvalue_get
// CHECK: bb0(%0 : @trivial $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @_T09protocols19subscriptableGetSetAA013SubscriptablecD0_pvp : $*SubscriptableGetSet
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*SubscriptableGetSet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]]
// CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!getter.1
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[ALLOCSTACK]])
// CHECK-NEXT: destroy_addr [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: end_access [[READ]] : $*SubscriptableGetSet
// CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: return [[RESULT]]
func use_subscript_lvalue_set(_ i : Int) {
subscriptableGetSet[i] = i
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_lvalue_set
// CHECK: bb0(%0 : @trivial $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @_T09protocols19subscriptableGetSetAA013SubscriptablecD0_pvp : $*SubscriptableGetSet
// CHECK: [[READ:%.*]] = begin_access [modify] [dynamic] [[GLOB]] : $*SubscriptableGetSet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr mutable_access [[READ]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!setter.1
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, %0, [[PROJ]])
//===----------------------------------------------------------------------===//
// Calling Archetype Subscripts
//===----------------------------------------------------------------------===//
func use_subscript_archetype_rvalue_get<T : SubscriptableGet>(_ generic : T, idx : Int) -> Int {
return generic[idx]
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_rvalue_get
// CHECK: bb0(%0 : @trivial $*T, %1 : @trivial $Int):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]]
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGet.subscript!getter.1
// CHECK-NEXT: apply [[METH]]<T>(%1, [[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]] : $*T
// CHECK-NEXT: dealloc_stack [[STACK]] : $*T
// CHECK-NEXT: destroy_addr %0
func use_subscript_archetype_lvalue_get<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) -> Int {
return generic[idx]
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_lvalue_get
// CHECK: bb0(%0 : @trivial $*T, %1 : @trivial $Int):
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*T
// CHECK: [[GUARANTEEDSTACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr [[READ]] to [initialization] [[GUARANTEEDSTACK]] : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!getter.1
// CHECK-NEXT: [[APPLYRESULT:%[0-9]+]] = apply [[METH]]<T>(%1, [[GUARANTEEDSTACK]])
// CHECK-NEXT: destroy_addr [[GUARANTEEDSTACK]] : $*T
// CHECK-NEXT: end_access [[READ]]
// CHECK-NEXT: dealloc_stack [[GUARANTEEDSTACK]] : $*T
// CHECK: return [[APPLYRESULT]]
func use_subscript_archetype_lvalue_set<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) {
generic[idx] = idx
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_lvalue_set
// CHECK: bb0(%0 : @trivial $*T, %1 : @trivial $Int):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!setter.1
// CHECK-NEXT: apply [[METH]]<T>(%1, %1, [[WRITE]])
//===----------------------------------------------------------------------===//
// Calling Existential Properties
//===----------------------------------------------------------------------===//
protocol PropertyWithGetter {
var a : Int { get }
}
protocol PropertyWithGetterSetter {
var b : Int { get set }
}
var propertyGet : PropertyWithGetter
var propertyGetSet : PropertyWithGetterSetter
func use_property_rvalue_get() -> Int {
return propertyGet.a
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_rvalue_get
// CHECK: [[GLOB:%[0-9]+]] = global_addr @_T09protocols11propertyGetAA18PropertyWithGetter_pvp : $*PropertyWithGetter
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*PropertyWithGetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*PropertyWithGetter to $*[[OPENED:@opened(.*) PropertyWithGetter]]
// CHECK: [[COPY:%.*]] = alloc_stack $[[OPENED]]
// CHECK-NEXT: copy_addr [[PROJ]] to [initialization] [[COPY]] : $*[[OPENED]]
// CHECK-NEXT: end_access [[READ]] : $*PropertyWithGetter
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetter.a!getter.1
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[COPY]])
func use_property_lvalue_get() -> Int {
return propertyGetSet.b
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_lvalue_get
// CHECK: [[GLOB:%[0-9]+]] = global_addr @_T09protocols14propertyGetSetAA24PropertyWithGetterSetter_pvp : $*PropertyWithGetterSetter
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*PropertyWithGetterSetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[STACK]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!getter.1
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[STACK]])
func use_property_lvalue_set(_ x : Int) {
propertyGetSet.b = x
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_lvalue_set
// CHECK: bb0(%0 : @trivial $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @_T09protocols14propertyGetSetAA24PropertyWithGetterSetter_pvp : $*PropertyWithGetterSetter
// CHECK: [[READ:%.*]] = begin_access [modify] [dynamic] [[GLOB]] : $*PropertyWithGetterSetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr mutable_access [[READ]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!setter.1
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, [[PROJ]])
//===----------------------------------------------------------------------===//
// Calling Archetype Properties
//===----------------------------------------------------------------------===//
func use_property_archetype_rvalue_get<T : PropertyWithGetter>(_ generic : T) -> Int {
return generic.a
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_rvalue_get
// CHECK: bb0(%0 : @trivial $*T):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]]
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetter.a!getter.1
// CHECK-NEXT: apply [[METH]]<T>([[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]]
// CHECK-NEXT: dealloc_stack [[STACK]]
// CHECK-NEXT: destroy_addr %0
func use_property_archetype_lvalue_get<T : PropertyWithGetterSetter>(_ generic : T) -> Int {
return generic.b
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_lvalue_get
// CHECK: bb0(%0 : @trivial $*T):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]] : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!getter.1
// CHECK-NEXT: apply [[METH]]<T>([[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]] : $*T
// CHECK-NEXT: dealloc_stack [[STACK]] : $*T
// CHECK-NEXT: destroy_addr %0
func use_property_archetype_lvalue_set<T : PropertyWithGetterSetter>(_ generic: inout T, v : Int) {
generic.b = v
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_lvalue_set
// CHECK: bb0(%0 : @trivial $*T, %1 : @trivial $Int):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!setter.1
// CHECK-NEXT: apply [[METH]]<T>(%1, [[WRITE]])
//===----------------------------------------------------------------------===//
// Calling Initializers
//===----------------------------------------------------------------------===//
protocol Initializable {
init(int: Int)
}
// CHECK-LABEL: sil hidden @_T09protocols27use_initializable_archetype{{[_0-9a-zA-Z]*}}F
func use_initializable_archetype<T: Initializable>(_ t: T, i: Int) {
// CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T
// CHECK: [[T_META:%[0-9]+]] = metatype $@thick T.Type
// CHECK: [[T_INIT:%[0-9]+]] = witness_method $T, #Initializable.init!allocator.1 : {{.*}} : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[T_RESULT_ADDR:%[0-9]+]] = apply [[T_INIT]]<T>([[T_RESULT]], %1, [[T_META]]) : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: destroy_addr [[T_RESULT]] : $*T
// CHECK: dealloc_stack [[T_RESULT]] : $*T
// CHECK: destroy_addr [[VAR_0:%[0-9]+]] : $*T
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
T(int: i)
}
// CHECK: sil hidden @_T09protocols29use_initializable_existential{{[_0-9a-zA-Z]*}}F
func use_initializable_existential(_ im: Initializable.Type, i: Int) {
// CHECK: bb0([[IM:%[0-9]+]] : @trivial $@thick Initializable.Type, [[I:%[0-9]+]] : @trivial $Int):
// CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[IM]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type
// CHECK: [[TEMP_VALUE:%[0-9]+]] = alloc_stack $Initializable
// CHECK: [[TEMP_ADDR:%[0-9]+]] = init_existential_addr [[TEMP_VALUE]] : $*Initializable, $@opened([[N]]) Initializable
// CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method $@opened([[N]]) Initializable, #Initializable.init!allocator.1 : {{.*}}, [[ARCHETYPE_META]]{{.*}} : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[TEMP_ADDR]], [[I]], [[ARCHETYPE_META]]) : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: destroy_addr [[TEMP_VALUE]] : $*Initializable
// CHECK: dealloc_stack [[TEMP_VALUE]] : $*Initializable
im.init(int: i)
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
}
//===----------------------------------------------------------------------===//
// Protocol conformance and witness table generation
//===----------------------------------------------------------------------===//
class ClassWithGetter : PropertyWithGetter {
var a: Int {
get {
return 42
}
}
}
// Make sure we are generating a protocol witness that calls the class method on
// ClassWithGetter.
// CHECK-LABEL: sil private [transparent] [thunk] @_T09protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSivgTW : $@convention(witness_method: PropertyWithGetter) (@in_guaranteed ClassWithGetter) -> Int {
// CHECK: bb0([[C:%.*]] : @trivial $*ClassWithGetter):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow %0
// CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetter, #ClassWithGetter.a!getter.1 : (ClassWithGetter) -> () -> Int, $@convention(method) (@guaranteed ClassWithGetter) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: end_borrow [[CCOPY_LOADED]] from %0
// CHECK-NEXT: return
class ClassWithGetterSetter : PropertyWithGetterSetter, PropertyWithGetter {
var a: Int {
get {
return 1
}
set {}
}
var b: Int {
get {
return 2
}
set {}
}
}
// CHECK-LABEL: sil private [transparent] [thunk] @_T09protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivgTW : $@convention(witness_method: PropertyWithGetterSetter) (@in_guaranteed ClassWithGetterSetter) -> Int {
// CHECK: bb0([[C:%.*]] : @trivial $*ClassWithGetterSetter):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow %0
// CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetterSetter, #ClassWithGetterSetter.b!getter.1 : (ClassWithGetterSetter) -> () -> Int, $@convention(method) (@guaranteed ClassWithGetterSetter) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: end_borrow [[CCOPY_LOADED]] from %0
// CHECK-NEXT: return
// Stored variables fulfilling property requirements
//
class ClassWithStoredProperty : PropertyWithGetter {
var a : Int = 0
// Make sure that accesses go through the generated accessors for classes.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden @_T09protocols23ClassWithStoredPropertyC011methodUsingE0SiyF
// CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassWithStoredProperty):
// CHECK-NEXT: debug_value [[ARG]]
// CHECK-NOT: copy_value
// CHECK-NEXT: [[FUN:%.*]] = class_method [[ARG]] : $ClassWithStoredProperty, #ClassWithStoredProperty.a!getter.1 : (ClassWithStoredProperty) -> () -> Int, $@convention(method) (@guaranteed ClassWithStoredProperty) -> Int
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[ARG]])
// CHECK-NOT: destroy_value
// CHECK-NEXT: return [[RESULT]] : $Int
}
struct StructWithStoredProperty : PropertyWithGetter {
var a : Int
// Make sure that accesses aren't going through the generated accessors.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden @_T09protocols24StructWithStoredPropertyV011methodUsingE0SiyF
// CHECK: bb0(%0 : @trivial $StructWithStoredProperty):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredProperty, #StructWithStoredProperty.a
// CHECK-NEXT: return %2 : $Int
}
// Make sure that we generate direct function calls for out struct protocol
// witness since structs don't do virtual calls for methods.
//
// *NOTE* Even though at first glance the copy_addr looks like a leak
// here, StructWithStoredProperty is a trivial struct implying that no
// leak is occurring. See the test with StructWithStoredClassProperty
// that makes sure in such a case we don't leak. This is due to the
// thunking code being too dumb but it is harmless to program
// correctness.
//
// CHECK-LABEL: sil private [transparent] [thunk] @_T09protocols24StructWithStoredPropertyVAA0eC6GetterA2aDP1aSivgTW : $@convention(witness_method: PropertyWithGetter) (@in_guaranteed StructWithStoredProperty) -> Int {
// CHECK: bb0([[C:%.*]] : @trivial $*StructWithStoredProperty):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [trivial] [[C]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @_T09protocols24StructWithStoredPropertyV1aSivg : $@convention(method) (StructWithStoredProperty) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: return
class C {}
// Make sure that if the getter has a class property, we pass it in
// in_guaranteed and don't leak.
struct StructWithStoredClassProperty : PropertyWithGetter {
var a : Int
var c: C = C()
// Make sure that accesses aren't going through the generated accessors.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden @_T09protocols29StructWithStoredClassPropertyV011methodUsingF0SiyF
// CHECK: bb0(%0 : @guaranteed $StructWithStoredClassProperty):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredClassProperty, #StructWithStoredClassProperty.a
// CHECK-NEXT: return %2 : $Int
}
// CHECK-LABEL: sil private [transparent] [thunk] @_T09protocols29StructWithStoredClassPropertyVAA0fC6GetterA2aDP1aSivgTW : $@convention(witness_method: PropertyWithGetter) (@in_guaranteed StructWithStoredClassProperty) -> Int {
// CHECK: bb0([[C:%.*]] : @trivial $*StructWithStoredClassProperty):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow [[C]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @_T09protocols29StructWithStoredClassPropertyV1aSivg : $@convention(method) (@guaranteed StructWithStoredClassProperty) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: end_borrow [[CCOPY_LOADED]] from %0
// CHECK-NEXT: return
// rdar://22676810
protocol ExistentialProperty {
var p: PropertyWithGetterSetter { get set }
}
func testExistentialPropertyRead<T: ExistentialProperty>(_ t: inout T) {
let b = t.p.b
}
// CHECK-LABEL: sil hidden @_T09protocols27testExistentialPropertyRead{{[_0-9a-zA-Z]*}}F
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*T
// CHECK: [[P_TEMP:%.*]] = alloc_stack $PropertyWithGetterSetter
// CHECK: [[T_TEMP:%.*]] = alloc_stack $T
// CHECK: copy_addr [[READ]] to [initialization] [[T_TEMP]] : $*T
// CHECK: [[P_GETTER:%.*]] = witness_method $T, #ExistentialProperty.p!getter.1 :
// CHECK-NEXT: apply [[P_GETTER]]<T>([[P_TEMP]], [[T_TEMP]])
// CHECK-NEXT: destroy_addr [[T_TEMP]]
// CHECK-NEXT: [[OPEN:%.*]] = open_existential_addr immutable_access [[P_TEMP]] : $*PropertyWithGetterSetter to $*[[P_OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK-NEXT: [[T0:%.*]] = alloc_stack $[[P_OPENED]]
// CHECK-NEXT: copy_addr [[OPEN]] to [initialization] [[T0]]
// CHECK-NEXT: [[B_GETTER:%.*]] = witness_method $[[P_OPENED]], #PropertyWithGetterSetter.b!getter.1
// CHECK-NEXT: apply [[B_GETTER]]<[[P_OPENED]]>([[T0]])
// CHECK-NEXT: destroy_addr [[T0]]
// CHECK-NOT: witness_method
// CHECK: return
func modify(_ x: inout Int) {}
// Make sure we call the materializeForSet callback with the correct
// generic signature.
func modifyProperty<T : PropertyWithGetterSetter>(_ x: inout T) {
modify(&x.b)
}
// CHECK-LABEL: sil hidden @_T09protocols14modifyPropertyyxzAA0C16WithGetterSetterRzlF
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T
// CHECK: [[WITNESS_FN:%.*]] = witness_method $T, #PropertyWithGetterSetter.b!materializeForSet.1
// CHECK: [[RESULT:%.*]] = apply [[WITNESS_FN]]<T>
// CHECK: [[TEMPORARY:%.*]] = tuple_extract [[RESULT]]
// CHECK: [[CALLBACK:%.*]] = tuple_extract [[RESULT]]
// CHECK: [[TEMPORARY_ADDR_TMP:%.*]] = pointer_to_address [[TEMPORARY]] : $Builtin.RawPointer to [strict] $*Int
// CHECK: [[TEMPORARY_ADDR:%.*]] = mark_dependence [[TEMPORARY_ADDR_TMP]] : $*Int on [[WRITE]] : $*T
// CHECK: [[MODIFY_FN:%.*]] = function_ref @_T09protocols6modifyySizF
// CHECK: apply [[MODIFY_FN]]([[TEMPORARY_ADDR]])
// CHECK: switch_enum [[CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2
// CHECK: bb1([[CALLBACK_ADDR:%.*]] : @trivial $Builtin.RawPointer):
// CHECK: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]]
// CHECK: [[METATYPE:%.*]] = metatype $@thick T.Type
// CHECK: [[TEMPORARY:%.*]] = address_to_pointer [[TEMPORARY_ADDR]] : $*Int to $Builtin.RawPointer
// CHECK: apply [[CALLBACK]]<T>
// CHECK-LABEL: sil_witness_table hidden ClassWithGetter: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter.1: {{.*}} : @_T09protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSivgTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetterSetter module protocols {
// CHECK-NEXT: method #PropertyWithGetterSetter.b!getter.1: {{.*}} : @_T09protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivgTW
// CHECK-NEXT: method #PropertyWithGetterSetter.b!setter.1: {{.*}} : @_T09protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivsTW
// CHECK-NEXT: method #PropertyWithGetterSetter.b!materializeForSet.1: {{.*}} : @_T09protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivmTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter.1: {{.*}} : @_T09protocols21ClassWithGetterSetterCAA08PropertycD0A2aDP1aSivgTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden StructWithStoredProperty: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter.1: {{.*}} : @_T09protocols24StructWithStoredPropertyVAA0eC6GetterA2aDP1aSivgTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden StructWithStoredClassProperty: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter.1: {{.*}} : @_T09protocols29StructWithStoredClassPropertyVAA0fC6GetterA2aDP1aSivgTW
// CHECK-NEXT: }
| apache-2.0 | a81f891329f5014f257737604023a5a3 | 49.956621 | 272 | 0.642636 | 3.806754 | false | false | false | false |
adrfer/swift | test/Serialization/print.swift | 20 | 1020 | // RUN: rm -rf %t
// RUN: mkdir %t
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t %s
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -print-module -skip-deinit=false -module-to-print=print -I %t -source-filename=%s | FileCheck %s
// REQUIRES: objc_interop
import Foundation
// CHECK-LABEL: class PropertyOwnership {
class PropertyOwnership {
// CHECK-NEXT: @NSCopying var copying: NSCopying?
@NSCopying var copying: NSCopying?
// CHECK-NEXT: weak var weakVar: @sil_weak AnyObject?
weak var weakVar: AnyObject?
// CHECK-NEXT: unowned var unownedVar: @sil_unowned PropertyOwnership
unowned var unownedVar: PropertyOwnership
// CHECK-NEXT: unowned(unsafe) var unownedUnsafeVar: @sil_unmanaged PropertyOwnership
unowned(unsafe) var unownedUnsafeVar: PropertyOwnership
// CHECK-NEXT: init(other: PropertyOwnership)
init(other: PropertyOwnership) {
unownedVar = other
unownedUnsafeVar = other
}
// CHECK-NEXT: deinit
} // CHECK-NEXT: }
| apache-2.0 | 36bb6d137624d8c9491ce3836bd7dd7c | 36.777778 | 158 | 0.72451 | 3.736264 | false | false | false | false |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/PhotoLibraryV2/View/PhotoLibraryV2ViewController.swift | 1 | 7889 | import AVFoundation
import ImageSource
import UIKit
final class PhotoLibraryV2ViewController: PaparazzoViewController, PhotoLibraryV2ViewInput, ThemeConfigurable {
typealias ThemeType = PhotoLibraryV2UITheme & NewCameraUITheme
private let photoLibraryView: PhotoLibraryV2View
var previewLayer: AVCaptureVideoPreviewLayer? {
return photoLibraryView.previewLayer
}
init(isNewFlowPrototype: Bool) {
photoLibraryView = PhotoLibraryV2View(isNewFlowPrototype: isNewFlowPrototype)
super.init()
if isNewFlowPrototype {
transitioningDelegate = PhotoLibraryToCameraTransitioningDelegate.shared
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - PhotoLibraryV2ViewController
func previewFrame(forBounds bounds: CGRect) -> CGRect {
return photoLibraryView.previewFrame(forBounds: bounds)
}
func setPreviewLayer(_ previewLayer: AVCaptureVideoPreviewLayer?) {
photoLibraryView.setPreviewLayer(previewLayer)
}
// MARK: - UIViewController
override func loadView() {
view = photoLibraryView
}
override func viewDidLoad() {
super.viewDidLoad()
onViewDidLoad?()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
if !UIDevice.current.hasTopSafeAreaInset {
UIApplication.shared.setStatusBarHidden(true, with: animated ? .fade : .none)
}
onViewWillAppear?()
}
override var prefersStatusBarHidden: Bool {
return !UIDevice.current.hasTopSafeAreaInset
}
// MARK: - ThemeConfigurable
func setTheme(_ theme: ThemeType) {
self.theme = theme
photoLibraryView.setTheme(theme)
}
// MARK: - PhotoLibraryViewInput
var onItemSelect: ((PhotoLibraryItem) -> ())?
var onViewDidLoad: (() -> ())?
var onViewWillAppear: (() -> ())?
var onTitleTap: (() -> ())? {
get { return photoLibraryView.onTitleTap }
set { photoLibraryView.onTitleTap = newValue }
}
var onContinueButtonTap: (() -> ())? {
get { return photoLibraryView.onContinueButtonTap }
set { photoLibraryView.onContinueButtonTap = newValue }
}
var onCloseButtonTap: (() -> ())? {
get { return photoLibraryView.onCloseButtonTap }
set { photoLibraryView.onCloseButtonTap = newValue }
}
var onAccessDeniedButtonTap: (() -> ())? {
get { return photoLibraryView.onAccessDeniedButtonTap }
set { photoLibraryView.onAccessDeniedButtonTap = newValue }
}
var onDimViewTap: (() -> ())? {
get { return photoLibraryView.onDimViewTap }
set { photoLibraryView.onDimViewTap = newValue }
}
var onLastPhotoThumbnailTap: (() -> ())? {
get { return photoLibraryView.onLastPhotoThumbnailTap }
set { photoLibraryView.onLastPhotoThumbnailTap = newValue }
}
@nonobjc func setTitle(_ title: String) {
photoLibraryView.setTitle(title)
}
func setTitleVisible(_ visible: Bool) {
photoLibraryView.setTitleVisible(visible)
}
func setContinueButtonTitle(_ title: String) {
photoLibraryView.setContinueButtonTitle(title)
}
func setContinueButtonVisible(_ isVisible: Bool) {
photoLibraryView.setContinueButtonVisible(isVisible)
}
func setContinueButtonStyle(_ style: MediaPickerContinueButtonStyle) {
photoLibraryView.setContinueButtonStyle(style)
}
func setContinueButtonPlacement(_ placement: MediaPickerContinueButtonPlacement) {
photoLibraryView.setContinueButtonPlacement(placement)
}
func setPlaceholderState(_ state: PhotoLibraryPlaceholderState) {
switch state {
case .hidden:
photoLibraryView.setPlaceholderVisible(false)
case .visible(let title):
photoLibraryView.setPlaceholderTitle(title)
photoLibraryView.setPlaceholderVisible(true)
}
}
func setCameraViewData(_ viewData: PhotoLibraryCameraViewData?) {
photoLibraryView.setCameraViewData(viewData)
}
func setItems(_ items: [PhotoLibraryItemCellData], scrollToTop: Bool, completion: (() -> ())?) {
photoLibraryView.setItems(items, scrollToTop: scrollToTop, completion: completion)
}
func applyChanges(_ changes: PhotoLibraryViewChanges, completion: (() -> ())?) {
photoLibraryView.applyChanges(changes, completion: completion)
}
func setCanSelectMoreItems(_ canSelectMoreItems: Bool) {
photoLibraryView.canSelectMoreItems = canSelectMoreItems
}
func setDimsUnselectedItems(_ dimUnselectedItems: Bool) {
photoLibraryView.dimsUnselectedItems = dimUnselectedItems
}
func deselectItem(with imageSource: ImageSource) -> Bool {
return photoLibraryView.deselectCell(with: imageSource)
}
func deselectAllItems() {
photoLibraryView.deselectAndAdjustAllCells()
}
func reloadSelectedItems() {
photoLibraryView.reloadSelectedItems()
}
func setAccessDeniedViewVisible(_ visible: Bool) {
photoLibraryView.setAccessDeniedViewVisible(visible)
}
func setAccessDeniedTitle(_ title: String) {
photoLibraryView.setAccessDeniedTitle(title)
}
func setAccessDeniedMessage(_ message: String) {
photoLibraryView.setAccessDeniedMessage(message)
}
func setAccessDeniedButtonTitle(_ title: String) {
photoLibraryView.setAccessDeniedButtonTitle(title)
}
func setProgressVisible(_ visible: Bool) {
photoLibraryView.setProgressVisible(visible)
}
func setHeaderVisible(_ visible: Bool) {
photoLibraryView.setHeaderVisible(visible)
}
func setAlbums(_ albums: [PhotoLibraryAlbumCellData]) {
photoLibraryView.setAlbums(albums)
}
func selectAlbum(withId id: String) {
photoLibraryView.selectAlbum(withId: id)
}
func showAlbumsList() {
photoLibraryView.showAlbumsList()
}
func hideAlbumsList() {
photoLibraryView.hideAlbumsList()
}
func toggleAlbumsList() {
photoLibraryView.toggleAlbumsList()
}
func setSelectedPhotosBarState(_ state: SelectedPhotosBarState) {
photoLibraryView.setSelectedPhotosBarState(state)
}
func setDoneButtonTitle(_ title: String) {
photoLibraryView.setDoneButtonTitle(title)
}
func setPlaceholderText(_ text: String) {
photoLibraryView.setPlaceholderText(text)
}
// MARK: - Orientation
override public var shouldAutorotate: Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .pad {
return .all
} else {
return .portrait
}
}
override public var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
if UIDevice.current.userInterfaceIdiom == .pad {
return super.preferredInterfaceOrientationForPresentation
} else {
return .portrait
}
}
// MARK: - Private
private var theme: PhotoLibraryV2UITheme?
@objc private func onCloseButtonTap(_ sender: UIBarButtonItem) {
onCloseButtonTap?()
}
@objc private func onContinueButtonTap(_ sender: UIBarButtonItem) {
onContinueButtonTap?()
}
}
| mit | dd35f715c7e5343a0fb87883b522a065 | 29.226054 | 111 | 0.657751 | 5.704266 | false | false | false | false |
thatseeyou/iOSSDKExamples | Pages/transform.rotation.y.xcplaygroundpage/Contents.swift | 1 | 1327 | import UIKit
class ViewController : UIViewController {
var targetView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = [#Color(colorLiteralRed: 0.7602152824401855, green: 0.7601925134658813, blue: 0.7602053880691528, alpha: 1)#]
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let label = UILabel()
label.text = "I'm target view"
label.sizeToFit()
label.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds))
self.targetView = label
self.view.addSubview(self.targetView)
Utility.runActionAfterTime(1) { [unowned self ] in
self.pop()
}
}
func pop() {
let animation = CABasicAnimation(keyPath: "transform.rotation.y")
animation.fromValue = 0.0
animation.toValue = M_PI * 2.0
animation.duration = 2.0
animation.repeatCount = Float.infinity
self.targetView.layer.addAnimation(animation, forKey: "spin")
// 가까우면 크게 멀면 작게
var transform = CATransform3DIdentity
transform.m34 = 5.0 / 500.0
self.targetView.layer.transform = transform
}
}
PlaygroundHelper.showViewController(ViewController())
| mit | 020514729d86aaebe392ae48b67d67fe | 26.229167 | 145 | 0.648814 | 4.16242 | false | false | false | false |
nacuteodor/ProcessTestSummaries | XCResultKit/ActionsInvocationRecord.swift | 1 | 1202 | //
// File.swift
//
//
// Created by David House on 6/30/19.
//
// Version: 3.19
//
// - ActionsInvocationRecord
// * Kind: object
// * Properties:
// + metadataRef: Reference?
// + metrics: ResultMetrics
// + issues: ResultIssueSummaries
// + actions: [ActionRecord]
// + archive: ArchiveInfo?
import Foundation
public struct ActionsInvocationRecord: XCResultObject {
public let metadataRef: Reference?
public let metrics: ResultMetrics
public let issues: ResultIssueSummaries
public let actions: [ActionRecord]
public let archive: ArchiveInfo?
public init?(_ json: [String: AnyObject]) {
do {
metrics = try xcRequired(element: "metrics", from: json)
issues = try xcRequired(element: "issues", from: json)
metadataRef = xcOptional(element: "metadataRef", from: json)
archive = xcOptional(element: "archive", from: json)
actions = xcArray(element: "actions", from: json).compactMap { ActionRecord($0) }
} catch {
print("Error parsing ActionsInvocationRecord: \(error.localizedDescription)")
return nil
}
}
}
| mit | 7282750d8de6b16c6362d4e2321246ca | 29.05 | 93 | 0.616473 | 4.116438 | false | false | false | false |
mirego/PinLayout | Tests/Common/WarningSpec.swift | 1 | 2630 | // Copyright (c) 2017 Luc Dion
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Quick
import Nimble
import PinLayout
class WarningSpec: QuickSpec {
override func spec() {
var viewController: PViewController!
var rootView: BasicView!
var aView: BasicView!
/*
root
|
- aView
*/
beforeEach {
_pinlayoutSetUnitTest(scale: 2)
Pin.lastWarningText = nil
viewController = PViewController()
viewController.view = BasicView()
rootView = BasicView()
rootView.frame = CGRect(x: 0, y: 0, width: 400, height: 400)
viewController.view.addSubview(rootView)
aView = BasicView()
aView.frame = CGRect(x: 40, y: 100, width: 100, height: 60)
aView.sizeThatFitsExpectedArea = 40 * 40
rootView.addSubview(aView)
}
afterEach {
_pinlayoutSetUnitTest(scale: nil)
}
//
// pinEdges warnings
//
describe("pinEdges() should warn ") {
it("test when top, left, bottom and right is set") {
aView.pin.top().bottom().left().right().width(100%).pinEdges()
expect(aView.frame).to(equal(CGRect(x: 0.0, y: 0.0, width: 400.0, height: 400.0)))
expect(Pin.lastWarningText).to(contain(["pinEdges()", "won't be applied", "top, left, bottom and right coordinates are already set"]))
}
}
}
}
| mit | f116365b9c81f3bc6848e372c0e021f1 | 37.676471 | 150 | 0.619392 | 4.581882 | false | false | false | false |
cuappdev/podcast-ios | old/Podcast/SearchFooterView.swift | 1 | 2331 | //
// SearchFooterView.swift
// Podcast
//
// Created by Jack Thompson on 5/2/18.
// Copyright © 2018 Cornell App Development. All rights reserved.
//
import UIKit
protocol SearchFooterDelegate: class {
func searchFooterDidPress(searchFooter: SearchFooterView)
}
class SearchFooterView: UIView {
static let height:CGFloat = 100
var noResultsLabel: UILabel!
var searchITunesLabel: UILabel!
let itunesLabelHeight:CGFloat = 34
var topPadding: CGFloat = 20
var padding: CGFloat = 12.5
let margins: CGFloat = 70
weak var delegate: SearchFooterDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
noResultsLabel = UILabel()
noResultsLabel.text = "Can't find a series you're looking for?"
noResultsLabel.textColor = .slateGrey
noResultsLabel.font = ._14RegularFont()
noResultsLabel.textAlignment = .center
addSubview(noResultsLabel)
noResultsLabel.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(topPadding)
make.leading.trailing.equalToSuperview()
}
searchITunesLabel = UILabel()
searchITunesLabel.font = ._14RegularFont()
searchITunesLabel.textColor = .slateGrey
let attributedText = NSMutableAttributedString(string: "Search the web to add more series to our collection.")
attributedText.addAttribute(.foregroundColor, value: UIColor.sea, range: NSRange(location: 0, length: 15))
searchITunesLabel.attributedText = attributedText
searchITunesLabel.textAlignment = .center
searchITunesLabel.numberOfLines = 2
addSubview(searchITunesLabel)
searchITunesLabel.snp.makeConstraints { (make) in
make.height.equalTo(itunesLabelHeight)
make.leading.trailing.equalToSuperview().inset(margins)
make.top.equalTo(noResultsLabel.snp.bottom).offset(padding)
}
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapSearch)))
}
@objc func didTapSearch() {
delegate?.searchFooterDidPress(searchFooter: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 436985c675aebfeccad433bf4a10dc45 | 31.816901 | 118 | 0.672103 | 5.132159 | false | false | false | false |
flow-ai/flowai-swift | FlowCore/Classes/Button.swift | 1 | 1056 | //
// buttons.swift
// Pods
//
// Created by Gijs van de Nieuwegiessen on 06/04/2017.
//
//
import Foundation
import HandyJSON
public class Button : HandyJSON {
/// Label of the button
private(set) public var label: String!
/// Payload or URL
private(set) public var value: String!
/// Action of the button (url, postback, webview)
private(set) public var type: String!
init(_ data: [String: Any]) throws {
guard let label = data["label"] as? String else {
throw Exception.Serialzation("button template has no label")
}
self.label = label
guard let value = data["value"] as? String else {
throw Exception.Serialzation("button template has no value")
}
self.value = value
guard let type = data["type"] as? String else {
throw Exception.Serialzation("button template has no type")
}
self.type = type
}
public required init() {}
}
| mit | 8ec73b02d352a27060966436832e891d | 22.466667 | 72 | 0.564394 | 4.455696 | false | false | false | false |
GeekSpeak/GeekSpeak-Show-Timer | GeekSpeak Show Timer/BreakCount-3/Timer.swift | 2 | 10440 | import Foundation
import CoreGraphics
let oneMinute = TimeInterval(60)
let timerUpdateInterval = TimeInterval(0.06)
// MARK: -
// MARK: Timer class
final class Timer: NSObject {
struct Constants {
static let TimeChange = "kGPTTimeChange"
static let CountingStatusChanged = "kGPTCountingStatusChanged"
static let DurationChanged = "kGPTDurationChanged"
static let UseDemoDurations = "useDemoDurations"
static let UUIDId = "timerUUIDId"
static let DemoId = "timerDemoId"
static let StateId = "timerCountingStateId"
static let PhaseId = "timerShowTimingPhaseId"
static let CountingStartTimeId = "timerCountingStartTimeId"
struct Durations {
static let PreShowId = "timerShowTimingDurationPreShowId"
static let Section1Id = "timerShowTimingDurationSection1Id"
static let Section2Id = "timerShowTimingDurationSection2Id"
static let Section3Id = "timerShowTimingDurationSection3Id"
static let Break1Id = "timerShowTimingDurationBreak1Id"
static let Break2Id = "timerShowTimingDurationBreak2Id"
}
struct ElapsedTime {
static let PreShowId = "timerShowTimingElapsedPreShowId"
static let Section1Id = "timerShowTimingElapsedSection1Id"
static let Section2Id = "timerShowTimingElapsedSection2Id"
static let Section3Id = "timerShowTimingElapsedSection3Id"
static let Break1Id = "timerShowTimingElapsedBreak1Id"
static let Break2Id = "timerShowTimingElapsedBreak2Id"
static let PostShowId = "timerShowTimingElapsedPostShowId"
}
}
// MARK: Properties
var uuid = UUID()
var countingStartTime: TimeInterval?
var timing = ShowTiming()
var demoTimings = false
// MARK: Computed Properties
var state: CountingState {
get {
return _state
}
set(newState) {
changeCountingState(newState)
}
}
var secondsElapsedAtPause: TimeInterval {
get {
return timing.elapsed
}
set(newElapsed) {
timing.elapsed = newElapsed
}
}
var duration: TimeInterval {
get {
return timing.duration
}
set(newDuration) {
timing.duration = newDuration
notifyTimerUpdated()
notifyTimerDurationUpdated()
}
}
var secondsElapsed: TimeInterval {
var secondsElapsed: TimeInterval
if let countingStartTime = countingStartTime {
let now = Date.timeIntervalSinceReferenceDate
secondsElapsed = now - countingStartTime + secondsElapsedAtPause
} else {
secondsElapsed = secondsElapsedAtPause
}
return secondsElapsed
}
var secondsRemaining: TimeInterval {
let seconds = duration - secondsElapsed
return max(seconds,0)
}
var totalShowTimeRemaining: TimeInterval {
switch timing.phase {
case .PreShow, .Break1, .Break2, .PostShow:
return max(timing.totalShowTimeRemaining,0)
case .Section1, .Section2, .Section3:
return max(timing.totalShowTimeRemaining - secondsElapsed,0)
}
}
var totalShowTimeElapsed: TimeInterval {
switch timing.phase {
case .PreShow, .Break1, .Break2, .PostShow:
return max(timing.totalShowTimeElapsed,0)
case .Section1, .Section2, .Section3:
return max(timing.totalShowTimeElapsed + secondsElapsed,0)
}
}
var percentageRemaining: CGFloat {
return secondsToPercentage(secondsRemaining)
}
var percentageComplete: CGFloat {
return 1.0 - percentageRemaining
}
func percentageComplete(_ phase: ShowPhase) -> CGFloat {
var percentageComplete = Double(0.0)
switch phase {
case .PreShow,
.Break1,
.Break2:
percentageComplete = Double(self.percentageComplete)
case .Section1:
// let a = timing.durations.section1
// let b = timing.timeElapsed.section1
// percentageComplete = 1 - ((a - b) / a)
percentageComplete = (timing.durations.section1 - timing.timeElapsed.section1) /
timing.durations.section1
case .Section2:
percentageComplete = (timing.durations.section2 - timing.timeElapsed.section2) /
timing.durations.section2
case .Section3:
percentageComplete = (timing.durations.section3 - timing.timeElapsed.section3) /
timing.durations.section3
case .PostShow:
percentageComplete = 0.0
}
return CGFloat(percentageComplete)
}
var percentageCompleteUnlimited: CGFloat {
// The secondsRemaining computed property is limited so that
// it can not be less than 0. This property is unlimited allowing
// percentageComplete to be greater than 1.0
let percentageRemaining = secondsToPercentage(duration - secondsElapsed)
let percentageComplete = 1.0 - percentageRemaining
return percentageComplete
}
func percentageFromSeconds(_ seconds: TimeInterval) -> Double {
let percent = seconds / duration
return percent
}
func percentageFromSecondsToEnd(_ seconds: TimeInterval) -> Double {
let percent = 1 - (seconds / duration)
return percent
}
// MARK: Internal Properties
var _state: CountingState = .Ready {
didSet {
onNextRunloopNotifyCountingStateUpdated()
}
}
// MARK: -
// MARK: Initialization
override init() {
super.init()
}
// MARK: -
// MARK: Timer Actions
func changeCountingState(_ state: CountingState) {
switch state {
case .Ready:
reset()
case .Counting,
.CountingAfterComplete:
start()
case .Paused,
.PausedAfterComplete:
pause()
}
}
func reset() {
reset(usingDemoTiming: demoTimings)
}
func reset(usingDemoTiming demoTimings: Bool) {
_state = .Ready
countingStartTime = .none
timing = ShowTiming()
if demoTimings {
timing.durations.useDemoDurations()
self.demoTimings = true
} else {
self.demoTimings = false
}
notifyAll()
}
func start() {
if percentageComplete < 1.0 {
_state = .Counting
} else {
_state = .CountingAfterComplete
}
countingStartTime = Date.timeIntervalSinceReferenceDate
incrementTimer()
}
func pause() {
if percentageComplete < 1.0 {
_state = .Paused
} else {
_state = .PausedAfterComplete
}
storeElapsedTimeAtPause()
}
func next() {
storeElapsedTimeAtPause()
countingStartTime = .none
timing.incrementPhase()
notifyTimerDurationUpdated()
if percentageComplete > 1.0 ||
timing.phase == .PostShow {
if _state == .Counting {
_state = .CountingAfterComplete
}
if _state == .Paused {
_state = .PausedAfterComplete
}
}
switch _state {
case .Ready:
reset()
case .Counting,
.CountingAfterComplete:
start()
case .Paused,
.PausedAfterComplete:
notifyTimerUpdated()
break
}
}
func addTimeBySeconds(_ seconds: TimeInterval) {
timing.duration += seconds
switch state {
case .Ready,
.Paused:
notifyTimerUpdated()
case .Counting,
.PausedAfterComplete,
.CountingAfterComplete:
break
}
}
// MARK: -
// MARK: Notify Observers
fileprivate func notifyTimerUpdated() {
NotificationCenter.default
.post( name: Notification.Name(rawValue: Constants.TimeChange),
object: self)
}
func notifyCountingStateUpdated() {
NotificationCenter.default
.post( name: Notification.Name(rawValue: Constants.CountingStatusChanged),
object: self)
}
fileprivate func notifyTimerDurationUpdated() {
NotificationCenter.default
.post( name: Notification.Name(rawValue: Constants.DurationChanged),
object: self)
}
func notifyAll() {
notifyTimerUpdated()
notifyCountingStateUpdated()
notifyTimerDurationUpdated()
}
// MARK: -
// MARK: Timer
func incrementTimer() {
switch state {
case .Ready:
break
case .Paused,
.PausedAfterComplete:
storeElapsedTimeAtPause()
case .Counting,
.CountingAfterComplete:
notifyTimerUpdated()
checkTimingForCompletion()
incrementTimerAgain()
}
}
func checkTimingForCompletion() {
if timing.durations.advancePhaseOnCompletion(timing.phase) {
if percentageComplete >= 1.0 {
next()
}
}
}
fileprivate func incrementTimerAgain() {
Foundation.Timer.scheduledTimer( timeInterval: timerUpdateInterval,
target: self,
selector: #selector(Timer.incrementTimer),
userInfo: nil,
repeats: false)
}
fileprivate func storeElapsedTimeAtPause() {
secondsElapsedAtPause = secondsElapsed
countingStartTime = .none
}
// MARK: -
// MARK: Helpers
fileprivate func secondsToPercentage(_ secondsRemaining: TimeInterval) -> CGFloat {
return CGFloat(secondsRemaining / duration)
}
// The timerChangedCountingStatus() is intended for acting on a change of state
// only, and not intended as a callback to check property values of the
// Timer class. (hense, only the TimerStatus emum is passed as the sole argument.)
// If this callback IS used to check properties, they may not represent
// the state of the timer correctly since the state is changed first and
// drives rest of the class. Properties sensitive to this are:
// secondsElapsedAtPause
// countingStartTime
// secondsElapsed (computed)
// To mitigate this case, the state callback is delayed until the next
// runloop using NSTimer with a delay of 0.0.
fileprivate func onNextRunloopNotifyCountingStateUpdated() {
Foundation.Timer.scheduledTimer( timeInterval: 0.0,
target: self,
selector: #selector(Timer.notifyCountingStateUpdated),
userInfo: nil,
repeats: false)
}
}
| mit | b0bb2a16bb54b1234ae8601536fdb138 | 26.84 | 98 | 0.633046 | 4.985673 | false | false | false | false |
zyphs21/HSStockChart | HSStockChart/Helpers/Extension.swift | 1 | 4475 | //
// Extension.swift
// MyStockChartDemo
//
// Created by Hanson on 16/8/17.
// Copyright © 2016年 hanson. All rights reserved.
//
import Foundation
import UIKit
// MARK: - UIColor Extension
extension UIColor: NameSpaceProtocol { }
extension NameSpaceWrapper where T: UIColor {
public static func color(rgba: String) -> UIColor {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
var hexStr = (rgba as NSString).substring(from: 1) as NSString
if hexStr.length == 8 {
let alphaHexStr = hexStr.substring(from: 6)
hexStr = hexStr.substring(to: 6) as NSString
var alphaHexValue: UInt32 = 0
let alphaScanner = Scanner(string: alphaHexStr)
if alphaScanner.scanHexInt32(&alphaHexValue) {
let alphaHex = Int(alphaHexValue)
alpha = CGFloat(alphaHex & 0x000000FF) / 255.0
} else {
print("scan alphaHex error")
}
}
let rgbScanner = Scanner(string: hexStr as String)
var hexValue: UInt32 = 0
if rgbScanner.scanHexInt32(&hexValue) {
if hexStr.length == 6 {
let hex = Int(hexValue)
red = CGFloat((hex & 0xFF0000) >> 16) / 255.0
green = CGFloat((hex & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hex & 0x0000FF) / 255.0
} else {
print("invalid rgb string, length should be 6")
}
} else {
print("scan hex error")
}
} else {
print("invalid rgb string, missing '#' as prefix")
}
return UIColor(red:red, green:green, blue:blue, alpha:alpha)
}
}
// MARK: - CGFloat Extension
extension CGFloat: NameSpaceProtocol { }
extension NameSpaceWrapper where T == CGFloat {
/// 输出格式化的String
///
/// - Parameter format: eg: ".2" 保留两位小数
/// - Returns: Formated String
public func toStringWithFormat(_ format: String) -> String {
return String(format: "%\(format)f", wrappedValue)
}
/// 输出为百分数
///
/// - Returns: 以%结尾的 百分数输出
public func toPercentFormat() -> String {
return String(format: "%.2f", wrappedValue) + "%"
}
}
// MARK: - String Extension
extension String: NameSpaceProtocol { }
extension NameSpaceWrapper where T == String {
public func toDate(_ format: String) -> Date? {
let dateformatter = DateFormatter.hschart.cached(withFormat: format)
dateformatter.timeZone = TimeZone.autoupdatingCurrent
return dateformatter.date(from: wrappedValue)
}
}
// MARK: - DateFormatter Extension
private var cachedFormatters = [String: DateFormatter]()
extension DateFormatter: NameSpaceProtocol {}
extension NameSpaceWrapper where T: DateFormatter {
public static func cached(withFormat format: String) -> DateFormatter {
if let cachedFormatter = cachedFormatters[format] { return cachedFormatter }
let formatter = DateFormatter()
formatter.dateFormat = format
cachedFormatters[format] = formatter
return formatter
}
}
// MARK: - Date Extension
extension Date: NameSpaceProtocol { }
extension NameSpaceWrapper where T == Date {
public func toString(_ format: String) -> String {
let dateformatter = DateFormatter.hschart.cached(withFormat: format)
dateformatter.timeZone = TimeZone.autoupdatingCurrent
return dateformatter.string(from: wrappedValue)
}
public static func toDate(_ dateString: String, format: String) -> Date {
let dateformatter = DateFormatter.hschart.cached(withFormat: format)
dateformatter.locale = Locale(identifier: "en_US")
let date = dateformatter.date(from: dateString) ?? Date()
return date
}
}
// MARK: - Double Extension
extension Double: NameSpaceProtocol { }
extension NameSpaceWrapper where T == Double {
/// %.2f 不带科学计数
public func toStringWithFormat(_ format:String) -> String! {
return NSString(format: format as NSString, wrappedValue) as String
}
}
| mit | f0519d3c1853199d2b54810ca0362205 | 28.77027 | 84 | 0.592601 | 4.692226 | false | false | false | false |
shorlander/firefox-ios | Client/Frontend/Browser/FaviconManager.swift | 3 | 6498 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
import Shared
import Storage
import WebImage
import Deferred
import Sync
class FaviconManager: TabHelper {
static let FaviconDidLoad = "FaviconManagerFaviconDidLoad"
let profile: Profile!
weak var tab: Tab?
static let maximumFaviconSize = 1 * 1024 * 1024 // 1 MiB file size limit
init(tab: Tab, profile: Profile) {
self.profile = profile
self.tab = tab
if let path = Bundle.main.path(forResource: "Favicons", ofType: "js") {
if let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String {
let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
tab.webView!.configuration.userContentController.addUserScript(userScript)
}
}
}
class func name() -> String {
return "FaviconsManager"
}
func scriptMessageHandlerName() -> String? {
return "faviconsMessageHandler"
}
fileprivate func loadFavicons(_ tab: Tab, profile: Profile, favicons: [Favicon]) -> Deferred<[Maybe<Favicon>]> {
var deferreds: [() -> Deferred<Maybe<Favicon>>]
deferreds = favicons.map { favicon in
return { [weak tab] () -> Deferred<Maybe<Favicon>> in
if let tab = tab,
let url = URL(string: favicon.url),
let currentURL = tab.url {
return self.getFavicon(tab, iconUrl: url, currentURL: currentURL, icon: favicon, profile: profile)
} else {
return deferMaybe(FaviconError())
}
}
}
return all(deferreds.map({$0()}))
}
func getFavicon(_ tab: Tab, iconUrl: URL, currentURL: URL, icon: Favicon, profile: Profile) -> Deferred<Maybe<Favicon>> {
let deferred = Deferred<Maybe<Favicon>>()
let manager = SDWebImageManager.shared()
let options = tab.isPrivate ?
[SDWebImageOptions.lowPriority, SDWebImageOptions.cacheMemoryOnly] : [SDWebImageOptions.lowPriority]
let url = currentURL.absoluteString
let site = Site(url: url, title: "")
var fetch: SDWebImageOperation?
fetch = manager?.downloadImage(with: iconUrl,
options: SDWebImageOptions(options),
progress: { (receivedSize, expectedSize) in
if receivedSize > FaviconManager.maximumFaviconSize || expectedSize > FaviconManager.maximumFaviconSize {
fetch?.cancel()
}
},
completed: { (img, err, cacheType, success, url) -> Void in
let fav = Favicon(url: url!.absoluteString,
date: Date(),
type: icon.type)
guard let img = img else {
deferred.fill(Maybe(failure: FaviconError()))
return
}
fav.width = Int(img.size.width)
fav.height = Int(img.size.height)
if !tab.isPrivate {
if tab.favicons.isEmpty {
self.makeFaviconAvailable(tab, atURL: currentURL, favicon: fav, withImage: img)
}
tab.favicons.append(fav)
self.profile.favicons.addFavicon(fav, forSite: site).upon { _ in
deferred.fill(Maybe(success: fav))
}
} else {
tab.favicons.append(fav)
deferred.fill(Maybe(success: fav))
}
})
return deferred
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
self.tab?.favicons.removeAll(keepingCapacity: false)
if let tab = self.tab, let currentURL = tab.url {
var favicons = [Favicon]()
if let icons = message.body as? [String: Int] {
for icon in icons {
if let _ = URL(string: icon.0), let iconType = IconType(rawValue: icon.1) {
let favicon = Favicon(url: icon.0, date: Date(), type: iconType)
favicons.append(favicon)
}
}
}
loadFavicons(tab, profile: profile, favicons: favicons).uponQueue(DispatchQueue.main) { result in
let results = result.flatMap({ $0.successValue })
let faviconsReadOnly = favicons
if results.count == 1 && faviconsReadOnly[0].type == .guess {
// No favicon is indicated in the HTML
self.noFaviconAvailable(tab, atURL: currentURL as URL)
}
NotificationCenter.default.post(name: NSNotification.Name(rawValue: FaviconManager.FaviconDidLoad), object: tab)
}
}
}
func makeFaviconAvailable(_ tab: Tab, atURL url: URL, favicon: Favicon, withImage image: UIImage) {
let helper = tab.getHelper(name: "SpotlightHelper") as? SpotlightHelper
helper?.updateImage(image, forURL: url)
}
func noFaviconAvailable(_ tab: Tab, atURL url: URL) {
let helper = tab.getHelper(name: "SpotlightHelper") as? SpotlightHelper
helper?.updateImage(forURL: url)
}
}
class FaviconError: MaybeErrorType {
internal var description: String {
return "No Image Loaded"
}
}
| mpl-2.0 | 4da03627ef6627237873f189caf26b77 | 45.085106 | 145 | 0.510465 | 5.650435 | false | false | false | false |
cxchope/NyaaCatAPP_iOS | nyaacatapp/AppDelegate.swift | 1 | 5232 | //
// AppDelegate.swift
// nyaacatapp
//
// Created by 神楽坂雅詩 on 16/2/11.
// Copyright © 2016年 KagurazakaYashi. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UITabBarControllerDelegate {
var window: UIWindow?
var 主视图:MainTBC? = nil
func applicationDidFinishLaunching(_ application: UIApplication) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
应用初始化()
let 屏幕尺寸:CGRect = UIScreen.main.bounds
let 主窗口:UIWindow = UIWindow(frame: 屏幕尺寸)
let 主故事板:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
主视图 = 主故事板.instantiateViewController(withIdentifier: "MainTBC") as? MainTBC
主视图!.delegate = self
主窗口.rootViewController = 主视图
self.window = 主窗口
self.window!.makeKeyAndVisible()
}
// private func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// self.window = 加载测试用窗口()
// self.window!.makeKeyAndVisible()
// return true
// }
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if (全局_用户名 == nil) {
if ((viewController as? StatusNC) != nil || (viewController as? DMChatNC) != nil || (viewController as? MapNC) != nil) {
主视图?.游客模式阻止(viewController.title)
return false
}
}
return true
}
func 加载测试用窗口() -> UIWindow {
let 屏幕尺寸:CGRect = UIScreen.main.bounds
let 主窗口:UIWindow = UIWindow(frame: 屏幕尺寸)
let 视图:UIViewController = UIViewController()
视图.view.backgroundColor = UIColor.lightGray
主窗口.rootViewController = 视图
return 主窗口
}
func 应用初始化() {
UIApplication.shared.statusBarStyle = .lightContent
APILoader().loadPrivateConstant()
}
private func application(_ app: UIApplication, open url: URL, options: [String : AnyObject]) -> Bool {
print("URL scheme:%@", url.scheme);
//NSLog("URL query: %@", url.query!);
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 全局_调整计时器延迟(_ 电池供电时:TimeInterval,外接电源时:TimeInterval) {
if (全局_设备信息.batteryState == .charging || 全局_设备信息.batteryState == .full){
全局_刷新延迟 = 外接电源时
} else {
全局_刷新延迟 = 电池供电时
}
NotificationCenter.default.post(name: Notification.Name(rawValue: "timerset"), object: nil)
}
//全局
let 全局_导航栏颜色:UIColor = UIColor(red: 1, green: 153/255.0, blue: 203/255.0, alpha: 1)
var 全局_刷新延迟:TimeInterval = 2.5 //1.0快速,2.5标准, 6.0节能,0.2模拟器压力测试,0.5真机压力测试
var 全局_综合信息:Dictionary<String,NSObject>? = nil
var 全局_用户名:String? = nil
var 全局_密码:String? = nil
var 全局_游客模式:Bool = false
let 全局_手机发送消息关键字:String = "[NyaaCatAPP] "
let 全局_设备信息:UIDevice = UIDevice.current
var 全局_喵窩API:Dictionary<String,String> = Dictionary<String,String>()
let 全局_浏览器标识:String = "Mozilla/5.0 (kagurazaka-browser)"
let 全局_缓存策略:NSURLRequest.CachePolicy = .reloadIgnoringLocalCacheData
| gpl-3.0 | 1b36638306a799a7eee9aa4ef0a840b5 | 41.258929 | 285 | 0.692373 | 4.298819 | false | false | false | false |
SteerClearWM/Steer-Clear-IOS | Steer Clear/ViewController.swift | 2 | 22652 | //
// ViewController.swift
// Steer Clear
//
// Created by Ulises Giacoman on 5/15/15.
// Copyright (c) 2015 Steer-Clear. All rights reserved.
//
import UIKit
import Foundation
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var usernameTextbox: UITextField!
@IBOutlet weak var passwordTextbox: UITextField!
@IBOutlet weak var phoneTextbox: UITextField!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var passwordLabel: UILabel!
@IBOutlet weak var phoneLabel: UILabel!
@IBOutlet weak var usernameIcon: UILabel!
@IBOutlet weak var passwordIcon: UILabel!
@IBOutlet weak var phoneIcon: UILabel!
@IBOutlet weak var usernameUnderlineLabel: UIView!
@IBOutlet weak var phoneUnderlineLabel: UIView!
@IBOutlet weak var passwordUnderlineLabel: UIView!
@IBOutlet weak var loginBtn: UIButton!
@IBOutlet weak var createAnAccountLabel: UIButton!
@IBOutlet weak var steerClearLogo: UIImageView!
let defaults = NSUserDefaults.standardUserDefaults()
var isRotating = false
var shouldStopRotating = false
var offset: CGFloat = 500
var myString:NSString = "Don't have an account? REGISTER"
var cancelNSString:NSString = "Cancel"
var cancelMutableString = NSMutableAttributedString()
var registerMutableString = NSMutableAttributedString()
var startX = CGFloat()
var startXphoneTextBox = CGFloat()
var startXphonelabel = CGFloat()
var startXphoneUnderline = CGFloat()
var endXphoneTextBox = CGFloat()
var endXphonelabel = CGFloat()
var endXphoneUnderline = CGFloat()
var keyboardUp = false
var settings = Settings()
override func viewDidLoad() {
print("----------------------------------------------------------------------------------------")
print("ViewController: Initializing ViewController")
super.viewDidLoad()
design()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
view.addGestureRecognizer(tap)
self.usernameTextbox.delegate = self;
self.passwordTextbox.delegate = self;
if self.defaults.stringForKey("lastUser") != nil {
self.usernameTextbox.text = self.defaults.stringForKey("lastUser")!
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
let name = "ViewController"
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: name)
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
hidePhoneLabels()
}
override func viewDidAppear(animated: Bool) {
getPhoneLabelsLocation()
movePhoneLabelsOffScreen(false)
self.startX = self.loginBtn.frame.origin.x
checkUser()
usernameTextbox.delegate = self
passwordTextbox.delegate = self
self.usernameTextbox.nextField = self.passwordTextbox
}
/*
loginButton
-----------
Attempts to log the user into the system
*/
@IBAction func login(sender: AnyObject) {
// grab username and password fields and check if they are not null
print("ViewController: Attempting to login...")
let username = usernameTextbox.text
let password = passwordTextbox.text
let phone = phoneTextbox.text
if (username!.isEmpty) || (password!.isEmpty) {
print("ViewController: Not all fields are filled.")
jiggleLogin()
self.displayAlert("Form Error", message: "Please make sure you have filled all fields.")
} else {
print("ViewController: Sending LOGIN network request.")
if loginBtn.titleLabel?.text == "LOGIN" {
if self.isRotating == false {
self.steerClearLogo.rotate360Degrees(completionDelegate: self)
// Perhaps start a process which will refresh the UI...
}
// else try to log the user in
SCNetwork.login(
username!,
password: password!,
completionHandler: {
success, message in
if(!success) {
// can't make UI updates from background thread, so we need to dispatch
// them to the main thread
dispatch_async(dispatch_get_main_queue(), {
print("ViewController: Login failed ~ \(message)")
self.jiggleLogin()
self.displayAlert("Login Error", message: message)
self.shouldStopRotating = true
})
}
else {
// can't make UI updates from background thread, so we need to dispatch
// them to the main thread
dispatch_async(dispatch_get_main_queue(), {
print("ViewController: Login successful, seguing towards MapViewController.")
self.shouldStopRotating = true
self.phoneTextbox.hidden = true
self.phoneLabel.hidden = true
self.phoneUnderlineLabel.hidden = true
let cookies: NSArray = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies as NSArray!
Cookies.setCookiesWithArr(cookies)
self.defaults.setObject("\(username!)", forKey: "lastUser")
self.performSegueWithIdentifier("loginRider", sender: self)
})
}
})
}
else {
print("ViewController: Attempting to register...")
if (phone!.isEmpty) {
print("ViewController: Not all fields are filled.")
jiggleLogin()
self.displayAlert("Form Error", message: "Please make sure you have filled all fields.")
} else {
print("ViewController: Sending register network request.")
SCNetwork.register(
username!,
password: password!,
phone: phone!,
completionHandler: {
success, message in
// can't make UI updates from background thread, so we need to dispatch
// them to the main thread
dispatch_async(dispatch_get_main_queue(), {
// check if registration succeeds
if(!success) {
print("ViewController: Registration Error ~ \(message)")
self.displayAlert("Registration Error", message: message)
} else {
// if it succeeded, log user in and change screens to
print("ViewController: Sending LOGIN network request.")
SCNetwork.login(
username!,
password: password!,
completionHandler: {
success, message in
if(!success) {
//can't make UI updates from background thread, so we need to dispatch
// them to the main thread
dispatch_async(dispatch_get_main_queue(), {
print("ViewController: Login failed ~ \(message)")
self.displayAlert("Login Error", message: message)
})
}
else {
//can't make UI updates from background thread, so we need to dispatch
// them to the main thread
dispatch_async(dispatch_get_main_queue(), {
print("ViewController: Login successful, seguing towards MapViewController.")
let cookies: NSArray = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies as NSArray!
Cookies.setCookiesWithArr(cookies)
self.defaults.setObject("\(username!)", forKey: "lastUser")
self.performSegueWithIdentifier("loginRider", sender: self)
})
}
})
}
})
}
)
}
}
}
}
/*
registerButton
--------------
Redirects user to Registration Page
*/
@IBAction func registerButton(sender: AnyObject) {
if createAnAccountLabel.titleLabel!.text == "Don't have an account? REGISTER" {
print("ViewController: User pressed Registration button, updating UI to show phone label.")
unHidePhoneLabels()
movePhoneLabelsOnScreen()
createAnAccountLabel.setAttributedTitle(self.cancelMutableString, forState: UIControlState.Normal)
loginBtn.setTitle("REGISTER", forState: UIControlState.Normal)
self.usernameTextbox.attributedPlaceholder = NSAttributedString(string:"W&M USERNAME (treveley)", attributes: [NSForegroundColorAttributeName: UIColor.grayColor()])
loginBtn.backgroundColor = UIColor.whiteColor()
loginBtn.setTitleColor(settings.wmGreen , forState: UIControlState.Normal)
}
else {
print("ViewController: User pressed Registration button, updating UI to hide phone label.")
movePhoneLabelsOffScreen(true)
createAnAccountLabel.setAttributedTitle(registerMutableString, forState: UIControlState.Normal)
loginBtn.setTitle("LOGIN", forState: UIControlState.Normal)
self.usernameTextbox.attributedPlaceholder = NSAttributedString(string:"W&M USERNAME", attributes: [NSForegroundColorAttributeName: UIColor.grayColor()])
loginBtn.backgroundColor = UIColor.clearColor()
loginBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
}
}
/*
design
------
Implements the following styles to the username and password textboxes in the Storyboard ViewController:
UsernameTextbox: change placeholder text white
PasswordTextbox: change placeholder text white
*/
func design() {
// Colors
self.loginBtn.layer.borderWidth = 2
self.loginBtn.layer.borderColor = UIColor.whiteColor().CGColor
// Username text box
usernameTextbox.layer.masksToBounds = true
self.usernameTextbox.attributedPlaceholder = NSAttributedString(string:self.usernameTextbox.placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.grayColor()])
// Password text box
self.passwordTextbox.attributedPlaceholder = NSAttributedString(string:self.passwordTextbox.placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.grayColor()])
self.phoneTextbox.attributedPlaceholder = NSAttributedString(string:self.phoneTextbox.placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.grayColor()])
cancelMutableString = NSMutableAttributedString(string: cancelNSString as String, attributes: [NSFontAttributeName:UIFont(name: "Avenir Next", size: 15.0)!])
registerMutableString = NSMutableAttributedString(string: myString as String, attributes: [NSFontAttributeName:UIFont(name: "Avenir Next", size: 15.0)!])
registerMutableString.addAttribute(NSForegroundColorAttributeName, value: settings.spiritGold, range: NSRange(location:23,length:8))
createAnAccountLabel.setAttributedTitle(registerMutableString, forState: UIControlState.Normal)
}
func checkUser() {
if isAppAlreadyLaunchedOnce() == false {
phoneTextbox.hidden = false
phoneLabel.hidden = false
phoneUnderlineLabel.hidden = false
self.phoneTextbox.frame.origin.x = self.startXphoneTextBox
self.phoneTextbox.frame.origin.x = self.startXphoneTextBox
self.phoneLabel.frame.origin.x = self.startXphonelabel
self.phoneUnderlineLabel.frame.origin.x = self.startXphoneUnderline
createAnAccountLabel.setAttributedTitle(self.cancelMutableString, forState: UIControlState.Normal)
loginBtn.setTitle("REGISTER", forState: UIControlState.Normal)
self.usernameTextbox.attributedPlaceholder = NSAttributedString(string:"W&M USERNAME (treveley)", attributes: [NSForegroundColorAttributeName: UIColor.grayColor()])
print("bringing back to center")
loginBtn.backgroundColor = UIColor.whiteColor()
loginBtn.setTitleColor(settings.wmGreen , forState: UIControlState.Normal)
}
}
func cookiesPresent()->Bool{
let data: NSData? = defaults.objectForKey("sessionCookies") as? NSData
if (data == nil){
print("No cookies, let user log in")
return false
}
else {
return true
}
}
func isAppAlreadyLaunchedOnce()->Bool{
if let _ = self.defaults.stringForKey("isAppAlreadyLaunchedOnce"){
return true
}
else {
defaults.setBool(true, forKey: "isAppAlreadyLaunchedOnce")
print("ViewController: First time launching app, displaying registration screen.")
return false
}
}
/*
displayAlert
------------
Handles user alerts. For example, when Username or Password is required but not entered.
*/
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if self.shouldStopRotating == false {
self.steerClearLogo.rotate360Degrees(completionDelegate: self)
} else {
self.reset()
}
}
func reset() {
self.isRotating = false
self.shouldStopRotating = false
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if let nextField = textField.nextField {
nextField.becomeFirstResponder()
}
if (textField.returnKeyType==UIReturnKeyType.Go)
{
textField.resignFirstResponder() // Dismiss the keyboard
loginBtn.sendActionsForControlEvents(.TouchUpInside)
}
return true
}
func registerForKeyboardNotifications() {
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self,
selector: "keyboardWillBeShown:",
name: UIKeyboardWillShowNotification,
object: nil)
notificationCenter.addObserver(self,
selector: "keyboardWillBeHidden:",
name: UIKeyboardWillHideNotification,
object: nil)
}
func jiggleLogin() {
UIView.animateWithDuration(
0.1,
animations: {
self.loginBtn.frame.origin.x = self.startX - 10
},
completion: { finish in
UIView.animateWithDuration(
0.1,
animations: {
self.loginBtn.frame.origin.x = self.startX + 10
},
completion: { finish in
UIView.animateWithDuration(
0.1,
animations: {
self.loginBtn.frame.origin.x = self.startX
}
)
}
)
}
)
}
//Calls this function when the tap is recognized.
func DismissKeyboard(){
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func keyboardWillShow(notification: NSNotification) {
if (!self.keyboardUp) {
if let _ = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
UIView.animateWithDuration(0.5, animations: {
self.steerClearLogo.alpha = 0.0
})
self.usernameTextbox.frame.origin.y -= 100
self.usernameIcon.frame.origin.y -= 100
self.usernameUnderlineLabel.frame.origin.y -= 100
self.passwordTextbox.frame.origin.y -= 100
self.passwordIcon.frame.origin.y -= 100
self.passwordUnderlineLabel.frame.origin.y -= 100
self.phoneTextbox.frame.origin.y -= 100
self.phoneIcon.frame.origin.y -= 100
self.phoneUnderlineLabel.frame.origin.y -= 100
}
self.keyboardUp = true
}
}
func keyboardWillHide(notification: NSNotification) {
if keyboardUp {
if let _ = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.usernameTextbox.frame.origin.y += 100
self.usernameIcon.frame.origin.y += 100
self.usernameUnderlineLabel.frame.origin.y += 100
self.passwordTextbox.frame.origin.y += 100
self.passwordIcon.frame.origin.y += 100
self.passwordUnderlineLabel.frame.origin.y += 100
self.phoneTextbox.frame.origin.y += 100
self.phoneIcon.frame.origin.y += 100
self.phoneUnderlineLabel.frame.origin.y += 100
UIView.animateWithDuration(0.5, animations: {
self.steerClearLogo.alpha = 1.0
})
self.keyboardUp = false
}
}
}
func hidePhoneLabels() {
phoneTextbox.hidden = true
phoneLabel.hidden = true
phoneUnderlineLabel.hidden = true
}
func unHidePhoneLabels() {
phoneTextbox.hidden = false
phoneLabel.hidden = false
phoneUnderlineLabel.hidden = false
}
func getPhoneLabelsLocation() {
self.startXphoneTextBox = self.phoneTextbox.frame.origin.x
self.startXphonelabel = self.phoneLabel.frame.origin.x
self.startXphoneUnderline = self.phoneUnderlineLabel.frame.origin.x
}
func movePhoneLabelsOffScreen(animate: Bool) {
if animate {
UIView.animateWithDuration(
0.5,
animations: {
self.phoneTextbox.frame.origin.x = self.endXphoneTextBox
self.phoneLabel.frame.origin.x = self.endXphonelabel
self.phoneUnderlineLabel.frame.origin.x = self.endXphoneUnderline
},
completion: nil
)
}
else {
self.phoneTextbox.frame.origin.x = startXphoneTextBox - self.offset
self.phoneLabel.frame.origin.x = startXphonelabel - self.offset
self.phoneUnderlineLabel.frame.origin.x = startXphoneUnderline - self.offset
self.endXphoneTextBox = self.phoneTextbox.frame.origin.x
self.endXphonelabel = self.phoneLabel.frame.origin.x
self.endXphoneUnderline = self.phoneUnderlineLabel.frame.origin.x
}
}
func movePhoneLabelsOnScreen() {
UIView.animateWithDuration(
0.5,
animations: {
self.phoneTextbox.frame.origin.x = self.startXphoneTextBox
self.phoneLabel.frame.origin.x = self.startXphonelabel
self.phoneUnderlineLabel.frame.origin.x = self.startXphoneUnderline
},
completion: nil
)
}
} | mit | fc3b1a26d625a9b9fc1f5c268f4f02b5 | 40.718232 | 180 | 0.543484 | 6.346876 | false | false | false | false |
kmcgill88/McPicker-iOS | Example/McPicker/ViewController.swift | 1 | 7511 | /*
Copyright (c) 2017-2020 Kevin McGill <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit
import McPicker
class ViewController: UIViewController {
@IBOutlet weak var mcTextField: McTextField!
@IBOutlet weak var label: UILabel!
let data: [[String]] = [
["Kevin", "Lauren", "Kibby", "Stella"]
]
override func viewDidLoad() {
let mcInputView = McPicker(data: data)
mcInputView.backgroundColor = .gray
mcInputView.backgroundColorAlpha = 0.25
mcTextField.inputViewMcPicker = mcInputView
mcTextField.doneHandler = { [weak mcTextField] (selections) in
mcTextField?.text = selections[0]!
}
mcTextField.selectionChangedHandler = { [weak mcTextField] (selections, componentThatChanged) in
mcTextField?.text = selections[componentThatChanged]!
}
mcTextField.cancelHandler = { [weak mcTextField] in
mcTextField?.text = "Cancelled."
}
mcTextField.textFieldWillBeginEditingHandler = { [weak mcTextField] (selections) in
if mcTextField?.text == "" {
// Selections always default to the first value per component
mcTextField?.text = selections[0]
}
}
}
@IBAction func showPressed(_ sender: Any) {
/*
McPicker.show(data: data) { [weak self] (selections:[Int: String]) in
if let name = selections[0] {
self?.label.text = name
}
}
*/
/*
McPicker.show(data: data, doneHandler: { [weak self] (selections) in
if let name = selections[0] {
self?.label.text = name
}
}, selectionChangedHandler: { (selections: [Int:String], componentThatChanged: Int) in
let newSelection = selections[componentThatChanged] ?? "Failed to get new selection!"
print("Component \(componentThatChanged) changed value to \(newSelection)")
})
*/
McPicker.show(data: data, doneHandler: { [weak self] (selections: [Int:String]) in
if let name = selections[0] {
self?.label.text = name
}
}, cancelHandler: {
print("Canceled Default Picker")
}, selectionChangedHandler: { (selections: [Int:String], componentThatChanged: Int) in
let newSelection = selections[componentThatChanged] ?? "Failed to get new selection!"
print("Component \(componentThatChanged) changed value to \(newSelection)")
})
}
@IBAction func styledPicker(_ sender: Any) {
let data: [[String]] = [
["Sir", "Mr", "Mrs", "Miss"],
["Kevin", "Lauren", "Kibby", "Stella"]
]
let mcPicker = McPicker(data: data)
let customLabel = UILabel()
customLabel.textAlignment = .center
customLabel.textColor = .white
customLabel.font = UIFont(name:"American Typewriter", size: 30)!
mcPicker.label = customLabel // Set your custom label
let fixedSpace = McPickerBarButtonItem.fixedSpace(width: 20.0)
let flexibleSpace = McPickerBarButtonItem.flexibleSpace()
let fireButton = McPickerBarButtonItem.done(mcPicker: mcPicker, title: "Fire!!!") // Set custom Text
let cancelButton = McPickerBarButtonItem.cancel(mcPicker: mcPicker, barButtonSystemItem: .cancel) // or system items
mcPicker.setToolbarItems(items: [fixedSpace, cancelButton, flexibleSpace, fireButton, fixedSpace])
mcPicker.toolbarItemsFont = UIFont(name:"American Typewriter", size: 17)!
mcPicker.toolbarButtonsColor = .white
mcPicker.toolbarBarTintColor = .darkGray
mcPicker.pickerBackgroundColor = .gray
mcPicker.backgroundColor = .gray
mcPicker.backgroundColorAlpha = 0.50
mcPicker.pickerSelectRowsForComponents = [
0: [3: true],
1: [2: true] // [Component: [Row: isAnimated]
]
if let barButton = sender as? UIBarButtonItem {
// Show as Popover
//
mcPicker.showAsPopover(fromViewController: self, barButtonItem: barButton) { [weak self] (selections: [Int : String]) -> Void in
if let prefix = selections[0], let name = selections[1] {
self?.label.text = "\(prefix) \(name)"
}
}
} else {
// Show Normal
//
/*
mcPicker.show { [weak self] selections in
if let prefix = selections[0], let name = selections[1] {
self?.label.text = "\(prefix) \(name)"
}
}
*/
mcPicker.show(doneHandler: { [weak self] (selections: [Int : String]) -> Void in
if let prefix = selections[0], let name = selections[1] {
self?.label.text = "\(prefix) \(name)"
}
}, cancelHandler: {
print("Canceled Styled Picker")
}, selectionChangedHandler: { (selections: [Int:String], componentThatChanged: Int) -> Void in
let newSelection = selections[componentThatChanged] ?? "Failed to get new selection!"
print("Component \(componentThatChanged) changed value to \(newSelection)")
})
}
}
@IBAction func popOverPicker(_ sender: UIButton) {
McPicker.showAsPopover(data:data, fromViewController: self, sourceView: sender, doneHandler: { [weak self] (selections: [Int : String]) -> Void in
if let name = selections[0] {
self?.label.text = name
}
}, cancelHandler: { () -> Void in
print("Canceled Popover")
}, selectionChangedHandler: { (selections: [Int:String], componentThatChanged: Int) -> Void in
let newSelection = selections[componentThatChanged] ?? "Failed to get new selection!"
print("Component \(componentThatChanged) changed value to \(newSelection)")
})
}
@IBAction func pressedBarButtonItem(_ sender: UIBarButtonItem) {
McPicker.showAsPopover(data: data, fromViewController: self, barButtonItem: sender) { [weak self] (selections: [Int : String]) -> Void in
print("Done with Popover")
if let name = selections[0] {
self?.label.text = name
}
}
}
}
| mit | fc17b04cb5128be7df521053b6540209 | 43.182353 | 154 | 0.610305 | 4.941447 | false | false | false | false |
ewhitley/CDAKit | CDAKit/health-data-standards/lib/import/c32/c32_immunization_importer.swift | 1 | 1521 | //
// immunization_importer.swift
// CDAKit
//
// Created by Eric Whitley on 1/21/16.
// Copyright © 2016 Eric Whitley. All rights reserved.
//
import Foundation
import Fuzi
class CDAKImport_C32_ImmunizationImporter: CDAKImport_CDA_SectionImporter {
override init(entry_finder: CDAKImport_CDA_EntryFinder = CDAKImport_CDA_EntryFinder(entry_xpath: "//cda:section[cda:templateId/@root='2.16.840.1.113883.3.88.11.83.117']/cda:entry/cda:substanceAdministration")) {
super.init(entry_finder: entry_finder)
code_xpath = "./cda:consumable/cda:manufacturedProduct/cda:manufacturedMaterial/cda:code"
description_xpath = "./cda:consumable/cda:manufacturedProduct/cda:manufacturedMaterial/cda:code/cda:originalText/cda:reference[@value]"
entry_class = CDAKImmunization.self
}
override func create_entry(entry_element: XMLElement, nrh: CDAKImport_CDA_NarrativeReferenceHandler = CDAKImport_CDA_NarrativeReferenceHandler()) -> CDAKImmunization? {
if let immunization = super.create_entry(entry_element, nrh: nrh) as? CDAKImmunization {
extract_negation(entry_element, entry: immunization)
extract_performer(entry_element, immunization: immunization)
return immunization
}
return nil
}
private func extract_performer(parent_element: XMLElement, immunization: CDAKImmunization) {
if let performer_element = parent_element.xpath("./cda:performer").first {
immunization.performer = import_actor(performer_element)
}
}
}
| mit | 04c902d3bb61775d5e40cd5057fcd697 | 34.348837 | 213 | 0.735526 | 4.03183 | false | false | false | false |
ZhaoBingDong/EasySwifty | EasySwifty/Classes/Easy+Data.swift | 1 | 2089 | //
// Easy+Data.swift
// EaseSwifty
//
// Created by 董招兵 on 2017/8/6.
// Copyright © 2017年 大兵布莱恩特. All rights reserved.
//
import Foundation
public protocol ValidJSONObject {
associatedtype JSONObjectType
init(json value :Self.JSONObjectType)
}
extension Dictionary : ValidJSONObject {
public typealias JSONObjectType = Dictionary
public init(json value: JSONObjectType) {
self = value
}
}
extension Array : ValidJSONObject {
public typealias JSONObjectType = Array
public init(json value: JSONObjectType) {
self = value
}
}
// MARK: - Data
public extension Data {
/// json 字符串转成 Array
@discardableResult
func arrayValue() -> [Any] {
if let jsonArray = jsonValue() {
return (jsonArray as! Array)
} else {
return Array()
}
}
/// json 字符串转成 Dictionary
@discardableResult
func dictionaryValue() -> Dictionary<String, Any> {
if let jsonDictionay = jsonValue() {
return (jsonDictionay as! Dictionary)
} else {
return Dictionary()
}
}
/// 将 data 转成 String 类型
@discardableResult
func stringValue() -> String? {
return String(data: self, encoding: .utf8)
}
/// 对 data base64编码 多用于上传二进制文件
@discardableResult
func dataToBase64Sting() -> String {
return base64EncodedString(options: [])
}
/// 转成 json
@discardableResult
func jsonValue() -> Any? {
let json = try? JSONSerialization.jsonObject(with: self, options: .allowFragments)
return json
}
/// 支持 Array Dictionary 转 Data
@discardableResult
static func dataWithObject<T : ValidJSONObject>(_ object : T) -> Data? {
if !JSONSerialization.isValidJSONObject(object) { return nil }
let data = try? JSONSerialization.data(withJSONObject: object, options: JSONSerialization.WritingOptions.prettyPrinted)
return data
}
}
| apache-2.0 | 173f7112fefb43fd48af5604ec95efd4 | 23.414634 | 127 | 0.620879 | 4.570776 | false | false | false | false |
PurpleSweetPotatoes/SwiftKit | SwiftKit/ui/BQNumLabel.swift | 1 | 1287 | //
// BQNumLabel.swift
// swift-Test
//
// Created by MrBai on 2017/6/29.
// Copyright © 2017年 MrBai. All rights reserved.
//
import UIKit
class BQNumLabel: UILabel {
override var text: String? {
didSet {
let center = self.center
self.adjustWidthForFont()
let width: Int = Int(self.sizeW + 8)
self.sizeW = CGFloat(width % 2 == 0 ? width : width + 1)
self.sizeH = self.sizeW
self.layer.cornerRadius = self.sizeW * 0.5
self.center = center
}
}
//MARK: - ***** initialize Method *****
override init(frame: CGRect) {
super.init(frame: frame)
self.initUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - ***** private Method *****
private func initUI() {
self.textAlignment = .center
self.backgroundColor = UIColor.red
self.textColor = UIColor.white
self.clipsToBounds = true
self.font = UIFont.systemFont(ofSize: 12)
}
//MARK: - ***** LoadData Method *****
//MARK: - ***** respond event Method *****
//MARK: - ***** Protocol *****
//MARK: - ***** create Method *****
}
| apache-2.0 | 3f8eae4c2102ac7bf3d415464ad6bf7b | 24.176471 | 68 | 0.53271 | 4.168831 | false | false | false | false |
jfosterdavis/FlashcardHero | FlashcardHero/CustomGemManagerCell.swift | 1 | 2061 | //
// CustomGemManagerCell.swift
// FlashcardHero
//
// Created by Jacob Foster Davis on 11/2/16.
// Copyright © 2016 Zero Mu, LLC. All rights reserved.
//
import Foundation
import UIKit
protocol SettingCellDelegate: class {
func didChangeSwitchState(sender: CustomGemManagerCell, isOn: Bool)
}
class CustomGemManagerCell: UITableViewCell {
//label
@IBOutlet weak var title: UILabel!
@IBOutlet weak var creator: UILabel!
@IBOutlet weak var termCount: UILabel!
@IBOutlet weak var customDescription: UILabel!
@IBOutlet weak var customImageView: UIImageView!
@IBOutlet weak var activeSwitch: UISwitch!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
weak var cellDelegate: SettingCellDelegate?
//QuizletSetSearchResult
var quizletSet : QuizletSet? {
didSet {
//try to set the label
if let title = quizletSet?.title {
self.title.text = title
}
//try to set the detailTextLabel
if let description = quizletSet?.setDescription {
self.customDescription.text = description
}
//try to set the detailTextLabel
if let termCount = quizletSet?.termCount {
self.termCount.text = String(termCount)
}
//try to set the detailTextLabel
if let creator = quizletSet?.createdBy {
self.creator.text = creator
}
if let isSwitchOn = quizletSet?.isActive {
self.activeSwitch.isOn = isSwitchOn
}
}
}
@IBAction func handledSwitchChange(sender: UISwitch) {
self.cellDelegate?.didChangeSwitchState(sender: self, isOn: activeSwitch.isOn)
}
func startActivityIndicator() {
self.activityIndicator!.startAnimating()
}
func stopActivityIndicator() {
self.activityIndicator!.stopAnimating()
}
}
| apache-2.0 | 979fe07a0eba553e9178a5724414d614 | 27.219178 | 86 | 0.602913 | 5.282051 | false | false | false | false |
artyom-razinov/EarlGrey | gem/lib/earlgrey/files/Swift-3.0/EarlGrey.swift | 1 | 6539 | //
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import EarlGrey
import Foundation
public func GREYAssert(_ expression: @autoclosure () -> Bool, reason: String) {
GREYAssert(expression, reason, details: "Expected expression to be true")
}
public func GREYAssertTrue(_ expression: @autoclosure () -> Bool, reason: String) {
GREYAssert(expression(), reason, details: "Expected the boolean expression to be true")
}
public func GREYAssertFalse(_ expression: @autoclosure () -> Bool, reason: String) {
GREYAssert(!expression(), reason, details: "Expected the boolean expression to be false")
}
public func GREYAssertNotNil(_ expression: @autoclosure ()-> Any?, reason: String) {
GREYAssert(expression() != nil, reason, details: "Expected expression to be not nil")
}
public func GREYAssertNil(_ expression: @autoclosure () -> Any?, reason: String) {
GREYAssert(expression() == nil, reason, details: "Expected expression to be nil")
}
public func GREYAssertEqual(_ left: @autoclosure () -> AnyObject?,
_ right: @autoclosure () -> AnyObject?, reason: String) {
GREYAssert(left() === right(), reason, details: "Expected left term to be equal to right term")
}
public func GREYAssertNotEqual(_ left: @autoclosure () -> AnyObject?,
_ right: @autoclosure () -> AnyObject?, reason: String) {
GREYAssert(left() !== right(), reason, details: "Expected left term to not equal the right term")
}
public func GREYAssertEqualObjects<T: Equatable>( _ left: @autoclosure () -> T?,
_ right: @autoclosure () -> T?, reason: String) {
GREYAssert(left() == right(), reason, details: "Expected object of the left term to be equal" +
" to the object of the right term")
}
public func GREYAssertNotEqualObjects<T: Equatable>( _ left: @autoclosure () -> T?,
_ right: @autoclosure () -> T?, reason: String) {
GREYAssert(left() != right(), reason, details: "Expected object of the left term to not" +
" equal the object of the right term")
}
public func GREYFail(_ reason: String) {
EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException,
reason: reason),
details: "")
}
public func GREYFailWithDetails(_ reason: String, details: String) {
EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException,
reason: reason),
details: details)
}
private func GREYAssert(_ expression: @autoclosure () -> Bool,
_ reason: String, details: String) {
GREYSetCurrentAsFailable()
GREYWaitUntilIdle()
if !expression() {
EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException,
reason: reason),
details: details)
}
}
private func GREYSetCurrentAsFailable() {
let greyFailureHandlerSelector =
#selector(GREYFailureHandler.setInvocationFile(_:andInvocationLine:))
let greyFailureHandler =
Thread.current.threadDictionary.value(forKey: kGREYFailureHandlerKey) as! GREYFailureHandler
if greyFailureHandler.responds(to: greyFailureHandlerSelector) {
greyFailureHandler.setInvocationFile!(#file, andInvocationLine:#line)
}
}
private func GREYWaitUntilIdle() {
GREYUIThreadExecutor.sharedInstance().drainUntilIdle()
}
open class EarlGrey: NSObject {
open class func select(elementWithMatcher matcher: GREYMatcher,
file: StaticString = #file,
line: UInt = #line) -> GREYElementInteraction {
return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
.selectElement(with: matcher)
}
open class func setFailureHandler(handler: GREYFailureHandler,
file: StaticString = #file,
line: UInt = #line) {
return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
.setFailureHandler(handler)
}
open class func handle(exception: GREYFrameworkException,
details: String,
file: StaticString = #file,
line: UInt = #line) {
return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
.handle(exception, details: details)
}
@discardableResult open class func rotateDeviceTo(orientation: UIDeviceOrientation,
errorOrNil: UnsafeMutablePointer<NSError?>!,
file: StaticString = #file,
line: UInt = #line)
-> Bool {
return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
.rotateDevice(to: orientation,
errorOrNil: errorOrNil)
}
}
extension GREYInteraction {
@discardableResult public func assert(_ matcher: @autoclosure () -> GREYMatcher) -> Self {
return self.assert(with:matcher())
}
@discardableResult public func assert(_ matcher: @autoclosure () -> GREYMatcher,
error: UnsafeMutablePointer<NSError?>!) -> Self {
return self.assert(with: matcher(), error: error)
}
@discardableResult public func using(searchAction: GREYAction,
onElementWithMatcher matcher: GREYMatcher) -> Self {
return self.usingSearch(searchAction, onElementWith: matcher)
}
}
extension GREYCondition {
open func waitWithTimeout(seconds: CFTimeInterval) -> Bool {
return self.wait(withTimeout: seconds)
}
open func waitWithTimeout(seconds: CFTimeInterval, pollInterval: CFTimeInterval)
-> Bool {
return self.wait(withTimeout: seconds, pollInterval: pollInterval)
}
}
| apache-2.0 | 2d9d81684fc9ee2055743d18e76272f6 | 40.386076 | 99 | 0.636948 | 5.057231 | false | false | false | false |
ajijoyo/kelinciTiga | kelinciTiga/stringExtends.swift | 1 | 757 | //
// stringExtends.swift
// kelinciTiga
//
// Created by Dealjava on 11/24/15.
// Copyright © 2015 juicegraphic. All rights reserved.
//
import UIKit
extension String {
var md5: String! {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
let hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.destroy()
return String(format: hash as String)
}
}
class stringExtends {
}
| mit | eaaee6b02b0cf70ae7c31f8d4026a5c9 | 24.2 | 88 | 0.645503 | 3.958115 | false | false | false | false |
Sadmansamee/quran-ios | Quran/CircleView.swift | 1 | 1808 | //
// CircleView.swift
// Quran
//
// Created by Mohamed Afifi on 4/22/16.
// Copyright © 2016 Quran.com. All rights reserved.
//
import UIKit
class CircleView: UIView {
@IBInspectable var progress: CGFloat = 0.8 {
didSet {
updateLayers()
}
}
@IBInspectable var emptyColor: UIColor = UIColor.red {
didSet {
updateLayers()
}
}
@IBInspectable var fillColor: UIColor = UIColor.green {
didSet {
updateLayers()
}
}
fileprivate let emptyCircle = CAShapeLayer()
fileprivate let fillCircle = CAShapeLayer()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
/**
Sets up the view.
*/
func setUp() {
layer.addSublayer(emptyCircle)
layer.addSublayer(fillCircle)
fillCircle.fillColor = nil
fillCircle.transform = CATransform3DMakeRotation(CGFloat(-M_PI_2), 0, 0, 1)
}
override func layoutSubviews() {
super.layoutSubviews()
updateLayers()
}
fileprivate func updateLayers() {
emptyCircle.frame = bounds
fillCircle.frame = bounds
// emtpy circle
// var circleBounds = bounds
emptyCircle.path = UIBezierPath(ovalIn: bounds).cgPath
emptyCircle.fillColor = emptyColor.cgColor
// fill circle
fillCircle.path = UIBezierPath(ovalIn: bounds.insetBy(dx: bounds.width / 4, dy: bounds.height / 4)).cgPath
fillCircle.strokeColor = fillColor.cgColor
fillCircle.lineWidth = bounds.width / 2
CALayer.withoutAnimation {
fillCircle.strokeEnd = progress
}
}
}
| mit | 5379c155e8f052dd44ec2b6472c971a2 | 22.467532 | 114 | 0.594909 | 4.681347 | false | false | false | false |
gkaimakas/Ion | Pod/Classes/SelectInputField.swift | 1 | 2038 | //
// SelectInputField.swift
// Pods
//
// Created by Γιώργος Καϊμακάς on 26/02/16.
//
//
import Foundation
import UIKit
open class SelectInputField: UITextField {
fileprivate var input: SelectInput? = nil
open func setInput(_ input: SelectInput) {
self.input = input
self.delegate = self
let picker = UIPickerView()
picker.dataSource = self
picker.delegate = self
inputView = picker
if let selectedIndex = input.selectedOptionIndex,
let selectedOption = input.selectedOption {
if selectedIndex < input.numberOfOptions {
picker.selectRow(selectedIndex, inComponent: 0, animated: true)
self.text = selectedOption.displayValue
}
}
}
}
//MARK: - UITextFieldDelegate
extension SelectInputField: UITextFieldDelegate {
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return true
}
}
//MARK: - UIPickerViewDataSource
extension SelectInputField: UIPickerViewDataSource {
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if let input = self.input {
return input.numberOfOptions
}
return 0
}
}
//MARK: - UIPickerViewDelegate
extension SelectInputField: UIPickerViewDelegate {
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if let input = self.input {
input.selectOptionAtIndex(row)
text = input.optionForIndex(row).displayValue
}
}
public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if let input = self.input {
return input.optionForIndex(row).displayValue
}
return nil
}
}
| mit | a2e62a925eacc0a6f08b1c27cd4e111f | 24.2875 | 136 | 0.658922 | 4.839713 | false | false | false | false |
jingyu982887078/daily-of-programmer | WeiBo/WeiBo/Classes/View/Main/WBBaseViewController.swift | 1 | 5275 | //
// WBBaseViewController.swift
// WeiBo
//
// Created by wangjingyu on 2017/5/4.
// Copyright © 2017年 wangjingyu. All rights reserved.
//
import UIKit
/// 基类控制器
class WBBaseViewController: UIViewController {
/// 访客视图字典信息
var visitorInfo: [String: String]?
/// 用户登录标记
var userLogon = true
//可选的,没有登录,就不创建
var tableView:UITableView?
//刷新控件
var refreshControl:UIRefreshControl?
//上拉刷新的标志,用来判断是上拉还是下啦,上啦的时候要追加数据,下拉的时候刷新数据
var isPullup = false
/// 自定义导航条
lazy var navigationBar:UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64))
/// 自定义navitem
lazy var navItem: UINavigationItem = UINavigationItem()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
/// 自己定义导航栏后,标题不显示了,重写标题的set方法
override var title: String? {
didSet {
navItem.title = title
}
}
}
// MARK: - 访客视图监听方法
extension WBBaseViewController {
@objc fileprivate func login() {
print("用户登录")
}
@objc fileprivate func register() {
print("用户注册")
}
}
// MARK: - 设置界面
extension WBBaseViewController {
func setupUI() {
view.backgroundColor = UIColor.white
automaticallyAdjustsScrollViewInsets = false
setupnavigationBar()
userLogon ? setupTableView() : setupVisitorView()
loadData()
}
/// 加载数据的方法,具体的实现由子类自行负责
func loadData() {
//如果补充些loaddata方法,默认,实现关闭刷新的功能。
refreshControl?.endRefreshing()
}
func setupTableView() {
tableView = UITableView(frame: view.bounds, style: .plain)
view.insertSubview(tableView!, belowSubview: navigationBar)
tableView?.delegate = self
tableView?.dataSource = self
//设置内容缩进
tableView?.contentInset = UIEdgeInsets(
top: navigationBar.bounds.height,
left: 0,
bottom:tabBarController?.tabBar.bounds.height ?? 49,
right: 0)
//添加刷新控件
refreshControl = UIRefreshControl()
tableView?.addSubview(refreshControl!)
//添加监听方法
refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
}
/// MARK: - 设置访客视图
func setupVisitorView() {
let visitorView = WBVisitorView(frame: view.bounds)
view.insertSubview(visitorView, belowSubview: navigationBar)
visitorView.visitorInfo(dict: visitorInfo)
// 添加监听方法
visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(login))
navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(register))
}
/// 设置navigationbar的属性
func setupnavigationBar() {
//添加navigationBar
view.addSubview(navigationBar)
//讲navItem 设置给nav
navigationBar.items = [navItem]
//设置导航栏的北京颜色
navigationBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
//设置标题字体颜色
navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray]
}
}
// MARK: - UITableViewDelegate,UITableViewDataSource
extension WBBaseViewController:UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
//子类的实现不需要super,这里只是保证语法没有错误。仅此而已,并为实现任何东西。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell()
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//当先到最后一行的时候,并且没有上拉刷新的时候,刷新表格
/// row
let row = indexPath.row
/// setction
let section = tableView.numberOfSections - 1
if row < 0 || section < 0 {
return
}
//3.行数,取出最大的一组的row的数量,可以得到最后一个row的值
let count = tableView.numberOfRows(inSection: section);
if row == count - 1 && !isPullup {
print("上拉刷新")
isPullup = true
loadData()
}
}
}
| mit | 95ef73eaeac42f0f26a5e46a2e3025d5 | 25.906977 | 133 | 0.607174 | 4.79089 | false | false | false | false |
nessBautista/iOSBackup | iOSNotebook/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift | 10 | 17950 | //
// DelegateProxyType.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !os(Linux)
import func Foundation.objc_getAssociatedObject
import func Foundation.objc_setAssociatedObject
import RxSwift
/**
`DelegateProxyType` protocol enables using both normal delegates and Rx observable sequences with
views that can have only one delegate/datasource registered.
`Proxies` store information about observers, subscriptions and delegates
for specific views.
Type implementing `DelegateProxyType` should never be initialized directly.
To fetch initialized instance of type implementing `DelegateProxyType`, `proxy` method
should be used.
This is more or less how it works.
+-------------------------------------------+
| |
| UIView subclass (UIScrollView) |
| |
+-----------+-------------------------------+
|
| Delegate
|
|
+-----------v-------------------------------+
| |
| Delegate proxy : DelegateProxyType +-----+----> Observable<T1>
| , UIScrollViewDelegate | |
+-----------+-------------------------------+ +----> Observable<T2>
| |
| +----> Observable<T3>
| |
| forwards events |
| to custom delegate |
| v
+-----------v-------------------------------+
| |
| Custom delegate (UIScrollViewDelegate) |
| |
+-------------------------------------------+
Since RxCocoa needs to automagically create those Proxys and because views that have delegates can be hierarchical
UITableView : UIScrollView : UIView
.. and corresponding delegates are also hierarchical
UITableViewDelegate : UIScrollViewDelegate : NSObject
... this mechanism can be extended by using the following snippet in `registerKnownImplementations` or in some other
part of your app that executes before using `rx.*` (e.g. appDidFinishLaunching).
RxScrollViewDelegateProxy.register { RxTableViewDelegateProxy(parentObject: $0) }
*/
public protocol DelegateProxyType: class {
associatedtype ParentObject: AnyObject
associatedtype Delegate
/// It is require that enumerate call `register` of the extended DelegateProxy subclasses here.
static func registerKnownImplementations()
/// Unique identifier for delegate
static var identifier: UnsafeRawPointer { get }
/// Returns designated delegate property for object.
///
/// Objects can have multiple delegate properties.
///
/// Each delegate property needs to have it's own type implementing `DelegateProxyType`.
///
/// It's abstract method.
///
/// - parameter object: Object that has delegate property.
/// - returns: Value of delegate property.
static func currentDelegate(for object: ParentObject) -> Delegate?
/// Sets designated delegate property for object.
///
/// Objects can have multiple delegate properties.
///
/// Each delegate property needs to have it's own type implementing `DelegateProxyType`.
///
/// It's abstract method.
///
/// - parameter toObject: Object that has delegate property.
/// - parameter delegate: Delegate value.
static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject)
/// Returns reference of normal delegate that receives all forwarded messages
/// through `self`.
///
/// - returns: Value of reference if set or nil.
func forwardToDelegate() -> Delegate?
/// Sets reference of normal delegate that receives all forwarded messages
/// through `self`.
///
/// - parameter forwardToDelegate: Reference of delegate that receives all messages through `self`.
/// - parameter retainDelegate: Should `self` retain `forwardToDelegate`.
func setForwardToDelegate(_ forwardToDelegate: Delegate?, retainDelegate: Bool)
}
// default implementations
extension DelegateProxyType {
/// Unique identifier for delegate
public static var identifier: UnsafeRawPointer {
let delegateIdentifier = ObjectIdentifier(Delegate.self)
let integerIdentifier = Int(bitPattern: delegateIdentifier)
return UnsafeRawPointer(bitPattern: integerIdentifier)!
}
}
// workaround of Delegate: class
extension DelegateProxyType {
static func _currentDelegate(for object: ParentObject) -> AnyObject? {
return currentDelegate(for: object).map { $0 as AnyObject }
}
static func _setCurrentDelegate(_ delegate: AnyObject?, to object: ParentObject) {
return setCurrentDelegate(castOptionalOrFatalError(delegate), to: object)
}
func _forwardToDelegate() -> AnyObject? {
return forwardToDelegate().map { $0 as AnyObject }
}
func _setForwardToDelegate(_ forwardToDelegate: AnyObject?, retainDelegate: Bool) {
return setForwardToDelegate(castOptionalOrFatalError(forwardToDelegate), retainDelegate: retainDelegate)
}
}
extension DelegateProxyType {
/// Store DelegateProxy subclass to factory.
/// When make 'Rx*DelegateProxy' subclass, call 'Rx*DelegateProxySubclass.register(for:_)' 1 time, or use it in DelegateProxyFactory
/// 'Rx*DelegateProxy' can have one subclass implementation per concrete ParentObject type.
/// Should call it from concrete DelegateProxy type, not generic.
public static func register<Parent>(make: @escaping (Parent) -> Self) {
self.factory.extend(make: make)
}
/// Creates new proxy for target object.
/// Should not call this function directory, use 'DelegateProxy.proxy(for:)'
public static func createProxy(for object: AnyObject) -> Self {
return castOrFatalError(factory.createProxy(for: object))
}
/// Returns existing proxy for object or installs new instance of delegate proxy.
///
/// - parameter object: Target object on which to install delegate proxy.
/// - returns: Installed instance of delegate proxy.
///
///
/// extension Reactive where Base: UISearchBar {
///
/// public var delegate: DelegateProxy<UISearchBar, UISearchBarDelegate> {
/// return RxSearchBarDelegateProxy.proxy(for: base)
/// }
///
/// public var text: ControlProperty<String> {
/// let source: Observable<String> = self.delegate.observe(#selector(UISearchBarDelegate.searchBar(_:textDidChange:)))
/// ...
/// }
/// }
public static func proxy(for object: ParentObject) -> Self {
MainScheduler.ensureExecutingOnScheduler()
let maybeProxy = self.assignedProxy(for: object)
let proxy: AnyObject
if let existingProxy = maybeProxy {
proxy = existingProxy
}
else {
proxy = castOrFatalError(self.createProxy(for: object))
self.assignProxy(proxy, toObject: object)
assert(self.assignedProxy(for: object) === proxy)
}
let currentDelegate = self._currentDelegate(for: object)
let delegateProxy: Self = castOrFatalError(proxy)
if currentDelegate !== delegateProxy {
delegateProxy._setForwardToDelegate(currentDelegate, retainDelegate: false)
assert(delegateProxy._forwardToDelegate() === currentDelegate)
self._setCurrentDelegate(proxy, to: object)
assert(self._currentDelegate(for: object) === proxy)
assert(delegateProxy._forwardToDelegate() === currentDelegate)
}
return delegateProxy
}
/// Sets forward delegate for `DelegateProxyType` associated with a specific object and return disposable that can be used to unset the forward to delegate.
/// Using this method will also make sure that potential original object cached selectors are cleared and will report any accidental forward delegate mutations.
///
/// - parameter forwardDelegate: Delegate object to set.
/// - parameter retainDelegate: Retain `forwardDelegate` while it's being set.
/// - parameter onProxyForObject: Object that has `delegate` property.
/// - returns: Disposable object that can be used to clear forward delegate.
public static func installForwardDelegate(_ forwardDelegate: Delegate, retainDelegate: Bool, onProxyForObject object: ParentObject) -> Disposable {
weak var weakForwardDelegate: AnyObject? = forwardDelegate as AnyObject
let proxy = self.proxy(for: object)
assert(proxy._forwardToDelegate() === nil, "This is a feature to warn you that there is already a delegate (or data source) set somewhere previously. The action you are trying to perform will clear that delegate (data source) and that means that some of your features that depend on that delegate (data source) being set will likely stop working.\n" +
"If you are ok with this, try to set delegate (data source) to `nil` in front of this operation.\n" +
" This is the source object value: \(object)\n" +
" This this the original delegate (data source) value: \(proxy.forwardToDelegate()!)\n" +
"Hint: Maybe delegate was already set in xib or storyboard and now it's being overwritten in code.\n")
proxy.setForwardToDelegate(forwardDelegate, retainDelegate: retainDelegate)
return Disposables.create {
MainScheduler.ensureExecutingOnScheduler()
let delegate: AnyObject? = weakForwardDelegate
assert(delegate == nil || proxy._forwardToDelegate() === delegate, "Delegate was changed from time it was first set. Current \(String(describing: proxy.forwardToDelegate())), and it should have been \(proxy)")
proxy.setForwardToDelegate(nil, retainDelegate: retainDelegate)
}
}
}
// fileprivate extensions
extension DelegateProxyType {
fileprivate static var factory: DelegateProxyFactory {
return DelegateProxyFactory.sharedFactory(for: self)
}
fileprivate static func assignedProxy(for object: ParentObject) -> AnyObject? {
let maybeDelegate = objc_getAssociatedObject(object, self.identifier)
return castOptionalOrFatalError(maybeDelegate)
}
fileprivate static func assignProxy(_ proxy: AnyObject, toObject object: ParentObject) {
objc_setAssociatedObject(object, self.identifier, proxy, .OBJC_ASSOCIATION_RETAIN)
}
}
/// Describes an object that has a delegate.
public protocol HasDelegate: AnyObject {
/// Delegate type
associatedtype Delegate
/// Delegate
var delegate: Delegate? { get set }
}
extension DelegateProxyType where ParentObject: HasDelegate, Self.Delegate == ParentObject.Delegate {
public static func currentDelegate(for object: ParentObject) -> Delegate? {
return object.delegate
}
public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) {
object.delegate = delegate
}
}
/// Describes an object that has a data source.
public protocol HasDataSource: AnyObject {
/// Data source type
associatedtype DataSource
/// Data source
var dataSource: DataSource? { get set }
}
extension DelegateProxyType where ParentObject: HasDataSource, Self.Delegate == ParentObject.DataSource {
public static func currentDelegate(for object: ParentObject) -> Delegate? {
return object.dataSource
}
public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) {
object.dataSource = delegate
}
}
#if os(iOS) || os(tvOS)
import UIKit
extension ObservableType {
func subscribeProxyDataSource<DelegateProxy: DelegateProxyType>(ofObject object: DelegateProxy.ParentObject, dataSource: DelegateProxy.Delegate, retainDataSource: Bool, binding: @escaping (DelegateProxy, Event<E>) -> Void)
-> Disposable
where DelegateProxy.ParentObject: UIView
, DelegateProxy.Delegate: AnyObject {
let proxy = DelegateProxy.proxy(for: object)
let unregisterDelegate = DelegateProxy.installForwardDelegate(dataSource, retainDelegate: retainDataSource, onProxyForObject: object)
// this is needed to flush any delayed old state (https://github.com/RxSwiftCommunity/RxDataSources/pull/75)
object.layoutIfNeeded()
let subscription = self.asObservable()
.observeOn(MainScheduler())
.catchError { error in
bindingError(error)
return Observable.empty()
}
// source can never end, otherwise it would release the subscriber, and deallocate the data source
.concat(Observable.never())
.takeUntil(object.rx.deallocated)
.subscribe { [weak object] (event: Event<E>) in
if let object = object {
assert(proxy === DelegateProxy.currentDelegate(for: object), "Proxy changed from the time it was first set.\nOriginal: \(proxy)\nExisting: \(String(describing: DelegateProxy.currentDelegate(for: object)))")
}
binding(proxy, event)
switch event {
case .error(let error):
bindingError(error)
unregisterDelegate.dispose()
case .completed:
unregisterDelegate.dispose()
default:
break
}
}
return Disposables.create { [weak object] in
subscription.dispose()
object?.layoutIfNeeded()
unregisterDelegate.dispose()
}
}
}
#endif
/**
To add delegate proxy subclasses call `DelegateProxySubclass.register()` in `registerKnownImplementations` or in some other
part of your app that executes before using `rx.*` (e.g. appDidFinishLaunching).
class RxScrollViewDelegateProxy: DelegateProxy {
public static func registerKnownImplementations() {
self.register { RxTableViewDelegateProxy(parentObject: $0) }
}
...
*/
private class DelegateProxyFactory {
private static var _sharedFactories: [UnsafeRawPointer: DelegateProxyFactory] = [:]
fileprivate static func sharedFactory<DelegateProxy: DelegateProxyType>(for proxyType: DelegateProxy.Type) -> DelegateProxyFactory {
MainScheduler.ensureExecutingOnScheduler()
let identifier = DelegateProxy.identifier
if let factory = _sharedFactories[identifier] {
return factory
}
let factory = DelegateProxyFactory(for: proxyType)
_sharedFactories[identifier] = factory
DelegateProxy.registerKnownImplementations()
return factory
}
private var _factories: [ObjectIdentifier: ((AnyObject) -> AnyObject)]
private var _delegateProxyType: Any.Type
private var _identifier: UnsafeRawPointer
private init<DelegateProxy: DelegateProxyType>(for proxyType: DelegateProxy.Type) {
_factories = [:]
_delegateProxyType = proxyType
_identifier = proxyType.identifier
}
fileprivate func extend<DelegateProxy: DelegateProxyType, ParentObject>(make: @escaping (ParentObject) -> DelegateProxy) {
MainScheduler.ensureExecutingOnScheduler()
precondition(_identifier == DelegateProxy.identifier, "Delegate proxy has inconsistent identifier")
guard _factories[ObjectIdentifier(ParentObject.self)] == nil else {
rxFatalError("The factory of \(ParentObject.self) is duplicated. DelegateProxy is not allowed of duplicated base object type.")
}
_factories[ObjectIdentifier(ParentObject.self)] = { make(castOrFatalError($0)) }
}
fileprivate func createProxy(for object: AnyObject) -> AnyObject {
MainScheduler.ensureExecutingOnScheduler()
var maybeMirror: Mirror? = Mirror(reflecting: object)
while let mirror = maybeMirror {
if let factory = _factories[ObjectIdentifier(mirror.subjectType)] {
return factory(object)
}
maybeMirror = mirror.superclassMirror
}
rxFatalError("DelegateProxy has no factory of \(object). Implement DelegateProxy subclass for \(object) first.")
}
}
#endif
| cc0-1.0 | a012d43122e53bd6aed601d7ffdc158d | 42.992647 | 359 | 0.605772 | 6.03125 | false | false | false | false |
apple/swift-argument-parser | Sources/ArgumentParser/Parsable Types/ParsableArguments.swift | 1 | 10381 | //===----------------------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Argument Parser open source project
//
// Copyright (c) 2020 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
//
//===----------------------------------------------------------------------===//
/// A type that can be parsed from a program's command-line arguments.
///
/// When you implement a `ParsableArguments` type, all properties must be declared with
/// one of the four property wrappers provided by the `ArgumentParser` library.
public protocol ParsableArguments: Decodable {
/// Creates an instance of this parsable type using the definitions
/// given by each property's wrapper.
init()
/// Validates the properties of the instance after parsing.
///
/// Implement this method to perform validation or other processing after
/// creating a new instance from command-line arguments.
mutating func validate() throws
/// The label to use for "Error: ..." messages from this type. (experimental)
static var _errorLabel: String { get }
}
/// A type that provides the `ParsableCommand` interface to a `ParsableArguments` type.
struct _WrappedParsableCommand<P: ParsableArguments>: ParsableCommand {
static var _commandName: String {
let name = String(describing: P.self).convertedToSnakeCase()
// If the type is named something like "TransformOptions", we only want
// to use "transform" as the command name.
if let optionsRange = name.range(of: "_options"),
optionsRange.upperBound == name.endIndex
{
return String(name[..<optionsRange.lowerBound])
} else {
return name
}
}
@OptionGroup var options: P
}
extension ParsableArguments {
public mutating func validate() throws {}
/// This type as-is if it conforms to `ParsableCommand`, or wrapped in the
/// `ParsableCommand` wrapper if not.
internal static var asCommand: ParsableCommand.Type {
self as? ParsableCommand.Type ?? _WrappedParsableCommand<Self>.self
}
public static var _errorLabel: String {
"Error"
}
}
// MARK: - API
extension ParsableArguments {
/// Parses a new instance of this type from command-line arguments.
///
/// - Parameter arguments: An array of arguments to use for parsing. If
/// `arguments` is `nil`, this uses the program's command-line arguments.
/// - Returns: A new instance of this type.
public static func parse(
_ arguments: [String]? = nil
) throws -> Self {
// Parse the command and unwrap the result if necessary.
switch try self.asCommand.parseAsRoot(arguments) {
case let helpCommand as HelpCommand:
throw ParserError.helpRequested(visibility: helpCommand.visibility)
case let result as _WrappedParsableCommand<Self>:
return result.options
case var result as Self:
do {
try result.validate()
} catch {
throw ParserError.userValidationError(error)
}
return result
default:
// TODO: this should be a "wrong command" message
throw ParserError.invalidState
}
}
/// Returns a brief message for the given error.
///
/// - Parameter error: An error to generate a message for.
/// - Returns: A message that can be displayed to the user.
public static func message(
for error: Error
) -> String {
MessageInfo(error: error, type: self).message
}
/// Returns a full message for the given error, including usage information,
/// if appropriate.
///
/// - Parameter error: An error to generate a message for.
/// - Returns: A message that can be displayed to the user.
public static func fullMessage(
for error: Error
) -> String {
MessageInfo(error: error, type: self).fullText(for: self)
}
/// Returns the text of the help screen for this type.
///
/// - Parameters:
/// - columns: The column width to use when wrapping long line in the
/// help screen. If `columns` is `nil`, uses the current terminal
/// width, or a default value of `80` if the terminal width is not
/// available.
/// - Returns: The full help screen for this type.
@_disfavoredOverload
@available(*, deprecated, message: "Use helpMessage(includeHidden:columns:) instead.")
public static func helpMessage(
columns: Int?
) -> String {
helpMessage(includeHidden: false, columns: columns)
}
/// Returns the text of the help screen for this type.
///
/// - Parameters:
/// - includeHidden: Include hidden help information in the generated
/// message.
/// - columns: The column width to use when wrapping long line in the
/// help screen. If `columns` is `nil`, uses the current terminal
/// width, or a default value of `80` if the terminal width is not
/// available.
/// - Returns: The full help screen for this type.
public static func helpMessage(
includeHidden: Bool = false,
columns: Int? = nil
) -> String {
HelpGenerator(self, visibility: includeHidden ? .hidden : .default)
.rendered(screenWidth: columns)
}
/// Returns the JSON representation of this type.
public static func _dumpHelp() -> String {
DumpHelpGenerator(self).rendered()
}
/// Returns the exit code for the given error.
///
/// The returned code is the same exit code that is used if `error` is passed
/// to `exit(withError:)`.
///
/// - Parameter error: An error to generate an exit code for.
/// - Returns: The exit code for `error`.
public static func exitCode(
for error: Error
) -> ExitCode {
MessageInfo(error: error, type: self).exitCode
}
/// Returns a shell completion script for the specified shell.
///
/// - Parameter shell: The shell to generate a completion script for.
/// - Returns: The completion script for `shell`.
public static func completionScript(for shell: CompletionShell) -> String {
let completionsGenerator = try! CompletionsGenerator(command: self.asCommand, shell: shell)
return completionsGenerator.generateCompletionScript()
}
/// Terminates execution with a message and exit code that is appropriate
/// for the given error.
///
/// If the `error` parameter is `nil`, this method prints nothing and exits
/// with code `EXIT_SUCCESS`. If `error` represents a help request or
/// another `CleanExit` error, this method prints help information and
/// exits with code `EXIT_SUCCESS`. Otherwise, this method prints a relevant
/// error message and exits with code `EX_USAGE` or `EXIT_FAILURE`.
///
/// - Parameter error: The error to use when exiting, if any.
public static func exit(
withError error: Error? = nil
) -> Never {
guard let error = error else {
Platform.exit(ExitCode.success.rawValue)
}
let messageInfo = MessageInfo(error: error, type: self)
let fullText = messageInfo.fullText(for: self)
if !fullText.isEmpty {
if messageInfo.shouldExitCleanly {
print(fullText)
} else {
print(fullText, to: &Platform.standardError)
}
}
Platform.exit(messageInfo.exitCode.rawValue)
}
/// Parses a new instance of this type from command-line arguments or exits
/// with a relevant message.
///
/// - Parameter arguments: An array of arguments to use for parsing. If
/// `arguments` is `nil`, this uses the program's command-line arguments.
public static func parseOrExit(
_ arguments: [String]? = nil
) -> Self {
do {
return try parse(arguments)
} catch {
exit(withError: error)
}
}
}
/// Unboxes the given value if it is a `nil` value.
///
/// If the value passed is the `.none` case of any optional type, this function
/// returns `nil`.
///
/// let intAsAny = (1 as Int?) as Any
/// let nilAsAny = (nil as Int?) as Any
/// nilOrValue(intAsAny) // Optional(1) as Any?
/// nilOrValue(nilAsAny) // nil as Any?
func nilOrValue(_ value: Any) -> Any? {
if case Optional<Any>.none = value {
return nil
} else {
return value
}
}
/// Existential protocol for property wrappers, so that they can provide
/// the argument set that they define.
protocol ArgumentSetProvider {
func argumentSet(for key: InputKey) -> ArgumentSet
var _visibility: ArgumentVisibility { get }
}
extension ArgumentSetProvider {
var _visibility: ArgumentVisibility { .default }
}
extension ArgumentSet {
init(_ type: ParsableArguments.Type, visibility: ArgumentVisibility, parent: InputKey.Parent) {
#if DEBUG
do {
try type._validate(parent: parent)
} catch {
assertionFailure("\(error)")
}
#endif
let a: [ArgumentSet] = Mirror(reflecting: type.init())
.children
.compactMap { child -> ArgumentSet? in
guard let codingKey = child.label else { return nil }
if let parsed = child.value as? ArgumentSetProvider {
guard parsed._visibility.isAtLeastAsVisible(as: visibility)
else { return nil }
let key = InputKey(name: codingKey, parent: parent)
return parsed.argumentSet(for: key)
} else {
let arg = ArgumentDefinition(
unparsedKey: codingKey,
default: nilOrValue(child.value), parent: parent)
// Save a non-wrapped property as is
return ArgumentSet(arg)
}
}
self.init(
a.joined().filter { $0.help.visibility.isAtLeastAsVisible(as: visibility) })
}
}
/// The fatal error message to display when someone accesses a
/// `ParsableArguments` type after initializing it directly.
internal let directlyInitializedError = """
--------------------------------------------------------------------
Can't read a value from a parsable argument definition.
This error indicates that a property declared with an `@Argument`,
`@Option`, `@Flag`, or `@OptionGroup` property wrapper was neither
initialized to a value nor decoded from command-line arguments.
To get a valid value, either call one of the static parsing methods
(`parse`, `parseAsRoot`, or `main`) or define an initializer that
initializes _every_ property of your parsable type.
--------------------------------------------------------------------
"""
| apache-2.0 | 9a2ef9dc0fcb22f8499240de0293330e | 33.48505 | 97 | 0.654239 | 4.453024 | false | false | false | false |
Moliholy/devslopes-smack-animation | Smack/Transitions/DisplayModalTransitionAnimator.swift | 1 | 1764 | //
// DisplayModalTransitionAnimator.swift
// Smack
//
// Created by Jose Molina Colmenero on 28/07/2017.
// Copyright © 2017 Jonny B. All rights reserved.
//
import Foundation
class DisplayModalTransitionAnimator : NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewController(forKey: .from)!
let toViewController = transitionContext.viewController(forKey: .to)!
let firstView = toViewController.view.subviews[0]
let secondView = toViewController.view.subviews[1]
let originalColor = firstView.backgroundColor
let originalFrame = secondView.frame
toViewController.view.frame = fromViewController.view.frame
firstView.backgroundColor = UIColor.clear
transitionContext.containerView.addSubview(toViewController.view)
secondView.frame = CGRect(x: firstView.frame.origin.x,
y: fromViewController.view.frame.size.height,
width: firstView.frame.size.width,
height: firstView.frame.size.height)
UIView.animate(withDuration: 0.5,
delay: 0,
options: .curveEaseOut,
animations: {
firstView.backgroundColor = originalColor
secondView.frame = originalFrame
}) { (finished) in
transitionContext.completeTransition(true)
}
}
}
| bsd-2-clause | 265fd3e803d2885406e943d518f8194c | 38.177778 | 109 | 0.638684 | 5.837748 | false | false | false | false |
february29/Learning | swift/ReactiveCocoaDemo/Pods/RxSwift/Platform/Platform.Darwin.swift | 327 | 2156 | //
// Platform.Darwin.swift
// Platform
//
// Created by Krunoslav Zaher on 12/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
import class Foundation.Thread
import func Foundation.OSAtomicCompareAndSwap32Barrier
import func Foundation.OSAtomicIncrement32Barrier
import func Foundation.OSAtomicDecrement32Barrier
import protocol Foundation.NSCopying
typealias AtomicInt = Int32
fileprivate func castToUInt32Pointer(_ pointer: UnsafeMutablePointer<Int32>) -> UnsafeMutablePointer<UInt32> {
let raw = UnsafeMutableRawPointer(pointer)
return raw.assumingMemoryBound(to: UInt32.self)
}
let AtomicCompareAndSwap = OSAtomicCompareAndSwap32Barrier
let AtomicIncrement = OSAtomicIncrement32Barrier
let AtomicDecrement = OSAtomicDecrement32Barrier
func AtomicOr(_ mask: UInt32, _ theValue : UnsafeMutablePointer<Int32>) -> Int32 {
return OSAtomicOr32OrigBarrier(mask, castToUInt32Pointer(theValue))
}
func AtomicFlagSet(_ mask: UInt32, _ theValue : UnsafeMutablePointer<Int32>) -> Bool {
// just used to create a barrier
OSAtomicXor32OrigBarrier(0, castToUInt32Pointer(theValue))
return (theValue.pointee & Int32(mask)) != 0
}
extension Thread {
static func setThreadLocalStorageValue<T: AnyObject>(_ value: T?, forKey key: NSCopying
) {
let currentThread = Thread.current
let threadDictionary = currentThread.threadDictionary
if let newValue = value {
threadDictionary[key] = newValue
}
else {
threadDictionary[key] = nil
}
}
static func getThreadLocalStorageValueForKey<T>(_ key: NSCopying) -> T? {
let currentThread = Thread.current
let threadDictionary = currentThread.threadDictionary
return threadDictionary[key] as? T
}
}
extension AtomicInt {
func valueSnapshot() -> Int32 {
return self
}
}
#endif
| mit | 1157d8726eced2b831e2efe11141ede9 | 31.651515 | 114 | 0.658469 | 5.070588 | false | false | false | false |
quintonwall/SalesforceViews | SalesforceViews/Themes/ThemeManager.swift | 1 | 2800 | //
// ThemeManager.swift
// SalesforceViews
//
// Created by Quinton Wall on 7/14/17.
// Copyright © 2017 me.quinton. All rights reserved.
//
import UIKit
protocol Theme {
var mainColor : UIColor { get }
var secondaryColor : UIColor { get }
var labelFont : UIFont { get }
var labelFontColor : UIColor { get }
var headerFont : UIFont { get }
var headerFontColor : UIColor { get }
var navigationBarColor : UIColor { get }
var navigationBarFontColor : UIColor { get }
var navigationBarFont : UIFont { get }
var selectedItemColor : UIColor { get }
}
let SelectedThemeKey = "SelectedTheme"
class ThemeManager {
public static let shared = ThemeManager()
private var theme : Theme?
public func set(newtheme: Theme?) {
if let theme = newtheme {
self.theme = theme
let sharedApplication = UIApplication.shared
//standard font attributes for labels
let labelattrs = [
NSForegroundColorAttributeName: theme.labelFontColor,
NSFontAttributeName: theme.labelFont
]
//main colors
sharedApplication.delegate?.window??.tintColor = theme.mainColor
//UIView.appearance().backgroundColor = theme.mainColor
//nav bar
UINavigationBar.appearance().tintColor = theme.navigationBarFontColor
UINavigationBar.appearance().barTintColor = theme.navigationBarColor
let navbarattrs = [
NSForegroundColorAttributeName: theme.navigationBarFontColor,
NSFontAttributeName: theme.navigationBarFont
]
UINavigationBar.appearance().titleTextAttributes = navbarattrs
//labels
UILabel.appearance().defaultFont = theme.labelFont
UILabel.appearance().defaultTextColor = theme.labelFontColor
//Tables
//UITableViewCell.appearance()
}
}
public func currentTheme() -> Theme? {
return theme
}
/*
static func currentTheme() -> Theme {
if let storedTheme = UserDefaults.standard.object(forKey: SelectedThemeKey) as? Theme {
return storedTheme
} else {
return TerminalTheme()
}
}
static func set(theme: Theme) {
UserDefaults.standard.set(theme, forKey: SelectedThemeKey)
let sharedApplication = UIApplication.shared
sharedApplication.delegate?.window??.tintColor = theme.mainColor
UIView.appearance().backgroundColor = theme.mainColor
}
*/
}
| mit | b623a932155cffbff9a07a247069bb25 | 28.15625 | 95 | 0.585924 | 5.819127 | false | false | false | false |
MoooveOn/Advanced-Frameworks | Movies/MovieSelector3DTouch/MovieSelector/MovieTableViewController.swift | 1 | 1459 | //
// MovieTableViewController.swift
// MovieSelector
//
// Created by Pavel Selivanov on 10.07.17.
// Copyright © 2017 Pavel Selivanov. All rights reserved.
//
import UIKit
import MovieSelectorBridge
class MovieTableViewController: UITableViewController {
var nowPlaying = [Movie]()
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
func loadData() {
Movie.nowPlaying { (success, movieList: [Movie]?) in
if success {
self.nowPlaying = movieList!
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int { return 1 }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return nowPlaying.count}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let movie = nowPlaying[indexPath.row]
cell.textLabel?.text = movie.title
cell.detailTextLabel?.text = movie.description
cell.selectionStyle = .none
Movie.getImage(forCell: cell, withMovieObject: movie)
return cell
}
}
| mit | 462927eb46a20fa670864a0f16f005f7 | 26 | 123 | 0.615226 | 5.151943 | false | false | false | false |
mattdaw/SwiftBoard | SwiftBoard/CollectionViewCells/FolderCollectionViewCell.swift | 1 | 4459 | //
// FolderCollectionViewCell.swift
// SwiftBoard
//
// Created by Matt Daw on 2014-09-18.
// Copyright (c) 2014 Matt Daw. All rights reserved.
//
import UIKit
class FolderCollectionViewCell : ItemViewModelCell, FolderViewModelDelegate {
@IBOutlet weak var collectionView: FolderCollectionView!
@IBOutlet weak var expandingView: UIView!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var topConstraint: NSLayoutConstraint!
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
@IBOutlet weak var leftConstraint: NSLayoutConstraint!
@IBOutlet weak var rightConstraint: NSLayoutConstraint!
let flickeringAnimationKey = "flickering"
private var expanded: Bool = false {
didSet {
expanded ? expand() : collapse()
}
}
private var flickering: Bool = false {
didSet {
flickering ? startFlickering() : stopFlickering()
}
}
weak var folderViewModel: FolderViewModel? {
didSet {
if let myViewModel = folderViewModel {
hidden = myViewModel.dragging
editing = myViewModel.editing
zoomed = myViewModel.zoomed
label.text = myViewModel.name
collectionView.folderViewModel = myViewModel
myViewModel.folderViewModelDelegate = self
} else {
hidden = false
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
collectionView.backgroundColor = UIColor.clearColor()
expandingView.layer.cornerRadius = 5
}
override func prepareForReuse() {
super.prepareForReuse()
hidden = false
}
override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes!) {
super.applyLayoutAttributes(layoutAttributes)
if zoomed {
topConstraint.constant = 10
bottomConstraint.constant = 30
leftConstraint.constant = 10
rightConstraint.constant = 10
} else {
let extraWidth = (bounds.width - 60) / 2
let extraHeight = (bounds.height - 80) / 2
topConstraint.constant = extraHeight
bottomConstraint.constant = extraHeight + 20
leftConstraint.constant = extraWidth
rightConstraint.constant = extraWidth
}
// Trigger constraint re-evaluation, so the subview sizes get animated too
// http://stackoverflow.com/questions/23564453/uicollectionview-layout-transitions
layoutIfNeeded()
}
override func iconRect() -> CGRect? {
return collectionView.frame
}
func expand() {
UIView.animateWithDuration(0.4) {
self.expandingView.layer.transform = CATransform3DMakeScale(1.2, 1.2, 1)
self.label.alpha = 0
}
}
func collapse() {
UIView.animateWithDuration(0.4) {
self.expandingView.layer.transform = CATransform3DIdentity
self.label.alpha = 1
}
}
func startFlickering() {
let anim = CABasicAnimation(keyPath: "backgroundColor")
anim.toValue = UIColor.darkGrayColor().CGColor
anim.autoreverses = true
anim.duration = 0.1
anim.repeatCount = HUGE
expandingView.layer.addAnimation(anim, forKey:flickeringAnimationKey);
}
func stopFlickering() {
expandingView.layer.removeAnimationForKey(flickeringAnimationKey)
}
// FolderViewModelDelegate
func folderViewModelDraggingDidChange(newValue: Bool) {
hidden = newValue
}
func folderViewModelEditingDidChange(newValue: Bool) {
editing = newValue
updateJiggling()
}
func folderViewModelZoomedDidChange(newValue: Bool) {
zoomed = newValue
updateJiggling()
}
func folderViewModelStateDidChange(state: FolderViewModelState) {
switch state {
case .Closed:
expanded = false
flickering = false
case .AppHovering:
expanded = true
flickering = false
case .PreparingToOpen:
expanded = true
flickering = true
case .Open:
expanded = false
flickering = false
}
updateJiggling()
}
}
| mit | 7eebf4f586d7caf598ba38e1ffadc034 | 28.529801 | 94 | 0.60462 | 5.54602 | false | false | false | false |
nathawes/swift | test/IRGen/prespecialized-metadata/enum-extradata-no_payload_size-no_trailing_flags.swift | 19 | 640 | // RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main6EitherOMP" = internal constant <{
// Ensure that there is no reference to an anonymous global from within
// s4main4PairVMP. It would be better to use CHECK-NOT-SAME, if such a thing
// existed.
// CHECK-NOT: {{@[0-9]+}}
// CHECK-LABEL: @"symbolic _____ 4main6EitherO"
enum Either<First, Second, Third> {
case first(Int)
case second(String)
}
| apache-2.0 | 42df3d5a16e349239e870f75986e6f26 | 31 | 111 | 0.682813 | 3.21608 | false | false | false | false |
kolyvan/kybookfmt | KyBookFmtKit/fb2kybook/main.swift | 1 | 2106 | //
// main.swift
// https://github.com/kolyvan/kybookfmt
//
// Created by Konstantin Bukreev on 07.02.16.
// Copyright © 2016 Konstantin Bukreev. All rights reserved.
//
import Foundation
import KyBookFmtKitOSX
func listItemsInTar(path: String) {
guard let reader = KyBookFmtReader(path: path) else {
return
}
for item in reader.items {
print("\(item.path) size:\(item.size)")
}
}
func processFb2File(fb2Path: String, outPath: String, args: [String:String]) {
do {
if let package = try FB2Loader.loadPackage(fb2Path) {
if let title = package.desc.titleInfo.title.text {
print("loaded '\(title)'")
}
var opt = FB2KyBook.Options();
if let val = args["gzip"] {
switch val {
case "0", "n", "no": opt.gzipChapter = false
default: break
}
}
if try FB2KyBook.convertPackage(package, outPath:outPath, opt: opt) {
print("done \(outPath)")
}
}
} catch let err {
print("failed: \(err)")
}
}
func run() {
guard Process.arguments.count > 1 else {
print("usage: file [gzip n|y]")
return
}
let file = Process.arguments[1]
var args = [String:String]()
if Process.arguments.count > 2 {
var key : String?
for arg in Process.arguments.dropFirst(2) {
if let s = key {
args[s] = arg
key = nil
} else {
key = arg
}
}
}
print("process file: \(file) args: \(args)")
let pathExt = (file as NSString).pathExtension
switch (pathExt) {
case "tar":
listItemsInTar(file)
case "fb2":
let outPath = file + ".tar"
processFb2File(file, outPath:outPath, args: args)
default:
print("unsupported format: \(pathExt)")
}
}
run()
| bsd-2-clause | e001c1483806703ed80146cde03191db | 21.393617 | 81 | 0.491211 | 4.095331 | false | false | false | false |
ffried/FFUIKit | Sources/FFUIKit/Extensions/UIScrollView+Keyboard.swift | 1 | 9874 | //
// UIScrollView+Keyboard.swift
// FFUIkit
//
// Created by Florian Friedrich on 20.2.15.
// Copyright 2015 Florian Friedrich
//
// 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.
//
#if !os(watchOS)
import enum ObjectiveC.objc_AssociationPolicy
import func ObjectiveC.objc_getAssociatedObject
import func ObjectiveC.objc_setAssociatedObject
import Foundation
import UIKit
private var _keyboardNotificationObserversKey = "KeyboardNotificationsObserver"
@available(tvOS, unavailable)
extension UIScrollView {
private typealias UserInfoDictionary = Dictionary<AnyHashable, Any>
private final var notificationObservers: Array<NSObjectProtocol> {
get {
guard let observers = objc_getAssociatedObject(self, &_keyboardNotificationObserversKey) as? Array<NSObjectProtocol>
else { return [] }
return observers
}
set { objc_setAssociatedObject(self, &_keyboardNotificationObserversKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
// MARK: Register / Unregister
public final func registerForKeyboardNotifications() {
typealias ObserverBlock = (Notification) -> Void
func block(for selector: @escaping (UserInfoDictionary) -> ()) -> ObserverBlock {
return { $0.userInfo.map(selector) }
}
let tuples: [(Notification.Name, ObserverBlock)] = [
(UIResponder.keyboardWillChangeFrameNotification, block(for: keyboardWillChangeFrame)),
(UIResponder.keyboardWillShowNotification, block(for: keyboardWillShow)),
(UIResponder.keyboardDidHideNotification, block(for: keyboardDidHide))
]
notificationObservers = tuples.map { NotificationCenter.default.addObserver(forName: $0, object: nil, queue: .main, using: $1) }
}
public final func unregisterFromKeyboardNotifications() {
notificationObservers.removeAll()
}
// MARK: Keyboard functions
private final func keyboardWillChangeFrame(userInfo: UserInfoDictionary) {
guard keyboardVisible else { return }
let beginFrame = rect(for: UIResponder.keyboardFrameBeginUserInfoKey, in: userInfo)
let endFrame = rect(for: UIResponder.keyboardFrameEndUserInfoKey, in: userInfo)
let oldHeight = keyboardHeight(from: beginFrame)
let newHeight = keyboardHeight(from: endFrame)
if newHeight != oldHeight {
setInsetsTo(keyboardHeight: newHeight, animated: true, withKeyboardUserInfo: userInfo)
}
}
private final func keyboardWillShow(userInfo: UserInfoDictionary) {
guard !keyboardVisible else { return }
saveEdgeInsets()
keyboardVisible = true
let endFrame = rect(for: UIResponder.keyboardFrameEndUserInfoKey, in: userInfo)
let endHeight = keyboardHeight(from: endFrame)
setInsetsTo(keyboardHeight: endHeight, animated: true, withKeyboardUserInfo: userInfo)
}
private final func keyboardDidHide(userInfo: UserInfoDictionary) {
guard keyboardVisible else { return }
keyboardVisible = false
restoreEdgeInsets(animated: true, userInfo: userInfo)
}
// MARK: Height Adjustments
private final func setInsetsTo(keyboardHeight height: CGFloat, animated: Bool = false, withKeyboardUserInfo userInfo: UserInfoDictionary? = nil) {
let changes: () -> () = {
self.contentInset.bottom = height
if #available(iOS 11.1, tvOS 11.1, macCatalyst 13.0, *) {
self.horizontalScrollIndicatorInsets.bottom = height
self.verticalScrollIndicatorInsets.bottom = height
} else {
self.scrollIndicatorInsets.bottom = height
}
}
let offsetChanges: () -> () = {
if let fr = UIResponder.firstResponder(in: self) as? UIView {
let respFrame = self.convert(fr.frame, from: fr.superview)
self.scrollRectToVisible(respFrame, animated: animated)
}
}
if animated {
animate(changes, withKeyboardUserInfo: userInfo) { _ in offsetChanges() }
} else {
changes()
offsetChanges()
}
}
// MARK: EdgeInsets
private final func saveEdgeInsets() {
originalContentInsets = contentInset
if #available(iOS 11.1, tvOS 11.1, macCatalyst 13.0, *) {
originalHorizontalScrollIndicatorInsets = horizontalScrollIndicatorInsets
originalVerticalScrollIndicatorInsets = verticalScrollIndicatorInsets
} else {
originalScrollIndicatorInsets = scrollIndicatorInsets
}
}
private final func restoreEdgeInsets(animated: Bool = false, userInfo: UserInfoDictionary? = nil) {
let changes: () -> () = {
self.contentInset = self.originalContentInsets
if #available(iOS 11.1, tvOS 11.1, macCatalyst 13.0, *) {
self.horizontalScrollIndicatorInsets = self.originalHorizontalScrollIndicatorInsets
self.verticalScrollIndicatorInsets = self.originalVerticalScrollIndicatorInsets
} else {
self.scrollIndicatorInsets = self.originalScrollIndicatorInsets
}
}
if animated {
animate(changes, withKeyboardUserInfo: userInfo)
} else {
changes()
}
}
// MARK: Helpers
private final func rect(for key: String, in userInfo: UserInfoDictionary) -> CGRect {
(userInfo[key] as? NSValue)?.cgRectValue ?? .zero
}
private final func keyboardHeight(from rect: CGRect) -> CGFloat {
guard let w = window else { return 0 }
let windowFrame = w.convert(bounds, from: self)
let keyboardFrame = windowFrame.intersection(rect)
let coveredFrame = w.convert(keyboardFrame, to: self)
return coveredFrame.size.height
}
private final func animate(_ animations: @escaping () -> (), withKeyboardUserInfo userInfo: UserInfoDictionary? = nil, completion: ((_ finished: Bool) -> ())? = nil) {
var duration: TimeInterval = 1 / 3
var curve: UIView.AnimationCurve = .linear
let options: UIView.AnimationOptions
if let info = userInfo {
if let d = info[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval { duration = d }
if let c = UIView.AnimationCurve(rawValue: (info[UIResponder.keyboardAnimationCurveUserInfoKey] as? UIView.AnimationCurve.RawValue ?? curve.rawValue)) { curve = c }
}
if #available(iOS 13, tvOS 13, watchOS 6, macCatalyst 13, *) {
assert(UIView.AnimationOptions.curveEaseIn.rawValue == UInt(UIView.AnimationCurve.easeIn.rawValue) << 16)
options = [.beginFromCurrentState, .allowAnimatedContent, .allowUserInteraction, UIView.AnimationOptions(rawValue: UInt(curve.rawValue) << 16)]
} else {
options = [.beginFromCurrentState, .allowAnimatedContent, .allowUserInteraction]
}
UIView.animate(withDuration: duration, delay: 0, options: options, animations: {
if #available(iOS 13, tvOS 13, watchOS 6, macCatalyst 13, *) {} else {
UIView.setAnimationCurve(curve)
}
animations()
}, completion: completion)
}
}
private var _originalContentInsetsKey = "OriginalContentInsets"
private var _originalScrollIndicatorInsetsKey = "OriginalScrollIndicatorInsets"
private var _originalHorizontalScrollIndicatorInsetsKey = "OriginalHorizontalScrollIndicatorInsets"
private var _originalVerticalScrollIndicatorInsetsKey = "OriginalVerticalScrollIndicatorInsets"
private var _keyboardVisibleKey = "KeyboardVisible"
fileprivate extension UIScrollView {
private func edgeInsets(forKey key: UnsafeRawPointer) -> UIEdgeInsets? {
(objc_getAssociatedObject(self, key) as? NSValue)?.uiEdgeInsetsValue
}
private func setEdgeInsets(_ edgeInsets: UIEdgeInsets?, forKey key: UnsafeRawPointer) {
objc_setAssociatedObject(self, key, edgeInsets.map(NSValue.init(uiEdgeInsets:)), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
final var originalContentInsets: UIEdgeInsets {
get { edgeInsets(forKey: &_originalContentInsetsKey) ?? .zero }
set { setEdgeInsets(newValue, forKey: &_originalContentInsetsKey) }
}
final var originalScrollIndicatorInsets: UIEdgeInsets {
get { edgeInsets(forKey: &_originalScrollIndicatorInsetsKey) ?? .zero }
set { setEdgeInsets(newValue, forKey: &_originalScrollIndicatorInsetsKey) }
}
final var originalHorizontalScrollIndicatorInsets: UIEdgeInsets {
get { edgeInsets(forKey: &_originalHorizontalScrollIndicatorInsetsKey) ?? .zero }
set { setEdgeInsets(newValue, forKey: &_originalHorizontalScrollIndicatorInsetsKey) }
}
final var originalVerticalScrollIndicatorInsets: UIEdgeInsets {
get { edgeInsets(forKey: &_originalVerticalScrollIndicatorInsetsKey) ?? .zero }
set { setEdgeInsets(newValue, forKey: &_originalVerticalScrollIndicatorInsetsKey) }
}
final var keyboardVisible: Bool {
get { (objc_getAssociatedObject(self, &_keyboardVisibleKey) as? Bool) ?? false }
set { objc_setAssociatedObject(self, &_keyboardVisibleKey, newValue, .OBJC_ASSOCIATION_ASSIGN) }
}
}
#endif
| apache-2.0 | 726e20569a47cd8cac2f7f9a58ee0779 | 44.712963 | 176 | 0.682905 | 5.369222 | false | false | false | false |
wxxsw/GSPhotos | GSPhotos/GSAlbum.swift | 1 | 3425 | //
// GSAlbum.swift
// GSPhotosExample
//
// Created by Gesen on 15/10/28.
// Copyright (c) 2015年 Gesen. All rights reserved.
//
import Foundation
import AssetsLibrary
import Photos
import CoreLocation
public class GSAlbum {
// 原始的 PHAssetCollection 或者 ALAssetsGroup 实例
private(set) var originalAssetCollection: AnyObject
// 相册名称
private(set) var name: String
// 包含的资源数量
private(set) lazy var count: Int = {
if #available(iOS 8, *) {
return PHAsset.fetchAssetsInAssetCollection(self.phAssetCollection, options: nil).count
} else {
return self.alAssetsGroup.numberOfAssets()
}
}()
@available(iOS 8.0, *)
init(phAssetCollection: PHAssetCollection) {
self.originalAssetCollection = phAssetCollection
self.name = phAssetCollection.localizedTitle ?? ""
}
init(alAssetsGroup: ALAssetsGroup) {
self.originalAssetCollection = alAssetsGroup
self.name = alAssetsGroup.valueForProperty(ALAssetsGroupPropertyName) as? String ?? ""
}
/**
获取封面图片
- parameter handler: 完成回调
- returns: 图片请求ID,仅为iOS8+取消图片请求时使用
*/
public func getPosterImage(handler: (UIImage?) -> Void) -> GSImageRequestID {
if let cachePosterImage = cachePosterImage {
handler(cachePosterImage)
return 0
}
if #available(iOS 8, *) {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", GSAssetMediaType.Image.rawValue)
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let fetch = PHAsset.fetchAssetsInAssetCollection(phAssetCollection, options: fetchOptions)
guard let phAsset = fetch.firstObject as? PHAsset else {
handler(nil)
return 0
}
let targetSize = CGSize(width: 150, height: 150)
let contentMode: PHImageContentMode = .AspectFill
let options = PHImageRequestOptions()
options.deliveryMode = .HighQualityFormat
options.resizeMode = .Fast
return PHImageManager.defaultManager().requestImageForAsset(phAsset, targetSize: targetSize, contentMode: contentMode, options: options, resultHandler: { (image, _) in
gs_dispatch_main_async_safe {
self.cachePosterImage = image
handler(image!)
}
})
} else {
let image = UIImage(CGImage: self.alAssetsGroup.posterImage().takeUnretainedValue())
gs_dispatch_main_async_safe {
self.cachePosterImage = image
handler(image)
}
return 0
}
}
// MARK: Private Method
private var cachePosterImage: UIImage?
@available(iOS 8.0, *)
private var phAssetCollection: PHAssetCollection {
return originalAssetCollection as! PHAssetCollection
}
private var alAssetsGroup: ALAssetsGroup {
return originalAssetCollection as! ALAssetsGroup
}
} | mit | 4cc81954aaba6e7498068b25633fcaae | 29.327273 | 179 | 0.590405 | 5.37037 | false | false | false | false |
huonw/swift | test/ClangImporter/objc_missing_designated_init.swift | 11 | 7231 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -typecheck -I %S/Inputs/custom-modules %s -swift-version 4 -verify
import UnimportableMembers
import UnimportableMembersUser
class IncompleteInitSubclassImplicit : IncompleteDesignatedInitializers {
var myOneNewMember = 1
}
class IncompleteInitSubclass : IncompleteDesignatedInitializers {
override init(first: Int) {}
override init(second: Int) {}
}
class IncompleteConvenienceInitSubclass : IncompleteConvenienceInitializers {}
class IncompleteUnknownInitSubclass : IncompleteUnknownInitializers {}
class IncompleteInitCategorySubclassImplicit : IncompleteDesignatedInitializersWithCategory {}
class IncompleteInitCategorySubclass : IncompleteDesignatedInitializersWithCategory {
override init(first: Int) {}
override init(second: Int) {}
}
class DesignatedInitializerInAnotherModuleSubclass : DesignatedInitializerInAnotherModule {}
func testBaseClassesBehaveAsExpected() {
_ = IncompleteDesignatedInitializers(first: 0) // okay
_ = IncompleteDesignatedInitializers(second: 0) // okay
_ = IncompleteDesignatedInitializers(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteDesignatedInitializers(conveniently: 0) // okay
_ = IncompleteDesignatedInitializers(category: 0) // okay
_ = IncompleteConvenienceInitializers(first: 0) // okay
_ = IncompleteConvenienceInitializers(second: 0) // okay
_ = IncompleteConvenienceInitializers(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteConvenienceInitializers(conveniently: 0) // okay
_ = IncompleteConvenienceInitializers(category: 0) // okay
_ = IncompleteUnknownInitializers(first: 0) // okay
_ = IncompleteUnknownInitializers(second: 0) // okay
_ = IncompleteUnknownInitializers(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteUnknownInitializers(conveniently: 0) // okay
_ = IncompleteUnknownInitializers(category: 0) // okay
_ = IncompleteDesignatedInitializersWithCategory(first: 0) // okay
_ = IncompleteDesignatedInitializersWithCategory(second: 0) // okay
_ = IncompleteDesignatedInitializersWithCategory(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteDesignatedInitializersWithCategory(conveniently: 0) // okay
_ = IncompleteDesignatedInitializersWithCategory(category: 0) // okay
_ = DesignatedInitializerInAnotherModule(first: 0) // okay
_ = DesignatedInitializerInAnotherModule(second: 0) // okay
_ = DesignatedInitializerInAnotherModule(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}}
_ = DesignatedInitializerInAnotherModule(conveniently: 0) // okay
_ = DesignatedInitializerInAnotherModule(category: 0) // okay
_ = DesignatedInitializerInAnotherModule(fromOtherModule: 0) // okay
}
func testSubclasses() {
_ = IncompleteInitSubclass(first: 0) // okay
_ = IncompleteInitSubclass(second: 0) // okay
_ = IncompleteInitSubclass(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteInitSubclass(conveniently: 0) // expected-error {{argument labels '(conveniently:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteInitSubclass(category: 0) // expected-error {{argument labels '(category:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteInitSubclassImplicit(first: 0) // okay
_ = IncompleteInitSubclassImplicit(second: 0) // okay
_ = IncompleteInitSubclassImplicit(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteInitSubclassImplicit(conveniently: 0) // expected-error {{argument labels '(conveniently:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteInitSubclassImplicit(category: 0) // expected-error {{argument labels '(category:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteConvenienceInitSubclass(first: 0) // okay
_ = IncompleteConvenienceInitSubclass(second: 0) // okay
_ = IncompleteConvenienceInitSubclass(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteConvenienceInitSubclass(conveniently: 0) // okay
_ = IncompleteConvenienceInitSubclass(category: 0) // okay
_ = IncompleteUnknownInitSubclass(first: 0) // okay
_ = IncompleteUnknownInitSubclass(second: 0) // okay
_ = IncompleteUnknownInitSubclass(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteUnknownInitSubclass(conveniently: 0) // okay
_ = IncompleteUnknownInitSubclass(category: 0) // okay
_ = IncompleteInitCategorySubclass(first: 0) // okay
_ = IncompleteInitCategorySubclass(second: 0) // okay
_ = IncompleteInitCategorySubclass(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteInitCategorySubclass(conveniently: 0) // expected-error {{argument labels '(conveniently:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteInitCategorySubclass(category: 0) // expected-error {{argument labels '(category:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteInitCategorySubclassImplicit(first: 0) // okay
_ = IncompleteInitCategorySubclassImplicit(second: 0) // okay
_ = IncompleteInitCategorySubclassImplicit(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteInitCategorySubclassImplicit(conveniently: 0) // expected-error {{argument labels '(conveniently:)' do not match any available overloads}} expected-note {{overloads}}
_ = IncompleteInitCategorySubclassImplicit(category: 0) // expected-error {{argument labels '(category:)' do not match any available overloads}} expected-note {{overloads}}
_ = DesignatedInitializerInAnotherModuleSubclass(first: 0) // okay
_ = DesignatedInitializerInAnotherModuleSubclass(second: 0) // okay
_ = DesignatedInitializerInAnotherModuleSubclass(missing: 0) // expected-error {{argument labels '(missing:)' do not match any available overloads}} expected-note {{overloads}}
_ = DesignatedInitializerInAnotherModuleSubclass(conveniently: 0) // expected-error {{argument labels '(conveniently:)' do not match any available overloads}} expected-note {{overloads}}
_ = DesignatedInitializerInAnotherModuleSubclass(category: 0) // expected-error {{argument labels '(category:)' do not match any available overloads}} expected-note {{overloads}}
_ = DesignatedInitializerInAnotherModuleSubclass(fromOtherModule: 0) // okay
}
| apache-2.0 | 29fcffa4bdf6fb82797bfb1d0208000a | 67.866667 | 188 | 0.766146 | 5.436842 | false | false | false | false |
UberJason/PlaidClient | Pods/Alamofire/Source/Manager.swift | 9 | 38963 | //
// Manager.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/**
Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
*/
public class Manager {
// MARK: - Properties
/**
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly
for any ad hoc requests.
*/
public static let sharedInstance: Manager = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
return Manager(configuration: configuration)
}()
/**
Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
*/
public static let defaultHTTPHeaders: [String: String] = {
// Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
// Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in
let quality = 1.0 - (Double(index) * 0.1)
return "\(languageCode);q=\(quality)"
}.joinWithSeparator(", ")
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
let osNameVersion: String = {
let versionString: String
if #available(OSX 10.10, *) {
let version = NSProcessInfo.processInfo().operatingSystemVersion
versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
} else {
versionString = "10.9"
}
let osName: String = {
#if os(iOS)
return "iOS"
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(OSX)
return "OS X"
#elseif os(Linux)
return "Linux"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
return "\(executable)/\(bundle) (\(appVersion)/\(appBuild)); \(osNameVersion))"
}
return "Alamofire"
}()
return [
"Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent
]
}()
let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
/// The underlying session.
public let session: NSURLSession
/// The session delegate handling all the task and session delegate callbacks.
public let delegate: SessionDelegate
/// Whether to start requests immediately after being constructed. `true` by default.
public var startRequestsImmediately: Bool = true
/**
The background completion handler closure provided by the UIApplicationDelegate
`application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
will automatically call the handler.
If you need to handle your own events before the handler is called, then you need to override the
SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
`nil` by default.
*/
public var backgroundCompletionHandler: (() -> Void)?
// MARK: - Lifecycle
/**
Initializes the `Manager` instance with the specified configuration, delegate and server trust policy.
- parameter configuration: The configuration used to construct the managed session.
`NSURLSessionConfiguration.defaultSessionConfiguration()` by default.
- parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
default.
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
challenges. `nil` by default.
- returns: The new `Manager` instance.
*/
public init(
configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
/**
Initializes the `Manager` instance with the specified session, delegate and server trust policy.
- parameter session: The URL session.
- parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
challenges. `nil` by default.
- returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter.
*/
public init?(
session: NSURLSession,
delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
guard delegate === session.delegate else { return nil }
self.delegate = delegate
self.session = session
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) {
session.serverTrustPolicyManager = serverTrustPolicyManager
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
guard let strongSelf = self else { return }
dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() }
}
}
deinit {
session.invalidateAndCancel()
}
// MARK: - Request
/**
Creates a request for the specified method, URL string, parameters, parameter encoding and headers.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter parameters: The parameters. `nil` by default.
- parameter encoding: The parameter encoding. `.URL` by default.
- parameter headers: The HTTP headers. `nil` by default.
- returns: The created request.
*/
public func request(
method: Method,
_ URLString: URLStringConvertible,
parameters: [String: AnyObject]? = nil,
encoding: ParameterEncoding = .URL,
headers: [String: String]? = nil)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
return request(encodedURLRequest)
}
/**
Creates a request for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request
- returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
var dataTask: NSURLSessionDataTask!
dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) }
let request = Request(session: session, task: dataTask)
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: - SessionDelegate
/**
Responsible for handling all delegate callbacks for the underlying session.
*/
public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate] = [:]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
/// Access the task delegate for the specified task in a thread-safe manner.
public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] }
return subdelegate
}
set {
dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue }
}
}
/**
Initializes the `SessionDelegate` instance.
- returns: The new `SessionDelegate` instance.
*/
public override init() {
super.init()
}
// MARK: - NSURLSessionDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`.
public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)?
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`.
public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`.
public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the session has been invalidated.
- parameter session: The session object that was invalidated.
- parameter error: The error that caused invalidation, or nil if the invalidation was explicit.
*/
public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
sessionDidBecomeInvalidWithError?(session, error)
}
/**
Requests credentials from the delegate in response to a session-level authentication request from the remote server.
- parameter session: The session containing the task that requested authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
*/
public func URLSession(
session: NSURLSession,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{
guard sessionDidReceiveChallengeWithCompletion == nil else {
sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
return
}
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
(disposition, credential) = sessionDidReceiveChallenge(session, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if let
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
disposition = .UseCredential
credential = NSURLCredential(forTrust: serverTrust)
} else {
disposition = .CancelAuthenticationChallenge
}
}
}
completionHandler(disposition, credential)
}
/**
Tells the delegate that all messages enqueued for a session have been delivered.
- parameter session: The session that no longer has any outstanding requests.
*/
public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: - NSURLSessionTaskDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and
/// requires the caller to call the `completionHandler`.
public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and
/// requires the caller to call the `completionHandler`.
public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and
/// requires the caller to call the `completionHandler`.
public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`.
public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the remote server requested an HTTP redirect.
- parameter session: The session containing the task whose request resulted in a redirect.
- parameter task: The task whose request resulted in a redirect.
- parameter response: An object containing the server’s response to the original request.
- parameter request: A URL request object filled out with the new location.
- parameter completionHandler: A closure that your handler should call with either the value of the request
parameter, a modified URL request object, or NULL to refuse the redirect and
return the body of the redirect response.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest,
completionHandler: NSURLRequest? -> Void)
{
guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
return
}
var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
/**
Requests credentials from the delegate in response to an authentication request from the remote server.
- parameter session: The session containing the task whose request requires authentication.
- parameter task: The task whose request requires authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)
{
guard taskDidReceiveChallengeWithCompletion == nil else {
taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
return
}
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
let result = taskDidReceiveChallenge(session, task, challenge)
completionHandler(result.0, result.1)
} else if let delegate = self[task] {
delegate.URLSession(
session,
task: task,
didReceiveChallenge: challenge,
completionHandler: completionHandler
)
} else {
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
/**
Tells the delegate when a task requires a new request body stream to send to the remote server.
- parameter session: The session containing the task that needs a new body stream.
- parameter task: The task that needs a new body stream.
- parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
needNewBodyStream completionHandler: NSInputStream? -> Void)
{
guard taskNeedNewBodyStreamWithCompletion == nil else {
taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
return
}
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
/**
Periodically informs the delegate of the progress of sending body content to the server.
- parameter session: The session containing the data task.
- parameter task: The data task.
- parameter bytesSent: The number of bytes sent since the last time this delegate method was called.
- parameter totalBytesSent: The total number of bytes sent so far.
- parameter totalBytesExpectedToSend: The expected length of the body data.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(
session,
task: task,
didSendBodyData: bytesSent,
totalBytesSent: totalBytesSent,
totalBytesExpectedToSend: totalBytesExpectedToSend
)
}
}
/**
Tells the delegate that the task finished transferring data.
- parameter session: The session containing the task whose request finished transferring data.
- parameter task: The task whose request finished transferring data.
- parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil.
*/
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let taskDidComplete = taskDidComplete {
taskDidComplete(session, task, error)
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
}
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task)
self[task] = nil
}
// MARK: - NSURLSessionDataDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`.
public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the data task received the initial reply (headers) from the server.
- parameter session: The session containing the data task that received an initial reply.
- parameter dataTask: The data task that received an initial reply.
- parameter response: A URL response object populated with headers.
- parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
constant to indicate whether the transfer should continue as a data task or
should become a download task.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse,
completionHandler: NSURLSessionResponseDisposition -> Void)
{
guard dataTaskDidReceiveResponseWithCompletion == nil else {
dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
return
}
var disposition: NSURLSessionResponseDisposition = .Allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
/**
Tells the delegate that the data task was changed to a download task.
- parameter session: The session containing the task that was replaced by a download task.
- parameter dataTask: The data task that was replaced by a download task.
- parameter downloadTask: The new download task that replaced the data task.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
{
if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
} else {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
}
/**
Tells the delegate that the data task has received some of the expected data.
- parameter session: The session containing the data task that provided data.
- parameter dataTask: The data task that provided data.
- parameter data: A data object containing the transferred data.
*/
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
}
/**
Asks the delegate whether the data (or upload) task should store the response in the cache.
- parameter session: The session containing the data (or upload) task.
- parameter dataTask: The data (or upload) task.
- parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
caching policy and the values of certain received headers, such as the Pragma
and Cache-Control headers.
- parameter completionHandler: A block that your handler must call, providing either the original proposed
response, a modified version of that response, or NULL to prevent caching the
response. If your delegate implements this method, it must call this completion
handler; otherwise, your app leaks memory.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
willCacheResponse proposedResponse: NSCachedURLResponse,
completionHandler: NSCachedURLResponse? -> Void)
{
guard dataTaskWillCacheResponseWithCompletion == nil else {
dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
return
}
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(
session,
dataTask: dataTask,
willCacheResponse: proposedResponse,
completionHandler: completionHandler
)
} else {
completionHandler(proposedResponse)
}
}
// MARK: - NSURLSessionDownloadDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`.
public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that a download task has finished downloading.
- parameter session: The session containing the download task that finished.
- parameter downloadTask: The download task that finished.
- parameter location: A file URL for the temporary file. Because the file is temporary, you must either
open the file for reading or move it to a permanent location in your app’s sandbox
container directory before returning from this delegate method.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL)
{
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
}
/**
Periodically informs the delegate about the download’s progress.
- parameter session: The session containing the download task.
- parameter downloadTask: The download task.
- parameter bytesWritten: The number of bytes transferred since the last time this delegate
method was called.
- parameter totalBytesWritten: The total number of bytes transferred so far.
- parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
header. If this header was not provided, the value is
`NSURLSessionTransferSizeUnknown`.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(
session,
downloadTask: downloadTask,
didWriteData: bytesWritten,
totalBytesWritten: totalBytesWritten,
totalBytesExpectedToWrite: totalBytesExpectedToWrite
)
}
}
/**
Tells the delegate that the download task has resumed downloading.
- parameter session: The session containing the download task that finished.
- parameter downloadTask: The download task that resumed. See explanation in the discussion.
- parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
existing content, then this value is zero. Otherwise, this value is an
integer representing the number of bytes on disk that do not need to be
retrieved again.
- parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(
session,
downloadTask: downloadTask,
didResumeAtOffset: fileOffset,
expectedTotalBytes: expectedTotalBytes
)
}
}
// MARK: - NSURLSessionStreamDelegate
var _streamTaskReadClosed: Any?
var _streamTaskWriteClosed: Any?
var _streamTaskBetterRouteDiscovered: Any?
var _streamTaskDidBecomeInputStream: Any?
// MARK: - NSObject
public override func respondsToSelector(selector: Selector) -> Bool {
#if !os(OSX)
if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) {
return sessionDidFinishEventsForBackgroundURLSession != nil
}
#endif
switch selector {
case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)):
return sessionDidBecomeInvalidWithError != nil
case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)):
return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil)
case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)):
return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
| mit | 67f9678309bd051563127ffcdf7b597d | 49.008986 | 197 | 0.644197 | 6.773952 | false | false | false | false |
antrix1989/PhotoSlider | Pod/Classes/ViewController.swift | 1 | 13795 | //
// ViewController.swift
//
// Created by nakajijapan on 3/28/15.
// Copyright (c) 2015 net.nakajijapan. All rights reserved.
//
import UIKit
import SDWebImage
@objc public protocol PhotoSliderDelegate:NSObjectProtocol {
optional func photoSliderControllerWillDismiss(viewController: PhotoSlider.ViewController)
optional func photoSliderControllerDidDismiss(viewController: PhotoSlider.ViewController)
}
enum PhotoSliderControllerScrollMode:Int {
case None = 0, Vertical, Horizontal, Rotating
}
public class ViewController:UIViewController, UIScrollViewDelegate {
var scrollView:UIScrollView!
var imageURLs:Array<NSURL>?
var backgroundView:UIView!
var effectView:UIVisualEffectView!
var closeButton:UIButton?
var scrollMode:PhotoSliderControllerScrollMode = .None
var scrollInitalized = false
var closeAnimating = false
var imageViews = Array<PhotoSlider.ImageView>()
public var delegate: PhotoSliderDelegate? = nil
public var visiblePageControl = true
public var visibleCloseButton = true
public var currentPage = 0
public var pageControl = UIPageControl()
public var backgroundViewColor = UIColor.blackColor()
public init(imageURLs:Array<NSURL>) {
super.init(nibName: nil, bundle: nil)
self.imageURLs = imageURLs
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public override func viewDidLoad() {
super.viewDidLoad()
self.view.frame = UIScreen.mainScreen().bounds
self.view.backgroundColor = UIColor.clearColor()
self.view.userInteractionEnabled = true
self.backgroundView = UIView(frame: self.view.bounds)
self.backgroundView.backgroundColor = backgroundViewColor
if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1 {
self.view.addSubview(self.backgroundView)
} else {
self.effectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Dark))
self.effectView.frame = self.view.bounds
self.view.addSubview(self.effectView)
self.effectView.addSubview(self.backgroundView)
}
// scrollview setting for Item
self.scrollView = UIScrollView(frame: CGRectMake(0, 0, self.view.bounds.width, self.view.bounds.height))
self.scrollView.pagingEnabled = true
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.delegate = self
self.scrollView.clipsToBounds = false
self.scrollView.alwaysBounceHorizontal = true
self.scrollView.alwaysBounceVertical = true
self.scrollView.scrollEnabled = true
self.view.addSubview(self.scrollView)
self.scrollView.contentSize = CGSizeMake(
CGRectGetWidth(self.view.bounds) * CGFloat(self.imageURLs!.count),
CGRectGetHeight(self.view.bounds) * 3.0
)
let width = CGRectGetWidth(self.view.bounds)
let height = CGRectGetHeight(self.view.bounds)
var frame = self.view.bounds
frame.origin.y = height
for imageURL in self.imageURLs! {
var imageView:PhotoSlider.ImageView = PhotoSlider.ImageView(frame: frame)
self.scrollView.addSubview(imageView)
imageView.loadImage(imageURL)
frame.origin.x += width
imageViews.append(imageView)
}
// Page Control
if self.visiblePageControl {
self.pageControl.frame = CGRectZero
self.pageControl.numberOfPages = imageURLs!.count
self.pageControl.currentPage = 0
self.pageControl.userInteractionEnabled = false
self.view.addSubview(self.pageControl)
self.layoutPageControl()
}
// Close Button
if self.visibleCloseButton {
self.closeButton = UIButton(frame: CGRectZero)
var imagePath = self.resourceBundle().pathForResource("PhotoSliderClose", ofType: "png")
self.closeButton!.setImage(UIImage(contentsOfFile: imagePath!), forState: UIControlState.Normal)
self.closeButton!.addTarget(self, action: "closeButtonDidTap:", forControlEvents: UIControlEvents.TouchUpInside)
self.closeButton!.imageView?.contentMode = UIViewContentMode.Center;
self.view.addSubview(self.closeButton!)
self.layoutCloseButton()
}
if self.respondsToSelector("setNeedsStatusBarAppearanceUpdate") {
self.setNeedsStatusBarAppearanceUpdate()
}
}
override public func viewWillAppear(animated: Bool) {
self.scrollView.contentOffset = CGPointMake(self.scrollView.bounds.width * CGFloat(self.currentPage), self.scrollView.bounds.height)
self.scrollInitalized = true
}
public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.dismissViewControllerAnimated(true) { () -> Void in
self.view.removeFromSuperview()
}
}
// MARK: - Constraints
func layoutCloseButton() {
self.closeButton!.setTranslatesAutoresizingMaskIntoConstraints(false)
var views = ["closeButton": self.closeButton!]
var constraintVertical = NSLayoutConstraint.constraintsWithVisualFormat("V:|-22-[closeButton(32@32)]", options: NSLayoutFormatOptions(0), metrics: nil, views: views)
var constraintHorizontal = NSLayoutConstraint.constraintsWithVisualFormat("H:[closeButton]-22-|", options: NSLayoutFormatOptions(0), metrics: nil, views: views)
self.view.addConstraints(constraintVertical)
self.view.addConstraints(constraintHorizontal)
}
func layoutPageControl() {
self.pageControl.setTranslatesAutoresizingMaskIntoConstraints(false)
var views = ["pageControl": self.pageControl]
var constraintVertical = NSLayoutConstraint.constraintsWithVisualFormat("V:[pageControl]-22-|", options: NSLayoutFormatOptions(0), metrics: nil, views: views)
var constraintCenterX = NSLayoutConstraint.constraintsWithVisualFormat("H:|[pageControl]|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: views)
self.view.addConstraints(constraintVertical)
self.view.addConstraints(constraintCenterX)
}
// MARK: - UIScrollViewDelegate
var scrollPreviewPoint = CGPointZero;
public func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.scrollPreviewPoint = scrollView.contentOffset
}
public func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollInitalized == false {
self.generateCurrentPage()
return
}
if self.scrollMode == .Rotating {
return
}
let offsetX = fabs(scrollView.contentOffset.x - self.scrollPreviewPoint.x)
let offsetY = fabs(scrollView.contentOffset.y - self.scrollPreviewPoint.y)
if self.scrollMode == .None {
if (offsetY > offsetX) {
self.scrollMode = .Vertical;
} else {
self.scrollMode = .Horizontal;
}
}
if self.scrollMode == .Vertical {
let offsetHeight = fabs(scrollView.frame.size.height - scrollView.contentOffset.y)
let alpha = 1.0 - (fabs(offsetHeight) / (scrollView.frame.size.height / 2.0))
self.backgroundView.alpha = alpha
var contentOffset = scrollView.contentOffset
contentOffset.x = self.scrollPreviewPoint.x
scrollView.contentOffset = contentOffset
let screenHeight = UIScreen.mainScreen().bounds.size.height
if self.scrollView.contentOffset.y > screenHeight * 1.4 {
self.closePhotoSlider(true)
} else if self.scrollView.contentOffset.y < screenHeight * 0.6 {
self.closePhotoSlider(false)
}
} else if self.scrollMode == .Horizontal {
var contentOffset = scrollView.contentOffset
contentOffset.y = self.scrollPreviewPoint.y
scrollView.contentOffset = contentOffset
}
// Save current page index.
var previousPage = self.pageControl.currentPage
// Update current page index.
self.generateCurrentPage()
// If page index has changed - reset zoom scale for previous image.
if previousPage != self.pageControl.currentPage {
var imageView = imageViews[previousPage]
imageView.scrollView.zoomScale = imageView.scrollView.minimumZoomScale
}
}
func generateCurrentPage() {
self.currentPage = abs(Int(scrollView.contentOffset.x / scrollView.frame.size.width))
if fmod(scrollView.contentOffset.x, scrollView.frame.size.width) == 0.0 {
if self.visiblePageControl {
self.pageControl.currentPage = self.currentPage
}
}
}
public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if self.scrollMode == .Vertical {
let velocity = scrollView.panGestureRecognizer.velocityInView(scrollView)
if velocity.y < -500 {
self.scrollView.frame = scrollView.frame;
self.closePhotoSlider(true)
} else if velocity.y > 500 {
self.scrollView.frame = scrollView.frame;
self.closePhotoSlider(false)
}
}
}
func closePhotoSlider(up:Bool) {
if self.closeAnimating == true {
return
}
self.closeAnimating = true
let screenHeight = UIScreen.mainScreen().bounds.size.height
let screenWidth = UIScreen.mainScreen().bounds.size.width
var movedHeight = CGFloat(0)
if (self.delegate?.respondsToSelector("photoSliderControllerWillDismiss:") != nil) {
self.delegate?.photoSliderControllerWillDismiss?(self)
}
if up {
movedHeight = -screenHeight
} else {
movedHeight = screenHeight
}
UIView.animateWithDuration(
0.4,
delay: 0,
options: UIViewAnimationOptions.CurveEaseOut,
animations: { () -> Void in
self.scrollView.frame = CGRectMake(0, movedHeight, screenWidth, screenHeight)
self.backgroundView.alpha = 0.0
self.closeButton?.alpha = 0.0
self.view.alpha = 0.0
},
completion: {(result) -> Void in
self.dissmissViewControllerAnimated(false)
self.closeAnimating = false
}
)
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
self.scrollMode = .None
}
// MARK: - Button Actions
func closeButtonDidTap(sender:UIButton) {
if (self.delegate?.respondsToSelector("photoSliderControllerWillDismiss:") != nil) {
self.delegate?.photoSliderControllerWillDismiss?(self)
}
self.dissmissViewControllerAnimated(true)
}
// MARK: - Private Methods
func dissmissViewControllerAnimated(animated:Bool) {
self.dismissViewControllerAnimated(animated, completion: { () -> Void in
if (self.delegate?.respondsToSelector("photoSliderControllerDidDismiss:") != nil) {
self.delegate?.photoSliderControllerDidDismiss?(self)
}
})
}
func resourceBundle() -> NSBundle {
var bundlePath = NSBundle.mainBundle().pathForResource(
"PhotoSlider",
ofType: "bundle",
inDirectory: "Frameworks/PhotoSlider.framework"
)
var bundle = NSBundle(path: bundlePath!)
return bundle!
}
// MARK: - UITraitEnvironment
public override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
self.scrollMode = .Rotating
let contentViewBounds = self.view.bounds
let height = contentViewBounds.height
// Background View
self.backgroundView.frame = contentViewBounds
if floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1 {
self.effectView.frame = contentViewBounds
}
// Scroll View
self.scrollView.contentSize = CGSizeMake(
contentViewBounds.width * CGFloat(self.imageURLs!.count),
contentViewBounds.height * 3.0
)
self.scrollView.frame = contentViewBounds;
// ImageViews
var frame = CGRect(x: 0.0, y: contentViewBounds.height, width: contentViewBounds.width, height: contentViewBounds.height)
for i in 0..<self.scrollView.subviews.count {
var imageView = self.scrollView.subviews[i] as! PhotoSlider.ImageView
imageView.frame = frame
frame.origin.x += contentViewBounds.size.width
imageView.scrollView.frame = contentViewBounds
}
self.scrollView.contentOffset = CGPointMake(CGFloat(self.currentPage) * contentViewBounds.width, height)
self.scrollMode = .None
}
}
| mit | 25aa9839683029c7f137f1afc69cbfa8 | 36.691257 | 175 | 0.637477 | 5.537937 | false | false | false | false |
Zewo/GrandCentralDispatch | Sources/IOChannel.swift | 1 | 4577 | // IOChannel.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public enum IOChannelType {
case Stream
case RandomAccess
private var value: dispatch_io_type_t {
switch self {
case .Stream: return DISPATCH_IO_STREAM
case .RandomAccess: return DISPATCH_IO_RANDOM
}
}
}
public enum IOChannelCleanUpResult {
case Success
case Failure(error: ErrorProtocol)
public func success(f: Void -> Void) {
switch self {
case Success: f()
default: break
}
}
public func failure(f: ErrorProtocol -> Void) {
switch self {
case Failure(let e): f(e)
default: break
}
}
}
public enum IOChannelResult {
case Success(done: Bool, data: [Int8])
case Canceled(data: [Int8])
case Failure(error: ErrorProtocol)
public func success(f: (done: Bool, data: [Int8]) -> Void) {
switch self {
case Success(let done, let data): f(done: done, data: data)
default: break
}
}
public func failure(f: ErrorProtocol -> Void) {
switch self {
case Failure(let e): f(e)
default: break
}
}
public func canceled(f: (data: [Int8]) -> Void) {
switch self {
case Canceled(let data): f(data: data)
default: break
}
}
}
public struct IOChannel {
let channel: dispatch_io_t
public init(type: IOChannelType, fileDescriptor: Int32, queue: Queue = defaultQueue, cleanupHandler: IOChannelCleanUpResult -> Void) {
channel = dispatch_io_create(type.value, fileDescriptor, queue.queue) { errorNumber in
if errorNumber == 0 {
cleanupHandler(.Success)
} else {
let error = DispatchError.fromErrorNumber(errorNumber)
cleanupHandler(.Failure(error: error))
}
}!
}
public func read(offset: Int64 = 0, length: Int = Int.max, queue: Queue = defaultQueue, handler: IOChannelResult -> Void) {
let mappedHandler = mapHandler(handler)
dispatch_io_read(channel, offset, length, queue.queue, mappedHandler)
}
public func write(offset: Int64 = 0, length: Int = Int.max, queue: Queue = defaultQueue, data: [Int8], handler: IOChannelResult -> Void) {
let data = dispatch_data_create(data, data.count, queue.queue, nil)
let mappedHandler = mapHandler(handler)
dispatch_io_write(channel, offset, data, queue.queue, mappedHandler)
}
private func mapHandler(handler: IOChannelResult -> Void) -> (done: Bool, data: dispatch_data_t!, errorNumber: Int32) -> Void {
return { done, data, errorNumber in
if errorNumber == ECANCELED {
handler(.Canceled(data: bufferFromData(data)))
} else if errorNumber != 0 {
let error = DispatchError.fromErrorNumber(errorNumber)
handler(.Failure(error: error))
} else {
handler(.Success(done: done, data: bufferFromData(data)))
}
}
}
public func setLowWater(lowWater: Int) {
dispatch_io_set_low_water(channel, lowWater)
}
public func setHighWater(highWater: Int) {
dispatch_io_set_high_water(channel, highWater)
}
public var fileDescriptor: Int32 {
return dispatch_io_get_descriptor(channel)
}
public func close() {
dispatch_io_close(channel, DISPATCH_IO_STOP)
}
}
| mit | 6a15848a18b9245d2f8cba247d3c6406 | 32.166667 | 142 | 0.641031 | 4.27757 | false | false | false | false |
ZHSD/ZHZB | ZHZB/ZHZB/Classes/Main/View/PageContentView.swift | 1 | 6000 | //
// PageContentView.swift
// ZHZB
//
// Created by 张浩 on 2016/11/16.
// Copyright © 2016年 张浩. All rights reserved.
//
import UIKit
//MARK: -定义代理协议用来告诉HomeViewController,然后传给pageTitleView
protocol pageContentViewDelegate : class {
func pageContentView(contentView : PageContentView, progress : CGFloat,sourceIndex : Int, targetIndex : Int )
}
fileprivate let contentCellID = "contentCellID"
class PageContentView: UIView {
//MARK: -定义属性
weak var delegate : pageContentViewDelegate?
fileprivate var childVcs : [UIViewController]
// weak只能修饰可选类型
fileprivate weak var parentViewController : UIViewController?
// MARK:- 记录开滑动的offsetX
fileprivate var startOffsetX : CGFloat = 0
// MARK:- 禁止滚动,避免重复的执行事件
fileprivate var isForbidScrollDelegate: Bool = false
//MARK: -懒加载属性
fileprivate lazy var collectionView : UICollectionView = {[weak self] in
//1.创建layuot
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
//创建collectionView
let collectionV = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionV.showsHorizontalScrollIndicator = false
collectionV.isPagingEnabled = true
collectionV.bounces = false
//设置数据源
collectionV.dataSource = self
collectionV.delegate = self
//注册cell
collectionV.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellID)
return collectionV
}()
//MARK: -自定义构造函数
init(frame: CGRect, childVcs:[UIViewController],parentViewController:UIViewController?) {
self.childVcs = childVcs
self.parentViewController = parentViewController
super.init(frame: frame)
//1.设置界面
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: -设置UI界面
extension PageContentView {
fileprivate func setupUI(){
//1.将所有的子控制器添加到父控制器中
for childeVc in childVcs {
parentViewController?.addChildViewController(childeVc)
}
//2.添加UICollectionView 用于在cell添加控制器
addSubview(collectionView)
collectionView.frame = bounds
}
}
//MARK: -遵守UIcollectionView的dataSource
extension PageContentView:UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1.创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellID, for: indexPath)
//2.设置cell内容
//以为循环使用,避免多次添加需要先移除一下
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
//MARK: -遵守UIcollectionView的代理
extension PageContentView :UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 0.判断是否是点击事件
if isForbidScrollDelegate { return}
//1.定义需要获取的数据
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
//2.判断是左滑还是右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX{//左滑
//2.1计算progress
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
//2.2计算sourceIndex
sourceIndex = Int(currentOffsetX / scrollViewW)
//2.3计算targetIndexs
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count {
targetIndex = childVcs.count - 1
}
//2.4 如果完全划过去
if currentOffsetX - startOffsetX == scrollViewW {
progress = 1
targetIndex = sourceIndex
}
}else {//右滑
//2.1计算progress
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
//2.2计算targetIndexs
targetIndex = Int(currentOffsetX / scrollViewW)
//2.3计算sourceIndex
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count {
sourceIndex = childVcs.count - 1
}
}
//3.通知代理,将progress/sourceIndex/targetIndex传递给TitleView
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
// print("progress:\(progress), sourceIndex:\(sourceIndex),targetIndex:\(targetIndex)")
}
}
//MARK: -对外暴露的方法
extension PageContentView {
func setCurrentIndent(currentIndex : Int) {
// 1.记录需要禁止执行代理方法
isForbidScrollDelegate = true
// 2.滚到正确的位置
let offsetX = CGFloat(currentIndex) * ZHScreenW
collectionView.setContentOffset(CGPoint(x : offsetX,y:0 ), animated: false)
}
}
| mit | ef7a61a20144568c443d7c262dc3a6c2 | 34.812903 | 124 | 0.651054 | 5.296756 | false | false | false | false |
mspvirajpatel/SwiftyBase | SwiftyBase/Classes/Utility/AppAlert.swift | 1 | 3388 | //
// AppAlert.swift
// Pods
//
// Created by MacMini-2 on 31/08/17.
//
//
import Foundation
public class AppAlert {
private var alertController: UIAlertController
public init(title: String? = nil, message: String? = nil, preferredStyle: UIAlertController.Style) {
self.alertController = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)
}
public func setTitle(_ title: String) -> Self {
alertController.title = title
return self
}
public func setMessage(_ message: String) -> Self {
alertController.message = message
return self
}
public func setPopoverPresentationProperties(sourceView: UIView? = nil, sourceRect: CGRect? = nil, barButtonItem: UIBarButtonItem? = nil, permittedArrowDirections: UIPopoverArrowDirection? = nil) -> Self {
if let poc = alertController.popoverPresentationController {
if let view = sourceView {
poc.sourceView = view
}
if let rect = sourceRect {
poc.sourceRect = rect
}
if let item = barButtonItem {
poc.barButtonItem = item
}
if let directions = permittedArrowDirections {
poc.permittedArrowDirections = directions
}
}
return self
}
public func addAction(title: String = "", style: UIAlertAction.Style = .default, handler: @escaping ((UIAlertAction?) -> Void) = { _ in }) -> Self {
alertController.addAction(UIAlertAction(title: title, style: style, handler: handler))
return self
}
public func addTextFieldHandler(_ handler: @escaping ((UITextField?) -> Void) = { _ in }) -> Self {
alertController.addTextField(configurationHandler: handler)
return self
}
public func build() -> UIAlertController {
return alertController
}
}
////Used For Open AlertBox
//
//AppAlert(title: "Enter Tilte", message: "Please type message", preferredStyle: .alert)
// .addAction(title: "NO", style: .cancel) { _ in
// // action
// }
// .addAction(title: "Okay", style: .default) { _ in
// // action
// }
// .build()
// .show(animated: true)
//
// --------------------------------------------------------------------------------
//
////Used For ActionSheet Open
//
//if UIDevice.current.userInterfaceIdiom != .pad {
// // Sample to show on iPad
// AppAlert(title: "Question", message: "Are you sure?", preferredStyle: .actionSheet)
// .addAction(title: "NO", style: .cancel) {_ in
// print("No")
// }
// .addAction(title: "YES", style: .default) { _ in
// print("Yes")
// }
// .build()
// .showAlert(animated: true)
//} else {
// // Sample to show on iPad
// AppAlert(title: "Question", message: "Are you sure?", preferredStyle: .actionSheet)
// .addAction(title: "Not Sure", style: .default) {
// _ in
// print("No")
// }
// .addAction(title: "YES", style: .default) { _ in
// print("Yes")
// }
// .setPopoverPresentationProperties(sourceView: self, sourceRect: CGRect.init(x: 0, y: 0, width: 100, height: 100), barButtonItem: nil, permittedArrowDirections: .any)
// .build()
// .showAlert(animated: true)
//}
//
| mit | a1964e96489293f3036ff8505630e1dd | 31.266667 | 209 | 0.57497 | 4.371613 | false | false | false | false |
ricealexanderb/forager | NewPatchViewController.swift | 1 | 5824 | //
// NewPatchViewController.swift
// Foragr
//
// Created by Alex on 8/13/14.
// Copyright (c) 2014 Alex Rice. All rights reserved.
//
import UIKit
class NewPatchViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate {
@IBOutlet weak var nextHarvest: UIDatePicker!
@IBOutlet weak var remindMe: UISwitch!
@IBOutlet weak var plantTypeTextField: UITextField!
@IBOutlet weak var suggestionLabel: UILabel!
@IBOutlet weak var slidingView: UIView!
@IBOutlet weak var topOfViewConstraint: NSLayoutConstraint!
var plantTypes = ["Raspberries","Blackberries","Blueberries"]
// TODO autocomplete should clear when there are no longer matching strings.
// NOTE: look into "attributed strings"
override func viewDidLoad() {
super.viewDidLoad()
self.nextHarvest.datePickerMode = UIDatePickerMode.Date
let nextButton = UIBarButtonItem(title: "Next", style: UIBarButtonItemStyle.Bordered, target: self, action: "goNext")
self.navigationItem.rightBarButtonItem = nextButton
plantTypeTextField.delegate = self
suggestionLabel.textColor = UIColor.lightGrayColor()
var tapRecognizer = UITapGestureRecognizer(target: self, action: "completeSuggestion:")
self.suggestionLabel.addGestureRecognizer(tapRecognizer)
}
func completeSuggestion(sender: UITapGestureRecognizer) {
plantTypeTextField.text = suggestionLabel.text
suggestionLabel.text = ""
println("completed")
}
@IBAction func remindMeToggled(sender: AnyObject) {
//UIUserNotificationSettings.aut
}
func goNext() {
self.performSegueWithIdentifier("toPinMap", sender: self)
}
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
println("replacement string: \(string)")
if string == "" {
println("backspace")
}
if countElements(plantTypeTextField.text) == 1 && string == "" {
println("zero")
suggestionLabel.text = ""
return true
}
var currentText = textField.text + string
currentText = currentText.lowercaseString
//
// UIColor* bgColor = [UIColor orangeColor];
// NSDictionary* style = @{
// NSBackgroundColorAttributeName: bgColor
// };
//
// NSAttributedString* myString = [[NSAttributedString alloc] initWithString:@"Touch Code Magazine"
// attributes:style];
for suggestion in plantTypes {
var normalizedSuggestion = suggestion.lowercaseString
if (normalizedSuggestion.hasPrefix(currentText)) {
var range = NSMakeRange(0, countElements(currentText))
// var bgColor = UIColor.blueColor()
// var style = [ NSBackgroundColorAttributeName : bgColor ]
//NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
var boldFontName = UIFont.boldSystemFontOfSize(17)
//var suggestionString = NSAttributedString(string: suggestion, attributes: style)
var suggestionWithBoldedSubstring = NSMutableAttributedString(string: suggestion)
suggestionWithBoldedSubstring.addAttribute(NSFontAttributeName, value: boldFontName, range: range)
suggestionLabel.attributedText = suggestionWithBoldedSubstring
//[mutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:subStringRange];
//suggestionLabel.attributedText = suggestionString
//suggestionLabel.text = suggestion
return true
}
}
//suggestionLabel.text = string
return true
}
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
self.plantTypeTextField.resignFirstResponder()
}
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
var newPin = segue.destinationViewController as NewPinViewController
newPin.plantName = plantTypeTextField.text
println("Setting Pin's name to \(plantTypeTextField.text)")
newPin.nextHarvest = nextHarvest.date
if remindMe.on {
println("pre segue Set reminder")
} else {
println("pre segue don't set reminder")
}
newPin.reminder = remindMe.on
}
//MARK: plant type picker
func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int {
return plantTypes.count
}
func pickerView(pickerView: UIPickerView!, titleForRow row: Int,forComponent component: Int) -> String! {
return plantTypes[row]
}
func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int {
return 1
}
func textFieldDidBeginEditing(textField: UITextField!) {
println("slide out")
//self.view.layoutIfNeeded()
topOfViewConstraint.constant += 30
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
func textFieldDidEndEditing(textField: UITextField!) {
println("slide in")
topOfViewConstraint.constant -= 30
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
}
| mit | fb71f1813d71f0ac09e144f9ccca550e | 33.874251 | 134 | 0.625515 | 5.789264 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Seller/views/SLV_UserReviewGroupView.swift | 1 | 3896 | //
// SLV_UserReviewGroupView.swift
// selluv-ios
//
// Created by 조백근 on 2017. 2. 13..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import UIKit
class SLV_UserReviewGroupView: UICollectionReusableView {
@IBOutlet weak var userImageView: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var userTypeLabel: UILabel!
@IBOutlet weak var dealImpressionLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var dealCommentLabel: UILabel!
@IBOutlet weak var userPageButton: UIButton!
@IBOutlet weak var detailReviewOpenButton: UIButton!
@IBOutlet weak var heartCloseButton: UIButton!
var review: SLVRespReview?
var moveBlock: ((_ userId: String) -> Void)?
var openBlock: ((_ isOpen: Bool) -> Void)?
override public func awakeFromNib() {
super.awakeFromNib()
}
func setupData(review: SLVRespReview, isOpen: Bool) {
self.review = review
if let info = self.review {
let name = info.nickname ?? ""
let thumb = info.avatar ?? ""
let type = (info.kind == "buy") ? "구매자":"판매자"
let text = info.text ?? ""
let point = info.grade ?? 1 //2, 1, 0
var impression = "만족해요!"
switch point {
case 1:
impression = "괜찮아요!"
break
case 0:
impression = "별로에요!"
break
default:
break
}
let time = info.createdAt
var ago = ""
if let time = time {
ago = Date.timeAgoSince(time)
}
self.userNameLabel?.text = name
if thumb != "" {
let dnModel = SLVDnImageModel.shared
let url = URL(string: "\(dnAvatar)\(thumb)")
if let url = url {
dnModel.setupImageView(view: self.userImageView, from: url)
}
}
self.userTypeLabel.text = type
self.dealImpressionLabel.text = impression
self.dealCommentLabel.text = text
self.timeLabel.text = ago
if isOpen == true {
self.detailReviewOpenButton.isHidden = true
self.heartCloseButton.isHidden = false
} else {
self.detailReviewOpenButton.isHidden = false
self.heartCloseButton.isHidden = true
}
}
}
func setupMove(block: @escaping ((_ userId:String) -> Void)) {
self.moveBlock = block
}
func setupOpen(block: @escaping ((_ isOpen:Bool) -> Void)) {
self.openBlock = block
}
//MARK: Event
@IBAction func touchUserPage(_ sender: Any) {
//UserPage 이동
if let info = self.review {
var userId = ""
if info.kind == "buy" {
userId = (info.sellerId ?? "").copy() as! String
} else {
userId = (info.buyerId ?? "").copy() as! String
}
if userId != "" && self.moveBlock != nil {
self.moveBlock!(userId)
}
}
}
@IBAction func touchDetailReviewOpen(_ sender: Any) {
//후기 상세 열기
if self.openBlock != nil {
self.detailReviewOpenButton.isHidden = true
self.heartCloseButton.isHidden = false
self.openBlock!(true)
}
}
@IBAction func touchHeartCloseOpen(_ sender: Any) {
//후기 상세 닫기
if self.openBlock != nil {
self.detailReviewOpenButton.isHidden = false
self.heartCloseButton.isHidden = true
self.openBlock!(false)
}
}
}
| mit | 3fb78b04d6ab967e96b2d04949afa5e3 | 29.34127 | 79 | 0.520795 | 4.69656 | false | false | false | false |
stripe/stripe-ios | StripeIdentity/StripeIdentity/Source/NativeComponents/ViewControllers/BiometricConsentViewController.swift | 1 | 6868 | //
// BiometricConsentViewController.swift
// StripeIdentity
//
// Created by Mel Ludowise on 10/29/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
@_spi(STP) import StripeCore
@_spi(STP) import StripeUICore
import UIKit
@available(iOSApplicationExtension, unavailable)
final class BiometricConsentViewController: IdentityFlowViewController {
private let htmlView = HTMLViewWithIconLabels()
let brandLogo: UIImage
let consentContent: StripeAPI.VerificationPageStaticContentConsentPage
private var consentSelection: Bool?
private var isSaving = false {
didSet {
updateUI()
}
}
var scrolledToBottom = false {
didSet {
updateUI()
}
}
private var scrolledToBottomYOffset: CGFloat? = nil
var flowViewModel: IdentityFlowView.ViewModel {
// Display loading indicator on user's selection while saving
let acceptButtonState: IdentityFlowView.ViewModel.Button.State
let declineButtonState: IdentityFlowView.ViewModel.Button.State
switch (isSaving, consentSelection) {
case (true, true):
acceptButtonState = .loading
declineButtonState = .disabled
case (true, false):
acceptButtonState = .disabled
declineButtonState = .loading
default:
acceptButtonState = .enabled
declineButtonState = .enabled
}
var buttons: [IdentityFlowView.ViewModel.Button] = []
if scrolledToBottom {
buttons.append(
.init(
text: consentContent.acceptButtonText,
state: acceptButtonState,
didTap: { [weak self] in
self?.didTapButton(consentValue: true)
}
)
)
} else {
buttons.append(
.init(
text: consentContent.scrollToContinueButtonText,
state: .disabled,
didTap: {}
)
)
}
buttons.append(
.init(
text: consentContent.declineButtonText,
state: declineButtonState,
didTap: { [weak self] in
self?.didTapButton(consentValue: false)
}
)
)
return .init(
headerViewModel: .init(
backgroundColor: .systemBackground,
headerType: .banner(
iconViewModel: .init(
iconType: .brand,
iconImage: brandLogo,
iconImageContentMode: .scaleToFill
)
),
titleText: consentContent.title
),
contentViewModel: .init(
view: htmlView,
inset: .init(top: 16, leading: 16, bottom: 8, trailing: 16)
),
buttons: buttons,
scrollViewDelegate: self,
flowViewDelegate: self
)
}
init(
brandLogo: UIImage,
consentContent: StripeAPI.VerificationPageStaticContentConsentPage,
sheetController: VerificationSheetControllerProtocol
) throws {
self.brandLogo = brandLogo
self.consentContent = consentContent
super.init(sheetController: sheetController, analyticsScreenName: .biometricConsent)
// If HTML fails to render, throw error since it's unacceptable to not
// display consent copy
try htmlView.configure(
with: .init(
iconText: [
.init(
image: Image.iconClock.makeImage().withTintColor(IdentityUI.iconColor),
text: consentContent.timeEstimate,
isTextHTML: false
)
],
nonIconText: [
.init(
text: consentContent.privacyPolicy,
isTextHTML: true
)
],
bodyHtmlString: consentContent.body,
didOpenURL: { [weak self] url in
self?.openInSafariViewController(url: url)
}
)
)
updateUI()
}
required init?(
coder: NSCoder
) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Private Helpers
@available(iOSApplicationExtension, unavailable)
extension BiometricConsentViewController {
fileprivate func updateUI() {
configure(
backButtonTitle: STPLocalizedString(
"Consent",
"Back button title for returning to consent screen of Identity verification"
),
viewModel: flowViewModel
)
}
fileprivate func didTapButton(consentValue: Bool) {
consentSelection = consentValue
isSaving = true
sheetController?.saveAndTransition(
from: analyticsScreenName,
collectedData: .init(
biometricConsent: consentValue
)
) { [weak self] in
self?.isSaving = false
}
}
}
// MARK: - IdentityDataCollecting
@available(iOSApplicationExtension, unavailable)
extension BiometricConsentViewController: IdentityDataCollecting {
var collectedFields: Set<StripeAPI.VerificationPageFieldType> {
return [.biometricConsent]
}
}
// MARK: - UIScrollViewDelegate
@available(iOS 13, *)
@available(iOSApplicationExtension, unavailable)
extension BiometricConsentViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if let scrolledToBottomYOffset = scrolledToBottomYOffset,
scrollView.contentOffset.y > scrolledToBottomYOffset
{
scrolledToBottom = true
}
}
}
// MARK: - IdentityFlowViewDelegate
@available(iOS 13, *)
@available(iOSApplicationExtension, unavailable)
extension BiometricConsentViewController: IdentityFlowViewDelegate {
func scrollViewFullyLaiedOut(_ scrollView: UIScrollView) {
guard scrolledToBottomYOffset == nil else {
return
}
let initialContentYOffset = scrollView.contentOffset.y
let contentSizeHeight = scrollView.contentSize.height
let visibleContentHeight =
scrollView.frame.size.height + initialContentYOffset - scrollView.contentInset.bottom
let nonVisibleContentHeight = contentSizeHeight - visibleContentHeight
scrolledToBottomYOffset = initialContentYOffset + nonVisibleContentHeight
// all content is visible, not scrollable
if visibleContentHeight > contentSizeHeight {
scrolledToBottom = true
}
}
}
| mit | bd8008bbdea1d190313f2c329b57b1a3 | 29.932432 | 97 | 0.583224 | 5.971304 | false | false | false | false |
starhoshi/BBMobilePointLogin | BBMobilePointLogin/BBMobilePoint.swift | 1 | 1688 | //
// BBMobilePoint.swift
// BBMobilePointLogin
//
// Created by Kensuke Hoshikawa on 2015/04/26.
// Copyright (c) 2015年 star__hoshi. All rights reserved.
//
import Foundation
import UIKit
class BBMobilePoint{
let bbLoginWebView:UIWebView!
let html:String!
/**
:param: BBMobilePointHtml <#BBMobilePointHtml description#>
:returns: <#return value description#>
*/
init(BBMobilePointWebView:UIWebView){
bbLoginWebView = BBMobilePointWebView
let js = "document.body.innerHTML"
html = bbLoginWebView.stringByEvaluatingJavaScriptFromString(js)
}
/**
:param: html <#html description#>
*/
func setParametor(){
}
func login() -> Bool{
var err : NSError?
let option = CInt(HTML_PARSE_NOERROR.value | HTML_PARSE_RECOVER.value)
let parser = HTMLParser(html: html, encoding: NSUTF8StringEncoding, option: option, error: &err)
if err != nil {
println(err)
exit(1)
}
let bodyNode = parser.body
var applicationDetail = [String:Any]()
var application:[[String:Any]] = []
if let path = bodyNode?.xpath("//div[@class='stream-item oauth-application ']") {
for node in path {
// iOSアプリの許可を取り消す方法はこちら
if (node.findChildTagAttr("a", attrName: "class", attrValue: "revoke ios-revoke-access") != nil){
continue
}
applicationDetail = getApplicationData(node)
application.append(applicationDetail)
}
}
return true
}
} | mit | f2815269e9d4801307e8958161fccf18 | 23.671642 | 113 | 0.585351 | 4.405333 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/SwifterSwift/Source/Extensions/DoubleExtensions.swift | 1 | 4410 | //
// DoubleExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/6/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
// MARK: - Properties
public extension Double {
/// SwifterSwift: Absolute of double value.
public var abs: Double {
return Swift.abs(self)
}
/// SwifterSwift: String with number and current locale currency.
public var asLocaleCurrency: String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale.current
return formatter.string(from: self as NSNumber)!
}
/// SwifterSwift: Ceil of double value.
public var ceil: Double {
return Foundation.ceil(self)
}
/// SwifterSwift: Radian value of degree input.
public var degreesToRadians: Double {
return Double.pi * self / 180.0
}
/// SwifterSwift: Floor of double value.
public var floor: Double {
return Foundation.floor(self)
}
/// SwifterSwift: Check if double is positive.
public var isPositive: Bool {
return self > 0
}
/// SwifterSwift: Check if double is negative.
public var isNegative: Bool {
return self < 0
}
/// SwifterSwift: Int.
public var int: Int {
return Int(self)
}
/// SwifterSwift: Float.
public var float: Float {
return Float(self)
}
/// SwifterSwift: CGFloat.
public var cgFloat: CGFloat {
return CGFloat(self)
}
/// SwifterSwift: String.
public var string: String {
return String(self)
}
/// SwifterSwift: Degree value of radian input.
public var radiansToDegrees: Double {
return self * 180 / Double.pi
}
}
// MARK: - Methods
extension Double {
/// SwifterSwift: Random double between two double values.
///
/// - Parameters:
/// - min: minimum number to start random from.
/// - max: maximum number random number end before.
/// - Returns: random double between two double values.
public static func random(between min: Double, and max: Double) -> Double {
return random(inRange: min...max)
}
/// SwifterSwift: Random double in a closed interval range.
///
/// - Parameter range: closed interval range.
/// - Returns: random double in the given closed range.
public static func random(inRange range: ClosedRange<Double>) -> Double {
let delta = range.upperBound - range.lowerBound
return Double(arc4random()) / Double(UInt64(UINT32_MAX)) * delta + range.lowerBound
}
}
// MARK: - Initializers
public extension Double {
/// SwifterSwift: Created a random double between two double values.
///
/// - Parameters:
/// - min: minimum number to start random from.
/// - max: maximum number random number end before.
public init(randomBetween min: Double, and max: Double) {
self = Double.random(between: min, and: max)
}
/// SwifterSwift: Create a random double in a closed interval range.
///
/// - Parameter range: closed interval range.
public init(randomInRange range: ClosedRange<Double>) {
self = Double.random(inRange: range)
}
}
// MARK: - Operators
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ** : PowerPrecedence
/// SwifterSwift: Value of exponentiation.
///
/// - Parameters:
/// - lhs: base double.
/// - rhs: exponent double.
/// - Returns: exponentiation result (example: 4.4 ** 0.5 = 2.0976176963).
public func ** (lhs: Double, rhs: Double) -> Double {
// http://nshipster.com/swift-operators/
return pow(lhs, rhs)
}
prefix operator √
/// SwifterSwift: Square root of double.
///
/// - Parameter double: double value to find square root for.
/// - Returns: square root of given double.
public prefix func √ (double: Double) -> Double {
// http://nshipster.com/swift-operators/
return sqrt(double)
}
infix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameters:
/// - lhs: double number.
/// - rhs: double number.
/// - Returns: tuple of plus-minus operation (example: 2.5 ± 1.5 -> (4, 1)).
public func ± (lhs: Double, rhs: Double) -> (Double, Double) {
// http://nshipster.com/swift-operators/
return (lhs + rhs, lhs - rhs)
}
prefix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameter int: double number
/// - Returns: tuple of plus-minus operation (example: ± 2.5 -> (2.5, -2.5)).
public prefix func ± (double: Double) -> (Double, Double) {
// http://nshipster.com/swift-operators/
return 0 ± double
}
| mit | a9ee3f90a7a4c8c6bffcb126644864bc | 23.847458 | 85 | 0.683265 | 3.590204 | false | false | false | false |
CosmicMind/Samples | Projects/Programmatic/Grid/Grid/ViewController.swift | 1 | 2690 | /*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* 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 CosmicMind 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
import Material
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
prepareHorizontalExample()
prepareVerticalExample()
}
}
extension ViewController {
fileprivate func prepareHorizontalExample() {
let container = View()
container.backgroundColor = nil
container.shapePreset = .square
container.grid.interimSpacePreset = .interimSpace3
view.layout(container).center().left(20).right(20).height(300)
for _ in 0..<12 {
let v = View()
v.grid.columns = 1
v.backgroundColor = Color.blue.base
container.grid.views.append(v)
}
}
fileprivate func prepareVerticalExample() {
let container = View()
container.backgroundColor = nil
container.shapePreset = .square
container.grid.axis.direction = .vertical
container.grid.interimSpacePreset = .interimSpace3
view.layout(container).center().left(20).right(20).height(300)
for _ in 0..<12 {
let v = View()
v.grid.rows = 1
v.backgroundColor = Color.blue.base
container.grid.views.append(v)
}
}
}
| bsd-3-clause | 8f2f6da2b048e9093959759df7bf61ce | 32.625 | 87 | 0.752045 | 4.069592 | false | false | false | false |
CatchChat/Yep | YepKit/Extensions/NSFileManager+Yep.swift | 1 | 7410 | //
// NSFileManager+Yep.swift
// Yep
//
// Created by NIX on 15/3/31.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
public enum FileExtension: String {
case JPEG = "jpg"
case MP4 = "mp4"
case M4A = "m4a"
public var mimeType: String {
switch self {
case .JPEG:
return "image/jpeg"
case .MP4:
return "video/mp4"
case .M4A:
return "audio/m4a"
}
}
}
public extension NSFileManager {
public class func yepCachesURL() -> NSURL {
return try! NSFileManager.defaultManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
}
// MARK: Avatar
public class func yepAvatarCachesURL() -> NSURL? {
let fileManager = NSFileManager.defaultManager()
let avatarCachesURL = yepCachesURL().URLByAppendingPathComponent("avatar_caches", isDirectory: true)
do {
try fileManager.createDirectoryAtURL(avatarCachesURL, withIntermediateDirectories: true, attributes: nil)
return avatarCachesURL
} catch let error {
println("Directory create: \(error)")
}
return nil
}
public class func yepAvatarURLWithName(name: String) -> NSURL? {
if let avatarCachesURL = yepAvatarCachesURL() {
return avatarCachesURL.URLByAppendingPathComponent("\(name).\(FileExtension.JPEG.rawValue)")
}
return nil
}
public class func saveAvatarImage(avatarImage: UIImage, withName name: String) -> NSURL? {
if let avatarURL = yepAvatarURLWithName(name) {
let imageData = UIImageJPEGRepresentation(avatarImage, 0.8)
if NSFileManager.defaultManager().createFileAtPath(avatarURL.path!, contents: imageData, attributes: nil) {
return avatarURL
}
}
return nil
}
public class func deleteAvatarImageWithName(name: String) {
if let avatarURL = yepAvatarURLWithName(name) {
do {
try NSFileManager.defaultManager().removeItemAtURL(avatarURL)
} catch let error {
println("File delete: \(error)")
}
}
}
// MARK: Message
public class func yepMessageCachesURL() -> NSURL? {
let fileManager = NSFileManager.defaultManager()
let messageCachesURL = yepCachesURL().URLByAppendingPathComponent("message_caches", isDirectory: true)
do {
try fileManager.createDirectoryAtURL(messageCachesURL, withIntermediateDirectories: true, attributes: nil)
return messageCachesURL
} catch let error {
println("Directory create: \(error)")
}
return nil
}
// Image
public class func yepMessageImageURLWithName(name: String) -> NSURL? {
if let messageCachesURL = yepMessageCachesURL() {
return messageCachesURL.URLByAppendingPathComponent("\(name).\(FileExtension.JPEG.rawValue)")
}
return nil
}
public class func saveMessageImageData(messageImageData: NSData, withName name: String) -> NSURL? {
if let messageImageURL = yepMessageImageURLWithName(name) {
if NSFileManager.defaultManager().createFileAtPath(messageImageURL.path!, contents: messageImageData, attributes: nil) {
return messageImageURL
}
}
return nil
}
public class func removeMessageImageFileWithName(name: String) {
if name.isEmpty {
return
}
if let messageImageURL = yepMessageImageURLWithName(name) {
do {
try NSFileManager.defaultManager().removeItemAtURL(messageImageURL)
} catch let error {
println("File delete: \(error)")
}
}
}
// Audio
public class func yepMessageAudioURLWithName(name: String) -> NSURL? {
if let messageCachesURL = yepMessageCachesURL() {
return messageCachesURL.URLByAppendingPathComponent("\(name).\(FileExtension.M4A.rawValue)")
}
return nil
}
public class func saveMessageAudioData(messageAudioData: NSData, withName name: String) -> NSURL? {
if let messageAudioURL = yepMessageAudioURLWithName(name) {
if NSFileManager.defaultManager().createFileAtPath(messageAudioURL.path!, contents: messageAudioData, attributes: nil) {
return messageAudioURL
}
}
return nil
}
public class func removeMessageAudioFileWithName(name: String) {
if name.isEmpty {
return
}
if let messageAudioURL = yepMessageAudioURLWithName(name) {
do {
try NSFileManager.defaultManager().removeItemAtURL(messageAudioURL)
} catch let error {
println("File delete: \(error)")
}
}
}
// Video
public class func yepMessageVideoURLWithName(name: String) -> NSURL? {
if let messageCachesURL = yepMessageCachesURL() {
return messageCachesURL.URLByAppendingPathComponent("\(name).\(FileExtension.MP4.rawValue)")
}
return nil
}
public class func saveMessageVideoData(messageVideoData: NSData, withName name: String) -> NSURL? {
if let messageVideoURL = yepMessageVideoURLWithName(name) {
if NSFileManager.defaultManager().createFileAtPath(messageVideoURL.path!, contents: messageVideoData, attributes: nil) {
return messageVideoURL
}
}
return nil
}
public class func removeMessageVideoFilesWithName(name: String, thumbnailName: String) {
if !name.isEmpty {
if let messageVideoURL = yepMessageVideoURLWithName(name) {
do {
try NSFileManager.defaultManager().removeItemAtURL(messageVideoURL)
} catch let error {
println("File delete: \(error)")
}
}
}
if !thumbnailName.isEmpty {
if let messageImageURL = yepMessageImageURLWithName(thumbnailName) {
do {
try NSFileManager.defaultManager().removeItemAtURL(messageImageURL)
} catch let error {
println("File delete: \(error)")
}
}
}
}
// MARK: Clean Caches
public class func cleanCachesDirectoryAtURL(cachesDirectoryURL: NSURL) {
let fileManager = NSFileManager.defaultManager()
if let fileURLs = (try? fileManager.contentsOfDirectoryAtURL(cachesDirectoryURL, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())) {
for fileURL in fileURLs {
do {
try fileManager.removeItemAtURL(fileURL)
} catch let error {
println("File delete: \(error)")
}
}
}
}
public class func cleanAvatarCaches() {
if let avatarCachesURL = yepAvatarCachesURL() {
cleanCachesDirectoryAtURL(avatarCachesURL)
}
}
public class func cleanMessageCaches() {
if let messageCachesURL = yepMessageCachesURL() {
cleanCachesDirectoryAtURL(messageCachesURL)
}
}
}
| mit | 38911c82cdafd942063b77ec5f2ebcd1 | 28.870968 | 166 | 0.608396 | 5.549064 | false | false | false | false |
shadanan/mado | Antlr4Runtime/Sources/Antlr4/atn/LexerChannelAction.swift | 1 | 2188 | /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
/// Implements the {@code channel} lexer action by calling
/// {@link org.antlr.v4.runtime.Lexer#setChannel} with the assigned channel.
///
/// - Sam Harwell
/// - 4.2
public final class LexerChannelAction: LexerAction, CustomStringConvertible {
fileprivate let channel: Int
/// Constructs a new {@code channel} action with the specified channel value.
/// - parameter channel: The channel value to pass to {@link org.antlr.v4.runtime.Lexer#setChannel}.
public init(_ channel: Int) {
self.channel = channel
}
/// Gets the channel to use for the {@link org.antlr.v4.runtime.Token} created by the lexer.
///
/// - returns: The channel to use for the {@link org.antlr.v4.runtime.Token} created by the lexer.
public func getChannel() -> Int {
return channel
}
/// {@inheritDoc}
/// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#CHANNEL}.
public override func getActionType() -> LexerActionType {
return LexerActionType.channel
}
/// {@inheritDoc}
/// - returns: This method returns {@code false}.
public override func isPositionDependent() -> Bool {
return false
}
/// {@inheritDoc}
///
/// <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#setChannel} with the
/// value provided by {@link #getChannel}.</p>
public override func execute(_ lexer: Lexer) {
lexer.setChannel(channel)
}
override
public var hashValue: Int {
var hash: Int = MurmurHash.initialize()
hash = MurmurHash.update(hash, getActionType().rawValue)
hash = MurmurHash.update(hash, channel)
return MurmurHash.finish(hash, 2)
}
public var description: String {
return "channel\(channel)"
}
}
public func ==(lhs: LexerChannelAction, rhs: LexerChannelAction) -> Bool {
if lhs === rhs {
return true
}
return lhs.channel == rhs.channel
}
| mit | 3baa96b30bd91888f51baa772e848b91 | 28.173333 | 104 | 0.652194 | 4.207692 | false | false | false | false |
nkirby/Humber | _lib/HMGithub/_src/Sync/SyncController+Account.swift | 1 | 1293 | // =======================================================
// HMGithub
// Nathaniel Kirby
// =======================================================
import Foundation
import ReactiveCocoa
import Result
import HMCore
// =======================================================
public protocol GithubAccountSyncProviding {
func syncCurrentGithubAccount() -> SignalProducer<Void, SyncError>
}
extension SyncController: GithubAccountSyncProviding {
public func syncCurrentGithubAccount() -> SignalProducer<Void, SyncError> {
guard let api = ServiceController.component(GithubAPIAccountResponseProviding.self),
let data = ServiceController.component(GithubAccountDataProviding.self) else {
return SignalProducer.empty
}
return api.getUserInfo()
.observeOn(CoreScheduler.background())
.mapError { _ in return SyncError.Unknown }
.flatMap(.Latest, transform: { response -> SignalProducer<Void, SyncError> in
return SignalProducer { observer, _ in
data.saveCurrentUser(accountResponse: response, write: true)
observer.sendNext()
observer.sendCompleted()
}
})
}
}
| mit | 227d49858333a9c0c5d1b8a7fc6e6fe4 | 33.945946 | 92 | 0.551431 | 6.127962 | false | false | false | false |
sviatoslav/EndpointProcedure | Sources/Core/EndpointProcedure.swift | 1 | 6828 | //
// EndpointProcedure.swift
// EndpointProcedure
//
// Created by Sviatoslav Yakymiv on 12/26/16.
// Copyright © 2016 Sviatoslav Yakymiv. All rights reserved.
//
import Foundation
#if canImport(ProcedureKit)
import ProcedureKit
#endif
/// Errors that `EndpointProcedure` can return in `output` property.
public enum EndpointProcedureError: Error {
case missingDataLoadingProcedure
case missingMappingProcedure
fileprivate enum Internal: Error {
case unimplementedDataLoadingProcedure
}
}
/// `EndpointProcedure` wraps `DataFlowProcedure` and is aimed for easy creation connections with endpoints.
///
/// Examples
/// --------
/// Creating simplest `EndpointProcedure`:
///
/// let requestData = HTTPRequestData.Builder.for(path: "users").build()
/// let usersProcedure = EndpointProcedure<[User]>(requestData: requestData)
///
/// Using `validationProcedure`:
///
/// let validation = TransformProcedure<HTTPResponseData, Void> {
/// if $0.urlResponse?.statusCode >= 400 {
/// throw Error.invalidStatusCode
/// }
/// }
/// let requestData = HTTPRequestData.Builder.for(path: "users").build()
/// let usersProcedure = EndpointProcedure<[User]>(requestData: requestData, validationProcedure: validation)
///
/// Using `interceptionProcedure`:
///
/// let interception = TransformProcedure<Any, Any> {
/// guard let dataDictionary = $0 as? [AnyHashable: Any] else {
/// throw Error.invalidResponseFormat
/// }
/// guard let usersArray = dataDictionary["data"] as? [Any] else {
/// throw Error.invalidResponseFormat
/// }
/// return usersArray
/// }
/// let requestData = HTTPRequestData.Builder.for(path: "users").build()
/// let usersProcedure = EndpointProcedure<[User]>(requestData: requestData, interceptionProcedure: interception)
///
/// Using custom `configuration`:
///
/// let configuration = //initialize with appropriate procedure factories
/// let requestData = HTTPRequestData.Builder.for(path: "users").build()
/// let usersProcedure = EndpointProcedure<[User]>(requestData: requestData, configuration: configuration)
///
/// Using custom `dataLoadingProcedure`:
///
/// let url = //Any URL
/// let dataLoadingProcedure = ContentsOfURLLoadingProcedure(url: url)
/// let usersProcedure = EndpointProcedure<[User]>(dataLoadingProcedure: dataLoadingProcedure)
///
open class EndpointProcedure<Result>: GroupProcedure, OutputProcedure, EndpointProcedureComponentsProviding {
/// Result of `EndpointProcedure`.
public var output: Pending<ProcedureResult<Result>> = .pending
private var configurationStorage: AnyEndpointProcedureComponentsProvider<Result>? = nil
public var configuration: AnyEndpointProcedureComponentsProvider<Result> {
get {
if let storage = self.configurationStorage { return storage }
do {
guard let container = (self as? ConfigurationProviderContaining & HTTPRequestDataContaining) else {
throw EndpointProcedureError.missingDataLoadingProcedure
}
return try container.configurationProvider.configuration(forRequestData: container.requestData(),
responseType: Result.self)
} catch let error {
return DefaultConfiguration(requestProcedureError: error).wrapped
}
}
set {
self.configurationStorage = newValue
}
}
public init() {
super.init(operations: [])
}
open func dataLoadingProcedure() throws -> AnyOutputProcedure<Data> {
throw EndpointProcedureError.Internal.unimplementedDataLoadingProcedure
}
open func requestProcedure() throws -> AnyOutputProcedure<HTTPResponseData> {
return try self.configuration.requestProcedure()
}
open func validationProcedure() -> AnyInputProcedure<HTTPResponseData> {
return self.configuration.validationProcedure()
}
open func deserializationProcedure() -> AnyProcedure<Data, Any> {
return self.configuration.deserializationProcedure()
}
open func interceptionProcedure() -> AnyProcedure<Any, Any> {
return self.configuration.interceptionProcedure()
}
open func responseMappingProcedure() throws -> AnyProcedure<Any, Result> {
return try self.configuration.responseMappingProcedure()
}
open func dataFlowProcedure() throws -> DataFlowProcedure<Result> {
let dataLoading: AnyOutputProcedure<Data>?
do {
dataLoading = try self.dataLoadingProcedure()
} catch EndpointProcedureError.Internal.unimplementedDataLoadingProcedure {
dataLoading = nil
}
return try dataLoading.map({
DataFlowProcedure(dataLoadingProcedure: $0,
deserializationProcedure: self.deserializationProcedure(),
interceptionProcedure: self.interceptionProcedure(),
resultMappingProcedure: try self.responseMappingProcedure())
}) ?? HTTPDataFlowProcedure(dataLoadingProcedure: self.requestProcedure(),
validationProcedure: self.validationProcedure(),
deserializationProcedure: self.deserializationProcedure(),
interceptionProcedure: self.interceptionProcedure(),
resultMappingProcedure: try self.responseMappingProcedure())
}
open override func execute() {
do {
let procedure = try self.dataFlowProcedure()
procedure.addDidFinishBlockObserver { [weak self] (procedure, _) in
self?.output = procedure.output
}
self.addChild(procedure)
} catch let error {
self.output = .ready(.failure(error))
}
super.execute()
}
}
private struct DefaultConfiguration<Response>: EndpointProcedureComponentsProviding {
private let requestProcedureError: Error
init(requestProcedureError: Error = EndpointProcedureError.missingDataLoadingProcedure) {
self.requestProcedureError = requestProcedureError
}
func requestProcedure() throws -> AnyOutputProcedure<HTTPResponseData> {
throw self.requestProcedureError
}
func responseMappingProcedure() throws -> AnyProcedure<Any, Response> {
throw EndpointProcedureError.missingMappingProcedure
}
}
protocol ConfigurationProviderContaining {
var configurationProvider: EndpointProcedureConfigurationProviding { get }
}
protocol HTTPRequestDataContaining {
func requestData() throws -> HTTPRequestData
}
| mit | 482d7ee17a7e8c4c54aac3548807ed59 | 40.883436 | 117 | 0.668522 | 5.820119 | false | true | false | false |
aijaz/icw1502 | playgrounds/Week05.playground/Pages/Intro.xcplaygroundpage/Contents.swift | 1 | 939 | //: Playground - noun: a place where people can play
import UIKit
enum Color {
case Red
case Green
case Blue
}
var crayon = Color.Red
crayon
crayon = Color.Green
crayon = .Green
if (crayon == .Green) {
print("It's green")
}
else if (crayon == .Red) {
print("It's red")
}
else if (crayon == .Blue) {
print("It's blue")
}
func actualColorIf(color: Color) -> UIColor {
if (crayon == .Green) {
return UIColor.greenColor()
}
else if (crayon == .Red) {
return UIColor.redColor()
}
else if (crayon == .Blue) {
return UIColor.blueColor()
}
return UIColor.blackColor()
}
func actualColor(color: Color) -> UIColor {
switch color {
case .Red:
return UIColor.redColor()
case .Green:
return UIColor.greenColor()
case .Blue:
return UIColor.blueColor()
}
}
let newCrayon = Color.Green
actualColor(newCrayon)
| mit | 9427b23900ca49711d1c0c9d9e4b6979 | 12.414286 | 52 | 0.589989 | 3.653696 | false | false | false | false |
ConradoMateu/GOT-Challenge-Swift | GOT-Challenge-Swift/Extensions/UIColor.swift | 1 | 3156 | //
// UIColor.swift
// GOT-Challenge-Swift
//
// Created by Conrado Mateu Gisbert on 12/03/17.
// Copyright © 2017 conradomateu. All rights reserved.
//
import Foundation
import Foundation
import UIKit
extension UIColor {
convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = rgba.index(rgba.startIndex, offsetBy: 1)
let hex = rgba.substring(from: index)
let scanner = Scanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexInt64(&hexValue) {
switch hex.count {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string")
}
} else {
print("Scan hex error")
}
} else {
print("Invalid RGB string, missing '#' as prefix", terminator: "")
}
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
static var windowBackgroundColor: UIColor {
return UIColor(rgba: "#0F0F0F0F")
}
static var loadingColor: UIColor {
return UIColor(rgba: "#4D5B69FF")
}
static var tabBarColor: UIColor {
return UIColor(rgba: "#4D5B69FF")
}
static var imageViewBackgroundColor: UIColor {
return UIColor(rgba: "#33333333")
}
static var tabBarTintColor: UIColor {
return UIColor(rgba: "#17D1FFFF")
}
static var navigationBarColor: UIColor {
return UIColor(rgba: "#33333333")
}
static var navigationBarTitleColor: UIColor {
return UIColor(rgba: "#F5F5F5FF")
}
static var gradientStartColor: UIColor {
return UIColor(rgba: "#2C343C00")
}
static var gradientEndColor: UIColor {
return UIColor(rgba: "#2C343CE5")
}
static var cellBackgroundColor: UIColor {
return UIColor(rgba: "#22282fFF")
}
}
| apache-2.0 | a167db37adc1e46bc1fc87d78832423f | 30.868687 | 78 | 0.513154 | 4.065722 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.