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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
shopgun/shopgun-ios-sdk | Sources/TjekAPI/Utils/UIColor+Hex.swift | 1 | 1947 | ///
/// Copyright (c) 2018 Tjek. All rights reserved.
///
#if canImport(UIKit)
import UIKit
extension UIColor {
convenience init?(hex: String) {
var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines)
hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "")
var rgb: UInt64 = 0
guard Scanner(string: hexSanitized).scanHexInt64(&rgb) else { return nil }
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 1.0
let strLen = hexSanitized.count
if strLen == 6 {
r = CGFloat((rgb & 0xFF0000) >> 16) / 255.0
g = CGFloat((rgb & 0x00FF00) >> 8) / 255.0
b = CGFloat(rgb & 0x0000FF) / 255.0
} else if strLen == 8 {
r = CGFloat((rgb & 0xFF000000) >> 24) / 255.0
g = CGFloat((rgb & 0x00FF0000) >> 16) / 255.0
b = CGFloat((rgb & 0x0000FF00) >> 8) / 255.0
a = CGFloat(rgb & 0x000000FF) / 255.0
} else {
return nil
}
self.init(red: r, green: g, blue: b, alpha: a)
}
var toHex: String? {
return toHex()
}
func toHex(alpha: Bool = false) -> String? {
guard let components = cgColor.components, components.count >= 3 else {
return nil
}
let r = Float(components[0])
let g = Float(components[1])
let b = Float(components[2])
var a = Float(1.0)
if components.count >= 4 {
a = Float(components[3])
}
if alpha {
return String(format: "%02lX%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255), lroundf(a * 255))
} else {
return String(format: "%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255))
}
}
}
#endif
| mit | b5c6777d8023084f9e2fff8108da5703 | 28.059701 | 129 | 0.504879 | 3.780583 | false | false | false | false |
superbderrick/SummerSlider | SummerSliderDemo/HorizontalViewController.swift | 1 | 2840 | //
// HorizontalViewController.swift
// SummerSlider
//
// Created by Kang Jinyeoung on 24/09/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import SummerSlider
class HorizontalViewController: UIViewController {
var testSlider1:SummerSlider!
var testSlider2:SummerSlider!
var testSlider3:SummerSlider!
let testRect1 = CGRect(x:30 ,y:70 , width:300 , height:30)
let testRect2 = CGRect(x:30 ,y:120 , width:300 , height:30)
let testRect3 = CGRect(x:30 ,y:170 , width:300 , height:30)
@IBOutlet weak var testSlider4: SummerSlider!
@IBOutlet weak var testSlider5: SummerSlider!
@IBOutlet weak var testSlider6: SummerSlider!
override func viewDidLoad() {
super.viewDidLoad()
var marksArray1 = Array<Float>()
marksArray1 = [0,10,20,30,40,50,60,70,80,90,100]
testSlider1 = SummerSlider(frame: testRect1)
testSlider1.selectedBarColor = UIColor.blue
testSlider1.unselectedBarColor = UIColor.red
testSlider1.markColor = UIColor.yellow
testSlider1.markWidth = 2.0
testSlider1.markPositions = marksArray1
var marksArray2 = Array<Float>()
marksArray2 = [10.0,15.0,23.0,67.0,71.0]
testSlider2 = SummerSlider(frame: testRect2)
testSlider2.selectedBarColor = UIColor(red:138/255.0 ,green:255/255.0 ,blue:0/255 ,alpha:1.0)
testSlider2.unselectedBarColor = UIColor(red:108/255.0 ,green:200/255.0 ,blue:0/255.0 ,alpha:1.0)
testSlider2.markColor = UIColor.red
testSlider2.markWidth = 1.0
testSlider2.markPositions = marksArray2
testSlider3 = SummerSlider(frame: testRect3)
var marksArray3 = Array<Float>()
marksArray3 = [20.0,15.0,23.0,67.0, 90.0]
testSlider3 = SummerSlider(frame: testRect3)
testSlider3.selectedBarColor = UIColor.blue
testSlider3.unselectedBarColor = UIColor(red:20/255.0 ,green:40/255.0 ,blue:0/255.0 ,alpha:1.0)
testSlider3.markColor = UIColor.gray
testSlider3.markWidth = 10.0
testSlider3.markPositions = marksArray3
self.view.addSubview(testSlider1)
self.view.addSubview(testSlider2)
self.view.addSubview(testSlider3)
var marksArray4 = Array<Float>()
marksArray4 = [0.0,25.0,90.0]
testSlider4.markPositions = marksArray4
var marksArray5 = Array<Float>()
marksArray5 = [10.0,20.0,30.0,80,90.0]
testSlider5.markPositions = marksArray5
var marksArray6 = Array<Float>()
marksArray6 = [0,12,23,34,45,56,77,99]
testSlider6.selectedBarColor = UIColor.white
testSlider6.unselectedBarColor = UIColor.black
testSlider6.markColor = UIColor.orange
testSlider6.markWidth = 6.0
testSlider6.markPositions = marksArray6
}
}
| mit | b9e3f152bcb7fb927207ad7f934ccaf3 | 31.632184 | 103 | 0.673124 | 3.826146 | false | true | false | false |
ostatnicky/kancional-ios | Pods/BonMot/Sources/UIKit/Tracking+Adaptive.swift | 2 | 1579 | //
// Tracking+Adaptive.swift
// BonMot
//
// Created by Brian King on 10/2/16.
// Copyright © 2016 Raizlabs. All rights reserved.
//
#if os(OSX)
import AppKit
#else
import UIKit
#endif
extension Tracking: AdaptiveStyleTransformation {
func adapt(attributes theAttributes: StyleAttributes, to traitCollection: UITraitCollection) -> StyleAttributes? {
if case .adobe = self {
var attributes = theAttributes
let styledFont = theAttributes[.font] as? UIFont
attributes.update(possibleValue: kerning(for: styledFont), forKey: .kern)
return attributes
}
else {
return nil
}
}
}
extension Tracking: EmbeddedTransformation {
struct Value {
static let adobeTracking = "adobe-tracking"
}
static func from(dictionary dict: StyleAttributes) -> EmbeddedTransformation? {
if case let (Value.adobeTracking?, size?) = (dict[EmbeddedTransformationHelpers.Key.type] as? String, dict[EmbeddedTransformationHelpers.Key.size] as? CGFloat) {
return Tracking.adobe(size)
}
return nil
}
var asDictionary: StyleAttributes {
if case let .adobe(size) = self {
return [
EmbeddedTransformationHelpers.Key.type: Value.adobeTracking,
EmbeddedTransformationHelpers.Key.size: size,
]
}
else {
// We don't need to persist point tracking, as it does not depend on
// the font size.
return [:]
}
}
}
| mit | 1df911a5492ae5b1f8db8706b4e07915 | 26.206897 | 169 | 0.614702 | 4.573913 | false | false | false | false |
koher/EasyImagy | Sources/EasyImagy/Util.swift | 1 | 970 | internal func clamp<T: Comparable>(_ x: T, lower: T, upper: T) -> T {
return min(max(x, lower), upper)
}
extension Range {
internal func isSuperset(of other: Range<Bound>) -> Bool {
return lowerBound <= other.lowerBound && other.upperBound <= upperBound || other.isEmpty
}
}
internal func range<R: RangeExpression>(from range: R, relativeTo collection: Range<Int>) -> Range<Int> where R.Bound == Int {
let all = Int.min ..< Int.max
let boundedRange: Range<Int> = range.relative(to: all)
let lowerBound: Int
let upperBound: Int
if boundedRange.lowerBound == .min {
lowerBound = Swift.max(boundedRange.lowerBound, collection.lowerBound)
} else {
lowerBound = boundedRange.lowerBound
}
if boundedRange.upperBound == .max {
upperBound = Swift.min(collection.upperBound, boundedRange.upperBound)
} else {
upperBound = boundedRange.upperBound
}
return lowerBound..<upperBound
}
| mit | 87d2229c4bb281fda916d9259c50f466 | 34.925926 | 126 | 0.66701 | 4.217391 | false | false | false | false |
brentsimmons/Evergreen | Shared/Exporters/OPMLExporter.swift | 1 | 755 | //
// OPMLExporter.swift
// NetNewsWire
//
// Created by Brent Simmons on 12/22/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import Account
import RSCore
struct OPMLExporter {
static func OPMLString(with account: Account, title: String) -> String {
let escapedTitle = title.escapingSpecialXMLCharacters
let openingText =
"""
<?xml version="1.0" encoding="UTF-8"?>
<!-- OPML generated by NetNewsWire -->
<opml version="1.1">
<head>
<title>\(escapedTitle)</title>
</head>
<body>
"""
let middleText = account.OPMLString(indentLevel: 0)
let closingText =
"""
</body>
</opml>
"""
let opml = openingText + middleText + closingText
return opml
}
}
| mit | e0c222cedc7986967700b53998b17e51 | 17.390244 | 73 | 0.648541 | 3.307018 | false | false | false | false |
Mayfleet/SimpleChat | Frontend/iOS/SimpleChat/SimpleChat/Screens/ChatList/ChatCell.swift | 1 | 5340 | //
// Created by Maxim Pervushin on 05/03/16.
// Copyright (c) 2016 Maxim Pervushin. All rights reserved.
//
import UIKit
protocol ChatCellDelegate: class {
func chatCellDidDelete(cell: ChatCell)
func chatCellDidEdit(cell: ChatCell)
func chatCellDidToggleAutoconnect(cell: ChatCell)
}
class ChatCell: UITableViewCell {
static let defaultReuseIdentifier = "ChatCell"
@IBOutlet weak var serverNameLabel: UILabel?
@IBOutlet weak var serverNotificationsLabel: UILabel?
@IBOutlet weak var leadingConstraint: NSLayoutConstraint?
@IBOutlet weak var editorContainer: UIView?
@IBOutlet weak var autoconnectButton: UIButton?
@IBOutlet weak var editButton: UIButton?
@IBOutlet weak var deleteButton: UIButton?
@IBAction func autoconnectButtonAction(sender: AnyObject) {
delegate?.chatCellDidToggleAutoconnect(self)
}
@IBAction func editButtonAction(sender: AnyObject) {
delegate?.chatCellDidEdit(self)
}
@IBAction func deleteButtonAction(sender: AnyObject) {
delegate?.chatCellDidDelete(self)
}
@objc func swipeLeftAction(sender: AnyObject) {
if !editing {
setEditing(true, animated: true)
}
}
@objc func swipeRightAction(sender: AnyObject) {
if editing {
setEditing(false, animated: true)
}
}
weak var delegate: ChatCellDelegate?
var chat: Chat? {
didSet {
serverNameLabel?.text = chat?.name
var autoconnectTitle = NSLocalizedString("Autoconnect: Off", comment: "Autoconnect Button Title: Off")
var autoconnectBackgroundColor = UIColor.flatYellowColorDark()
if let chat = chat where chat.autoconnect {
autoconnectTitle = NSLocalizedString("Autoconnect: On", comment: "Autoconnect Button Title: On")
autoconnectBackgroundColor = UIColor.flatGreenColorDark()
}
autoconnectButton?.setTitle(autoconnectTitle, forState: .Normal)
autoconnectButton?.backgroundColor = autoconnectBackgroundColor
subscribe()
}
}
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
if let
leadingConstraint = leadingConstraint,
editorContainer = editorContainer {
layoutIfNeeded()
leadingConstraint.constant = editing ? -editorContainer.frame.size.width : 4
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: [.CurveEaseInOut], animations: {
() -> Void in
self.layoutIfNeeded()
}, completion: nil)
}
}
private func subscribe() {
unsubscribe()
if let chat = chat {
let center = NSNotificationCenter.defaultCenter()
center.addObserverForName(Chat.statusChangedNotification, object: chat, queue: nil, usingBlock: chatStatusChangedNotification)
center.addObserverForName(Chat.messagesChangedNotification, object: chat, queue: nil, usingBlock: chatMessagesChangedNotification)
}
updateUI()
}
private func unsubscribe() {
let center = NSNotificationCenter.defaultCenter()
center.removeObserver(self, name: Chat.statusChangedNotification, object: nil)
center.removeObserver(self, name: Chat.messagesChangedNotification, object: nil)
}
private func updateUI() {
guard let chat = chat else {
serverNotificationsLabel?.hidden = true
return
}
serverNotificationsLabel?.hidden = false
serverNotificationsLabel?.text = chat.messages.count > 0 ? "\(chat.messages.count)" : ""
switch chat.status {
case Chat.Status.Online:
serverNotificationsLabel?.backgroundColor = UIColor.flatGreenColorDark()
break
case Chat.Status.Offline:
serverNotificationsLabel?.backgroundColor = UIColor.flatRedColorDark()
break
}
editButton?.backgroundColor = UIColor.flatSkyBlueColorDark()
deleteButton?.backgroundColor = UIColor.flatRedColorDark()
}
private func commonInit() {
let leftSwipeRecognizer = UISwipeGestureRecognizer(target: self, action: "swipeLeftAction:")
leftSwipeRecognizer.numberOfTouchesRequired = 1
leftSwipeRecognizer.direction = .Left
addGestureRecognizer(leftSwipeRecognizer)
let rightSwipeRecognizer = UISwipeGestureRecognizer(target: self, action: "swipeRightAction:")
rightSwipeRecognizer.numberOfTouchesRequired = 1
rightSwipeRecognizer.direction = .Right
addGestureRecognizer(rightSwipeRecognizer)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
deinit {
unsubscribe()
}
}
extension ChatCell {
private func chatStatusChangedNotification(notification: NSNotification) {
updateUI()
}
private func chatMessagesChangedNotification(notification: NSNotification) {
updateUI()
}
} | mit | 3848e93172fb215b20eef71788caebb7 | 31.567073 | 150 | 0.670787 | 5.522234 | false | false | false | false |
remlostime/one | one/one/ViewControllers/FeedViewController.swift | 1 | 3464 | //
// FeedViewController.swift
// one
//
// Created by Kai Chen on 1/20/17.
// Copyright © 2017 Kai Chen. All rights reserved.
//
import UIKit
import Parse
class FeedViewController: UITableViewController {
var postUUIDs: [String?] = []
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "One"
loadPosts()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.titleTextAttributes =
[NSFontAttributeName: UIFont(name: "Vonique64-Bold", size: 26)!]
}
func loadPosts() {
let userid = PFUser.current()?.username
let query = PFQuery(className: Follow.modelName.rawValue)
query.whereKey(Follow.follower.rawValue, equalTo: userid!)
var following: [String?] = []
query.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
for object in objects! {
following.append(object[Follow.following.rawValue] as! String?)
}
let postQuery = PFQuery(className: Post.modelName.rawValue)
postQuery.whereKey(Post.username.rawValue, containedIn: following)
postQuery.order(byDescending: "createdAt")
postQuery.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
for object in objects! {
self.postUUIDs.append(object[Post.uuid.rawValue] as! String?)
}
self.tableView.reloadData()
}
}
}
override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return false
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postUUIDs.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Identifier.postHeaderViewCell.rawValue, for: indexPath) as? PostHeaderViewCell
cell?.delegate = self
let uuid = postUUIDs[indexPath.row]
cell?.config(uuid!)
return cell!
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 600
}
}
extension FeedViewController: PostHeaderViewCellDelegate {
func navigateToUserPage(_ username: String?) {
guard let username = username else {
return
}
let homeVC = self.storyboard?.instantiateViewController(withIdentifier: Identifier.profileViewController.rawValue) as? ProfileViewController
homeVC?.userid = username
self.navigationController?.pushViewController(homeVC!, animated: true)
}
func showActionSheet(_ alertController: UIAlertController?) {
self.present(alertController!, animated: true, completion: nil)
}
func navigateToPostPage(_ uuid: String?) {
guard let uuid = uuid else {
return
}
let dstVC = self.storyboard?.instantiateViewController(withIdentifier: Identifier.commentViewController.rawValue) as? CommentViewController
dstVC?.hidesBottomBarWhenPushed = true
dstVC?.postUUID = uuid
self.navigationController?.pushViewController(dstVC!, animated: true)
}
}
| gpl-3.0 | 18ffa251b979d10ab520c2316182050e | 30.770642 | 148 | 0.656945 | 5.215361 | false | false | false | false |
zvonler/PasswordElephant | external/github.com/apple/swift-protobuf/Sources/SwiftProtobuf/BinaryEncodingSizeVisitor.swift | 7 | 15208 | // Sources/SwiftProtobuf/BinaryEncodingSizeVisitor.swift - Binary size calculation support
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Visitor used during binary encoding that precalcuates the size of a
/// serialized message.
///
// -----------------------------------------------------------------------------
import Foundation
/// Visitor that calculates the binary-encoded size of a message so that a
/// properly sized `Data` or `UInt8` array can be pre-allocated before
/// serialization.
internal struct BinaryEncodingSizeVisitor: Visitor {
/// Accumulates the required size of the message during traversal.
var serializedSize: Int = 0
init() {}
mutating func visitUnknown(bytes: Data) throws {
serializedSize += bytes.count
}
mutating func visitSingularFloatField(value: Float, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed32).encodedSize
serializedSize += tagSize + MemoryLayout<Float>.size
}
mutating func visitSingularDoubleField(value: Double, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed64).encodedSize
serializedSize += tagSize + MemoryLayout<Double>.size
}
mutating func visitSingularInt32Field(value: Int32, fieldNumber: Int) throws {
try visitSingularInt64Field(value: Int64(value), fieldNumber: fieldNumber)
}
mutating func visitSingularInt64Field(value: Int64, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize
serializedSize += tagSize + Varint.encodedSize(of: value)
}
mutating func visitSingularUInt32Field(value: UInt32, fieldNumber: Int) throws {
try visitSingularUInt64Field(value: UInt64(value), fieldNumber: fieldNumber)
}
mutating func visitSingularUInt64Field(value: UInt64, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize
serializedSize += tagSize + Varint.encodedSize(of: value)
}
mutating func visitSingularSInt32Field(value: Int32, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize
serializedSize += tagSize + Varint.encodedSize(of: ZigZag.encoded(value))
}
mutating func visitSingularSInt64Field(value: Int64, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize
serializedSize += tagSize + Varint.encodedSize(of: ZigZag.encoded(value))
}
mutating func visitSingularFixed32Field(value: UInt32, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed32).encodedSize
serializedSize += tagSize + MemoryLayout<UInt32>.size
}
mutating func visitSingularFixed64Field(value: UInt64, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed64).encodedSize
serializedSize += tagSize + MemoryLayout<UInt64>.size
}
mutating func visitSingularSFixed32Field(value: Int32, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed32).encodedSize
serializedSize += tagSize + MemoryLayout<Int32>.size
}
mutating func visitSingularSFixed64Field(value: Int64, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed64).encodedSize
serializedSize += tagSize + MemoryLayout<Int64>.size
}
mutating func visitSingularBoolField(value: Bool, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize
serializedSize += tagSize + 1
}
mutating func visitSingularStringField(value: String, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let count = value.utf8.count
serializedSize += tagSize + Varint.encodedSize(of: Int64(count)) + count
}
mutating func visitSingularBytesField(value: Data, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let count = value.count
serializedSize += tagSize + Varint.encodedSize(of: Int64(count)) + count
}
mutating func visitPackedFloatField(value: [Float], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let dataSize = value.count * MemoryLayout<Float>.size
serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedDoubleField(value: [Double], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let dataSize = value.count * MemoryLayout<Double>.size
serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedInt32Field(value: [Int32], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
var dataSize = 0
for v in value {
dataSize += Varint.encodedSize(of: v)
}
serializedSize +=
tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedInt64Field(value: [Int64], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
var dataSize = 0
for v in value {
dataSize += Varint.encodedSize(of: v)
}
serializedSize +=
tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedSInt32Field(value: [Int32], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
var dataSize = 0
for v in value {
dataSize += Varint.encodedSize(of: ZigZag.encoded(v))
}
serializedSize +=
tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedSInt64Field(value: [Int64], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
var dataSize = 0
for v in value {
dataSize += Varint.encodedSize(of: ZigZag.encoded(v))
}
serializedSize +=
tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedUInt32Field(value: [UInt32], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
var dataSize = 0
for v in value {
dataSize += Varint.encodedSize(of: v)
}
serializedSize +=
tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedUInt64Field(value: [UInt64], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
var dataSize = 0
for v in value {
dataSize += Varint.encodedSize(of: v)
}
serializedSize +=
tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedFixed32Field(value: [UInt32], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let dataSize = value.count * MemoryLayout<UInt32>.size
serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedFixed64Field(value: [UInt64], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let dataSize = value.count * MemoryLayout<UInt64>.size
serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedSFixed32Field(value: [Int32], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let dataSize = value.count * MemoryLayout<Int32>.size
serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedSFixed64Field(value: [Int64], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let dataSize = value.count * MemoryLayout<Int64>.size
serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedBoolField(value: [Bool], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let dataSize = value.count
serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitSingularEnumField<E: Enum>(value: E,
fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .varint).encodedSize
serializedSize += tagSize
let dataSize = Varint.encodedSize(of: Int32(truncatingIfNeeded: value.rawValue))
serializedSize += dataSize
}
mutating func visitRepeatedEnumField<E: Enum>(value: [E],
fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .varint).encodedSize
serializedSize += value.count * tagSize
for v in value {
let dataSize = Varint.encodedSize(of: Int32(truncatingIfNeeded: v.rawValue))
serializedSize += dataSize
}
}
mutating func visitPackedEnumField<E: Enum>(value: [E],
fieldNumber: Int) throws {
guard !value.isEmpty else {
return
}
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .varint).encodedSize
serializedSize += tagSize
var dataSize = 0
for v in value {
dataSize += Varint.encodedSize(of: Int32(truncatingIfNeeded: v.rawValue))
}
serializedSize += Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitSingularMessageField<M: Message>(value: M,
fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .lengthDelimited).encodedSize
let messageSize = try value.serializedDataSize()
serializedSize +=
tagSize + Varint.encodedSize(of: UInt64(messageSize)) + messageSize
}
mutating func visitRepeatedMessageField<M: Message>(value: [M],
fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .lengthDelimited).encodedSize
serializedSize += value.count * tagSize
for v in value {
let messageSize = try v.serializedDataSize()
serializedSize +=
Varint.encodedSize(of: UInt64(messageSize)) + messageSize
}
}
mutating func visitSingularGroupField<G: Message>(value: G, fieldNumber: Int) throws {
// The wire format doesn't matter here because the encoded size of the
// integer won't change based on the low three bits.
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .startGroup).encodedSize
serializedSize += 2 * tagSize
try value.traverse(visitor: &self)
}
mutating func visitRepeatedGroupField<G: Message>(value: [G],
fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .startGroup).encodedSize
serializedSize += 2 * value.count * tagSize
for v in value {
try v.traverse(visitor: &self)
}
}
mutating func visitMapField<KeyType, ValueType: MapValueType>(
fieldType: _ProtobufMap<KeyType, ValueType>.Type,
value: _ProtobufMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .lengthDelimited).encodedSize
for (k,v) in value {
var sizer = BinaryEncodingSizeVisitor()
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &sizer)
try ValueType.visitSingular(value: v, fieldNumber: 2, with: &sizer)
let entrySize = sizer.serializedSize
serializedSize += Varint.encodedSize(of: Int64(entrySize)) + entrySize
}
serializedSize += value.count * tagSize
}
mutating func visitMapField<KeyType, ValueType>(
fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type,
value: _ProtobufEnumMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws where ValueType.RawValue == Int {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .lengthDelimited).encodedSize
for (k,v) in value {
var sizer = BinaryEncodingSizeVisitor()
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &sizer)
try sizer.visitSingularEnumField(value: v, fieldNumber: 2)
let entrySize = sizer.serializedSize
serializedSize += Varint.encodedSize(of: Int64(entrySize)) + entrySize
}
serializedSize += value.count * tagSize
}
mutating func visitMapField<KeyType, ValueType>(
fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type,
value: _ProtobufMessageMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .lengthDelimited).encodedSize
for (k,v) in value {
var sizer = BinaryEncodingSizeVisitor()
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &sizer)
try sizer.visitSingularMessageField(value: v, fieldNumber: 2)
let entrySize = sizer.serializedSize
serializedSize += Varint.encodedSize(of: Int64(entrySize)) + entrySize
}
serializedSize += value.count * tagSize
}
mutating func visitExtensionFieldsAsMessageSet(
fields: ExtensionFieldValueSet,
start: Int,
end: Int
) throws {
var sizer = BinaryEncodingMessageSetSizeVisitor()
try fields.traverse(visitor: &sizer, start: start, end: end)
serializedSize += sizer.serializedSize
}
}
internal extension BinaryEncodingSizeVisitor {
// Helper Visitor to compute the sizes when writing out the extensions as MessageSets.
internal struct BinaryEncodingMessageSetSizeVisitor: SelectiveVisitor {
var serializedSize: Int = 0
init() {}
mutating func visitSingularMessageField<M: Message>(value: M, fieldNumber: Int) throws {
var groupSize = WireFormat.MessageSet.itemTagsEncodedSize
groupSize += Varint.encodedSize(of: Int32(fieldNumber))
let messageSize = try value.serializedDataSize()
groupSize += Varint.encodedSize(of: UInt64(messageSize)) + messageSize
serializedSize += groupSize
}
// SelectiveVisitor handles the rest.
}
}
| gpl-3.0 | 247c8bb2646e44512c63737b9692df6c | 40.214092 | 94 | 0.697988 | 4.934458 | false | false | false | false |
kylecrawshaw/ImagrAdmin | ImagrAdmin/WorkflowSupport/WorkflowComponents/LocalizationComponent/LocalizationComponent.swift | 1 | 2448 | //
// ImageComponent.swift
// ImagrManager
//
// Created by Kyle Crawshaw on 7/12/16.
// Copyright © 2016 Kyle Crawshaw. All rights reserved.
//
import Foundation
import Cocoa
class LocalizationComponent: BaseComponent {
var keyboardLayoutName: String?
var keyboardLayoutId: String?
var countryCode: String?
var language: String?
var timezone: String?
// var locale: String?
init(id: Int!, workflowName: String!, workflowId: Int!) {
super.init(id: id, type: "localize", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = LocalizationComponentViewController()
}
init(id: Int!, workflowName: String!, workflowId: Int!, dict: NSDictionary!) {
super.init(id: id, type: "localize", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = LocalizationComponentViewController()
self.keyboardLayoutName = dict.valueForKey("keyboard_layout_name") as? String
self.keyboardLayoutId = dict.valueForKey("keyboard_layout_id") as? String
self.timezone = dict.valueForKey("timezone") as? String
self.language = dict.valueForKey("language") as? String
if let locale = dict.valueForKey("locale") as? String {
let localeComponents = locale.characters.split{$0 == "_"}.map(String.init)
if localeComponents.count == 1 {
self.countryCode = localeComponents[0]
} else if localeComponents.count == 2 {
self.countryCode = localeComponents[1]
}
}
}
override func asDict() -> NSDictionary? {
var dict: [String: AnyObject] = [
"type": type,
]
if (keyboardLayoutName != nil) && (keyboardLayoutName != "") {
dict["keyboard_layout_name"] = keyboardLayoutName!
}
if (keyboardLayoutId != nil) && (keyboardLayoutId != "" ){
dict["keyboard_layout_id"] = Int(keyboardLayoutId!)
}
if (language != nil) && (language! != "") {
dict["language"] = language!
}
if (countryCode != nil && countryCode! != "" && language != nil) {
dict["locale"] = "\(language!)_\(countryCode!)"
}
if (timezone != nil) && (timezone != "") {
dict["timezone"] = timezone!
}
return dict
}
} | apache-2.0 | ed85fdb917133c9363687278c249b66c | 33 | 96 | 0.589293 | 4.652091 | false | false | false | false |
nickbryanmiller/UniqueAccessibilityIdentifiers | Unique AccessID iOS/Unique AccessID iOS/AIDExtension.swift | 2 | 15277 | // Please Leave This Header In This File
//
// File Name: AIDExtension.swift
//
// Description:
// Creating Unique Accessibility Identifiers of every object at Runtime
//
// This is big for Native Automated Testing in conjunction with the XCTest Framework
// If you call this file the test recording software no longer has to grab the relative identifier because it
// can grab the absolute identifier making the test cases less difficult to write
//
// Developers:
// Nicholas Bryan Miller (GitHub: https://github.com/nickbryanmiller )
// Justin Rose (GitHub: https://github.com/justinjaster )
//
// Created by Nicholas Miller on 7/21/16
// Copyright © 2016 Nicholas Miller. All rights reserved.
// This code is under the Apache 2.0 License.
//
// Use:
// In the viewDidLayoutSubviews() method in each ViewController put "self.setEachIDInViewController()"
// In the viewWillDisappear() method in each ViewController put "self.removeEachIDInViewController()"
// and this file will do the rest for you
//
// Tools:
// We make use of class extensions, mirroring, and the built in view hierarchy
//
// Note:
// If you see an issue anywhere please open a merge request and we will get to it as soon as possible.
// If you would like to make an improvement anywhere open a merge request.
// If you liked anything or are curious about anything reach out to one of us.
// We like trying to improve the iOS Community :)
// If you or your company decides to take it and implement it we would LOVE to know that please!!
//
import Foundation
import UIKit
extension Array where Element: Equatable {
mutating func removeObject(object: Element) {
if let index = self.indexOf(object) {
self.removeAtIndex(index)
}
}
mutating func removeEveryObjectInArray(array: [Element]) {
for object in array {
self.removeObject(object)
}
}
mutating func removeAllOfAnObjectInArray(array: [Element], object: Element) {
for element in array {
if element == object {
self.removeObject(object)
}
}
}
}
extension String {
func removeSpaces() -> String {
let noSpaceString = self.characters.split{$0 == " "}.map{String($0)}.joinWithSeparator("")
return noSpaceString
}
func splitBy(splitter: Character) -> [String] {
let splitArray = self.characters.split{$0 == splitter}.map(String.init)
return splitArray
}
}
extension UIViewController {
// This could be a dictionary where the key is the ViewControllerName
private struct AssociatedKeys {
static var existingIDArray: [String] = []
}
func removeEachIDInViewController() {
removeEachIDForViewControllerAndView(self.view)
}
func setEachIDInViewController() {
setEachIDForViewControllerAndView(self.view)
}
private func removeEachIDForViewControllerAndView(view: UIView) {
for element in view.subviews {
if let aID = element.accessibilityIdentifier {
if aID.containsString("NJAid") {
AssociatedKeys.existingIDArray.removeObject(aID)
element.accessibilityIdentifier = nil
}
}
if element.subviews.count > 0 {
removeEachIDForViewControllerAndView(element)
}
}
}
private func setEachIDForViewControllerAndView(view: UIView) {
for element in view.subviews {
// We want to mark these with identifiers and go down their view hierarchy
if element is UITableViewCell || element is UICollectionViewCell || element is UIScrollView || element is UITableView || element is UICollectionView {
setAndCheckID(element)
}
// essentials
if element is UITextField || element is UITextView || element is UIButton || element is UISwitch || element is UISegmentedControl || element is UIWebView {
setAndCheckID(element)
}
// throw aways
else if element is UILabel || element is UIImageView || element is UINavigationBar || element is UITabBar {
}
// recursive down the view hierarchy
else if element.subviews.count > 0 {
setEachIDForViewControllerAndView(element)
}
}
}
private func setAndCheckID(element: UIView) {
if element.accessibilityIdentifier != nil && element.accessibilityIdentifier != "" {
return
}
else {
if element is UIScrollView {
element.setID(self, pageType: "Dynamic")
}
else {
element.setID(self, pageType: "Static")
}
var idString = element.getID()
let count = getDuplicateCount(idString)
if count > 0 {
idString = idString + ", Count: \(count)"
}
let finalID = "<" + idString + ">"
element.setCustomID(finalID)
AssociatedKeys.existingIDArray.append(finalID)
}
}
func getDuplicateCount(idString: String) -> Int {
var testIDString = idString
var duplicateCount = 0
if !AssociatedKeys.existingIDArray.contains("<" + testIDString + ">") {
return 0
}
else {
// This is to make sure that we do not have a duplicate. If we do it appends a number to it
// This number is increasing based on the order it was added to the xml
while AssociatedKeys.existingIDArray.contains("<" + testIDString + ">") {
testIDString = idString
duplicateCount = duplicateCount + 1
testIDString = testIDString + ", Count: \(duplicateCount)"
}
return duplicateCount
}
}
// This method is for developers to set a custom ID
// At the viewcontroller level is ideal because we can check for a duplicate
func setIDForElement(element: UIView, aID: String) {
if AssociatedKeys.existingIDArray.contains(aID) {
print("It already exists in the application")
}
else {
element.setCustomID(aID)
}
}
func getExisitingIDArray() -> [String] {
return AssociatedKeys.existingIDArray
}
func printEachID() {
for element in AssociatedKeys.existingIDArray {
print(element)
}
}
func printOutlets() {
let vcMirror = Mirror(reflecting: self)
for child in vcMirror.children {
print(child)
print(child.label)
}
}
}
extension UIView {
func setCustomID(aID: String) {
self.accessibilityIdentifier = aID
}
func getID() -> String {
if let aID = self.accessibilityIdentifier {
return aID
}
else {
return ""
}
}
private func setID(vc: UIViewController, pageType: String) {
let vcMirror = Mirror(reflecting: vc)
var id: String = "NJAid"
// let className = NSStringFromClass(vc.classForCoder).splitBy(".")[1]
let className = "\(vcMirror.subjectType)"
let grandParentOutletName = getGrandParentOutletName(vcMirror)
let parentOutletName = getParentOutletName(vcMirror)
let selfOutletName = getSelfOutletName(vcMirror)
let positionInParent = getPositionInParentView()
let title = getTitle()
let type = getType()
if className != "" {
id = id + ", ClassName: " + className
}
if grandParentOutletName != "" {
id = id + ", GPOutlet: " + grandParentOutletName
}
if parentOutletName != "" {
id = id + ", POutlet: " + parentOutletName
}
if selfOutletName != "" {
id = id + ", SelfOutlet: " + selfOutletName
}
if pageType == "Static" {
if positionInParent != "" {
id = id + ", PositionInParent: " + positionInParent
}
}
if title != "" {
id = id + ", Title: " + title
}
if type != "" {
id = id + ", Type: " + type
}
self.accessibilityIdentifier = id
}
func getGrandParentOutletName(vcMirror: Mirror) -> String {
var memoryID = ""
let selfString = "\(self.superview?.superview)"
if let firstColon = selfString.characters.indexOf(":") {
let twoAfterFirstColon = firstColon.advancedBy(2)
let beyondType = selfString.substringFromIndex(twoAfterFirstColon)
if let firstSemicolon = beyondType.characters.indexOf(";") {
memoryID = beyondType.substringToIndex(firstSemicolon)
}
}
for child in vcMirror.children {
if memoryID != "" && "\(child.value)".containsString(memoryID) {
if let childLabel = child.label {
return childLabel
}
}
}
return ""
}
func getParentOutletName(vcMirror: Mirror) -> String {
var memoryID = ""
let selfString = "\(self.superview)"
if let firstColon = selfString.characters.indexOf(":") {
let twoAfterFirstColon = firstColon.advancedBy(2)
let beyondType = selfString.substringFromIndex(twoAfterFirstColon)
if let firstSemicolon = beyondType.characters.indexOf(";") {
memoryID = beyondType.substringToIndex(firstSemicolon)
}
}
for child in vcMirror.children {
if memoryID != "" && "\(child.value)".containsString(memoryID) {
if let childLabel = child.label {
return childLabel
}
}
}
return ""
}
func getSelfOutletName(vcMirror: Mirror) -> String {
var memoryID = ""
let selfString = "\(self)"
if let firstColon = selfString.characters.indexOf(":") {
let twoAfterFirstColon = firstColon.advancedBy(2)
let beyondType = selfString.substringFromIndex(twoAfterFirstColon)
if let firstSemicolon = beyondType.characters.indexOf(";") {
memoryID = beyondType.substringToIndex(firstSemicolon)
}
}
for child in vcMirror.children {
if memoryID != "" && "\(child.value)".containsString(memoryID) {
if let childLabel = child.label {
return childLabel
}
}
}
return ""
}
private func getTitle() -> String {
var title: String = ""
if let myButton = self as? UIButton {
if let buttonTitle = myButton.currentTitle {
title = buttonTitle.removeSpaces()
}
}
else if let myLabel = self as? UILabel {
if let labelTitle = myLabel.text {
title = labelTitle.removeSpaces()
}
}
else if let myTextField = self as? UITextField {
if let textFieldTitle = myTextField.placeholder {
title = textFieldTitle.removeSpaces()
}
}
else if let myNavigationBar = self as? UINavigationBar {
if let navigationBarTitle = myNavigationBar.topItem?.title {
title = navigationBarTitle.removeSpaces()
}
}
return title
}
func getType() -> String {
var elementType: String = ""
switch self {
case is UIButton:
elementType = "UIButton"
case is UILabel:
elementType = "UILabel"
case is UIImageView:
elementType = "UIImageView"
case is UITextView:
elementType = "UITextView"
case is UITextField:
elementType = "UITextField"
case is UISegmentedControl:
elementType = "UISegmentedControl"
case is UISwitch:
elementType = "UISwitch"
case is UINavigationBar:
elementType = "UINavigationBar"
case is UITabBar:
elementType = "UITabBar"
case is UIWebView:
elementType = "UIWebView"
case is UITableViewCell:
elementType = "UITableViewCell"
case is UICollectionViewCell:
elementType = "UICollectionViewCell"
case is UITableView:
elementType = "UITableView"
case is UICollectionView:
elementType = "UICollectionView"
default:
elementType = "UIView"
}
return elementType
}
private func getPositionInParentView() -> String {
var positionInParent: String = ""
if let parentView = self.superview {
let parentViewHeightDividedByThree = parentView.bounds.height / 3
let parentViewWidthDividedByThree = parentView.bounds.width / 3
let subviewCenterX = self.center.x
let subviewCenterY = self.center.y
if subviewCenterY <= parentViewHeightDividedByThree {
if subviewCenterX <= parentViewWidthDividedByThree {
positionInParent = "TopLeft"
}
else if subviewCenterX > parentViewWidthDividedByThree && subviewCenterX < parentViewWidthDividedByThree * 2 {
positionInParent = "TopMiddle"
}
else if subviewCenterX >= parentViewWidthDividedByThree * 2 {
positionInParent = "TopRight"
}
}
else if subviewCenterY > parentViewHeightDividedByThree && subviewCenterY < parentViewHeightDividedByThree * 2 {
if subviewCenterX <= parentViewWidthDividedByThree {
positionInParent = "MiddleLeft"
}
else if subviewCenterX > parentViewWidthDividedByThree && subviewCenterX < parentViewWidthDividedByThree * 2 {
positionInParent = "MiddleMiddle"
}
else if subviewCenterX >= parentViewWidthDividedByThree * 2 {
positionInParent = "MiddleRight"
}
}
else if subviewCenterY >= parentViewHeightDividedByThree * 2 {
if subviewCenterX <= parentViewWidthDividedByThree {
positionInParent = "BottomLeft"
}
else if subviewCenterX > parentViewWidthDividedByThree && subviewCenterX < parentViewWidthDividedByThree * 2 {
positionInParent = "BottomMiddle"
}
else if subviewCenterX >= parentViewWidthDividedByThree * 2 {
positionInParent = "BottomRight"
}
}
}
return positionInParent
}
}
| apache-2.0 | e53bf23286d5b6d51f1bda4c23f5184f | 32.353712 | 167 | 0.570568 | 5.760181 | false | false | false | false |
keyOfVv/KEYUI | KEYUI/sources/KEYButton/KEYButton.swift | 1 | 8706 | //
// KEYButton.swift
// KEYButton
//
// Created by Ke Yang on 4/20/16.
// Copyright © 2016 com.sangebaba. All rights reserved.
//
/*
* 功能:
* - 可自定义图片与标题的相对位置, 包括左右对调和上下排列.
*
*/
import UIKit
@objc public enum LayoutType: Int {
case normal
case leftTitleRightImage
case topTitleBottomImage
case topImageBottomTitle
}
open class KEYButton: UIButton {
// MARK: stored property
/// size of title
fileprivate var ttlF = CGRect.zero
/// size of image
fileprivate var imgF = CGRect.zero
/// layout type
open var layoutType = LayoutType.normal {
didSet { self.setNeedsLayout() }
}
/// border line width
open var borderWidth = 0.0 {
didSet {
self.setNeedsDisplay()
}
}
/// border line color
open var borderColor = UIColor.black {
didSet { self.setNeedsDisplay() }
}
/// fill color
open var fillColor = UIColor.clear {
didSet { self.setNeedsDisplay() }
}
/// rounding corners
open var roundingCorners: UIRectCorner = UIRectCorner.allCorners {
didSet { self.setNeedsDisplay() }
}
// MARK: computed property
/// animation images
open var animationImages: [UIImage]? {
set {
self.setImage(newValue?.first, for: UIControlState())
self.imageView?.animationImages = newValue
}
get {
return self.imageView?.animationImages
}
}
/// animation duration
open var animationDuration: TimeInterval {
set {
self.imageView?.animationDuration = newValue
}
get {
return self.imageView?.animationDuration ?? 0
}
}
/// animation repeat count
open var animationRepeatCount: Int {
set {
self.imageView?.animationRepeatCount = newValue
}
get {
return self.imageView?.animationRepeatCount ?? 0
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public convenience init(layoutType: LayoutType) {
self.init(frame: CGRect.zero)
self.layoutType = layoutType
}
open override func layoutSubviews() {
super.layoutSubviews()
// 1. cal image bounds
if let img = self.currentImage {
imgF = CGRect(x: 0.0, y: 0.0, width: img.size.width, height: img.size.height)
}
// 2. cal title bounds
if let ttl = self.currentTitle, let font = self.titleLabel?.font {
ttlF = (ttl as NSString).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil)
}
// 3. layout subviews
switch layoutType {
// 3.1
case .leftTitleRightImage: // w = 120, h = 60
// 3.1.1 cal title frame
// default horizontal margin of title
let hTtlMrgDef = max((frame.width - imgF.width - ttlF.width) * 0.5, 0.0)
// default vertical margin of title
let vTtlMrgDef = max((frame.height - ttlF.height) * 0.5, 0.0)
// ttlX/Y/W/H
let ttlX = contentEdgeInsets.left + titleEdgeInsets.left + hTtlMrgDef
let ttlY = contentEdgeInsets.top + titleEdgeInsets.top + vTtlMrgDef
let ttlW = max(min(frame.width - ttlX - contentEdgeInsets.right - titleEdgeInsets.right, ttlF.width), 0.0)
let ttlH = max(min(frame.height - ttlY - contentEdgeInsets.bottom - titleEdgeInsets.bottom, ttlF.height), 0.0)
let newTtlF = CGRect(x: ttlX, y: ttlY, width: ttlW, height: ttlH)
// 3.1.2 cal image frame
// default vertical margin of image
let vImgMrgDef = (frame.height - imgF.height) * 0.5
// imgX/Y/W/H
let imgX = contentEdgeInsets.left + imageEdgeInsets.left + hTtlMrgDef + ttlF.width
let imgY = contentEdgeInsets.top + imageEdgeInsets.top + vImgMrgDef
let imgW = max(min(frame.width - imgX - contentEdgeInsets.right - imageEdgeInsets.right, imgF.width), 0.0)
let imgH = max(min(frame.height - imgY - contentEdgeInsets.bottom - imageEdgeInsets.bottom, imgF.height), 0.0)
let newImgF = CGRect(x: imgX, y: imgY, width: imgW, height: imgH)
self.titleLabel?.frame = newTtlF
self.imageView?.frame = newImgF
// print("\noverall frame = \(frame)\ntitle frame = \(ttlF)\nimage frame = \(imgF)\ndefault title margin H = \(hTtlMrgDef)\ndefault title margi V = \(vTtlMrgDef)\ntitle frame = \(newTtlF)")
break
// 3.2
case .topImageBottomTitle:
// 3.2.1 cal image frame
// default horizontal margin of image
let hImgMrgDef = max((frame.width - imgF.width) * 0.5, 0.0)
// default vertical margin of image
let vImgMrgDef = max((frame.height - imgF.height - ttlF.height) * 0.5, 0.0)
// imgX/Y/W/H
let imgX = contentEdgeInsets.left + imageEdgeInsets.left + hImgMrgDef
let imgY = contentEdgeInsets.top + imageEdgeInsets.top + vImgMrgDef
let imgW = max(min(frame.width - imgX - contentEdgeInsets.right - imageEdgeInsets.right, imgF.width), 0.0)
let imgH = max(min(frame.height - imgY - contentEdgeInsets.bottom - imageEdgeInsets.bottom, imgF.height), 0.0)
let newImgF = CGRect(x: imgX, y: imgY, width: imgW, height: imgH)
// 3.2.2 cal title frame
// default horizontal margin of title
let hTtlMrgDef = max((frame.width - ttlF.width) * 0.5, 0.0)
// ttlX/Y/W/H
let ttlX = contentEdgeInsets.left + titleEdgeInsets.left + hTtlMrgDef
let ttlY = contentEdgeInsets.top + titleEdgeInsets.top + vImgMrgDef + imgF.height
let ttlW = max(min(frame.width - ttlX - contentEdgeInsets.right - titleEdgeInsets.right, ttlF.width), 0.0)
let ttlH = max(min(frame.height - ttlY - contentEdgeInsets.bottom - titleEdgeInsets.bottom, ttlF.height), 0.0)
let newTtlF = CGRect(x: ttlX, y: ttlY, width: ttlW, height: ttlH)
self.titleLabel?.frame = newTtlF
self.imageView?.frame = newImgF
break
case .topTitleBottomImage:
// 3.2.1 cal title frame
// default horizontal margin of title
let hTtlMrgDef = max((frame.width - ttlF.width) * 0.5, 0.0)
// default vertical margin of title
let vTtlMrgDef = max((frame.height - ttlF.height - imgF.height) * 0.5, 0.0)
// ttlX/Y/W/H
let ttlX = contentEdgeInsets.left + titleEdgeInsets.left + hTtlMrgDef
let ttlY = contentEdgeInsets.top + titleEdgeInsets.top + vTtlMrgDef
let ttlW = max(min(frame.width - ttlX - contentEdgeInsets.right - titleEdgeInsets.right, ttlF.width), 0.0)
let ttlH = max(min(frame.height - ttlY - contentEdgeInsets.bottom - titleEdgeInsets.bottom, ttlF.height), 0.0)
let newTtlF = CGRect(x: ttlX, y: ttlY, width: ttlW, height: ttlH)
// 3.2.2 cal image frame
// default horizontal margin of image
let hImgMrgDef = max((frame.width - imgF.width) * 0.5, 0.0)
// imgX/Y/W/H
let imgX = contentEdgeInsets.left + imageEdgeInsets.left + hImgMrgDef
let imgY = contentEdgeInsets.top + imageEdgeInsets.top + vTtlMrgDef + ttlF.height
let imgW = max(min(frame.width - imgX - contentEdgeInsets.right - imageEdgeInsets.right, imgF.width), 0.0)
let imgH = max(min(frame.height - imgY - contentEdgeInsets.bottom - imageEdgeInsets.bottom, imgF.height), 0.0)
let newImgF = CGRect(x: imgX, y: imgY, width: imgW, height: imgH)
self.titleLabel?.frame = newTtlF
self.imageView?.frame = newImgF
break
default:
break
}
}
}
// MARK: -
extension KEYButton {
open override func draw(_ rect: CGRect) {
super.draw(rect)
if borderWidth > 0 {
// 1. draw border
// 1.1 cal rect for border path
let bW = rect.width - CGFloat(borderWidth)
let bH = rect.height - CGFloat(borderWidth)
let bCR = max(self.layer.cornerRadius - CGFloat(borderWidth) * 0.5, 0.0)
let bX = CGFloat(borderWidth) * 0.5
let bY = bX
let borderP = UIBezierPath(roundedRect: CGRect(x: bX, y: bY, width: bW, height: bH),
byRoundingCorners: roundingCorners,
cornerRadii: CGSize(width: bCR, height: bCR))
borderP.lineWidth = CGFloat(borderWidth)
borderColor.setStroke()
borderP.stroke()
// 2. fill within border
let fW = bW - CGFloat(borderWidth)
let fH = bH - CGFloat(borderWidth)
let fX = CGFloat(borderWidth)
let fY = fX
let fCR = max(self.layer.cornerRadius - CGFloat(borderWidth), 0.0)
let fP = UIBezierPath(roundedRect: CGRect(x: fX, y: fY, width: fW, height: fH),
byRoundingCorners: roundingCorners,
cornerRadii: CGSize(width: fCR, height: fCR))
self.backgroundColor = UIColor.clear
fillColor.setFill()
fP.fill()
}
}
public func startAnimating() {
self.imageView?.startAnimating()
}
public func stopAnimating() {
self.imageView?.stopAnimating()
}
public func isAnimating() -> Bool {
return self.imageView?.isAnimating ?? false
}
}
| mit | e50b3da90313169b9293eea589ceca28 | 34.747934 | 191 | 0.677263 | 3.544039 | false | false | false | false |
RCacheaux/BitbucketKit | Carthage/Checkouts/Swinject/Carthage/Checkouts/Quick/Sources/QuickTests/FunctionalTests/SharedExamples+BeforeEachTests.swift | 5 | 1869 | import XCTest
import Quick
import Nimble
#if SWIFT_PACKAGE
import QuickTestHelpers
#endif
var specBeforeEachExecutedCount = 0
var sharedExamplesBeforeEachExecutedCount = 0
class FunctionalTests_SharedExamples_BeforeEachTests_SharedExamples: QuickConfiguration {
override class func configure(configuration: Configuration) {
sharedExamples("a group of three shared examples with a beforeEach") {
beforeEach { sharedExamplesBeforeEachExecutedCount += 1 }
it("passes once") {}
it("passes twice") {}
it("passes three times") {}
}
}
}
class FunctionalTests_SharedExamples_BeforeEachSpec: QuickSpec {
override func spec() {
beforeEach { specBeforeEachExecutedCount += 1 }
it("executes the spec beforeEach once") {}
itBehavesLike("a group of three shared examples with a beforeEach")
}
}
class SharedExamples_BeforeEachTests: XCTestCase, XCTestCaseProvider {
var allTests: [(String, () -> Void)] {
return [
("testBeforeEachOutsideOfSharedExamplesExecutedOnceBeforeEachExample", testBeforeEachOutsideOfSharedExamplesExecutedOnceBeforeEachExample),
("testBeforeEachInSharedExamplesExecutedOnceBeforeEachSharedExample", testBeforeEachInSharedExamplesExecutedOnceBeforeEachSharedExample),
]
}
func testBeforeEachOutsideOfSharedExamplesExecutedOnceBeforeEachExample() {
specBeforeEachExecutedCount = 0
qck_runSpec(FunctionalTests_SharedExamples_BeforeEachSpec.self)
XCTAssertEqual(specBeforeEachExecutedCount, 4)
}
func testBeforeEachInSharedExamplesExecutedOnceBeforeEachSharedExample() {
sharedExamplesBeforeEachExecutedCount = 0
qck_runSpec(FunctionalTests_SharedExamples_BeforeEachSpec.self)
XCTAssertEqual(sharedExamplesBeforeEachExecutedCount, 3)
}
}
| apache-2.0 | 5b4a035ab7521c0abead1f281e1c646d | 35.647059 | 151 | 0.743178 | 6.292929 | false | true | false | false |
thebluepotato/AlamoFuzi | Pods/Alamofire/Source/Validation.swift | 1 | 9789 | //
// Validation.swift
//
// Copyright (c) 2014-2018 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
extension Request {
// MARK: Helper Types
fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason
/// Used to represent whether a validation succeeded or failed.
public typealias ValidationResult = AFResult<Void>
fileprivate struct MIMEType {
let type: String
let subtype: String
var isWildcard: Bool { return type == "*" && subtype == "*" }
init?(_ string: String) {
let components: [String] = {
let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines)
let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)]
return split.components(separatedBy: "/")
}()
if let type = components.first, let subtype = components.last {
self.type = type
self.subtype = subtype
} else {
return nil
}
}
func matches(_ mime: MIMEType) -> Bool {
switch (type, subtype) {
case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"):
return true
default:
return false
}
}
}
// MARK: Properties
fileprivate var acceptableStatusCodes: Range<Int> { return 200..<300 }
fileprivate var acceptableContentTypes: [String] {
if let accept = request?.value(forHTTPHeaderField: "Accept") {
return accept.components(separatedBy: ",")
}
return ["*/*"]
}
// MARK: Status Code
fileprivate func validate<S: Sequence>(
statusCode acceptableStatusCodes: S,
response: HTTPURLResponse)
-> ValidationResult
where S.Iterator.Element == Int
{
if acceptableStatusCodes.contains(response.statusCode) {
return .success(Void())
} else {
let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode)
return .failure(AFError.responseValidationFailed(reason: reason))
}
}
// MARK: Content Type
fileprivate func validate<S: Sequence>(
contentType acceptableContentTypes: S,
response: HTTPURLResponse,
data: Data?)
-> ValidationResult
where S.Iterator.Element == String
{
guard let data = data, data.count > 0 else { return .success(Void()) }
guard
let responseContentType = response.mimeType,
let responseMIMEType = MIMEType(responseContentType)
else {
for contentType in acceptableContentTypes {
if let mimeType = MIMEType(contentType), mimeType.isWildcard {
return .success(Void())
}
}
let error: AFError = {
let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes))
return AFError.responseValidationFailed(reason: reason)
}()
return .failure(error)
}
for contentType in acceptableContentTypes {
if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) {
return .success(Void())
}
}
let error: AFError = {
let reason: ErrorReason = .unacceptableContentType(
acceptableContentTypes: Array(acceptableContentTypes),
responseContentType: responseContentType
)
return AFError.responseValidationFailed(reason: reason)
}()
return .failure(error)
}
}
// MARK: -
extension DataRequest {
/// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the
/// request was valid.
public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult
/// Validates that the response has a status code in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter range: The range of acceptable status codes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
return validate { [unowned self] _, response, _ in
return self.validate(statusCode: acceptableStatusCodes, response: response)
}
}
/// Validates that the response has a content type in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
return validate { [unowned self] _, response, data in
return self.validate(contentType: acceptableContentTypes(), response: response, data: data)
}
}
/// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
/// type matches any specified in the Accept HTTP header field.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - returns: The request.
@discardableResult
public func validate() -> Self {
let contentTypes: () -> [String] = { [unowned self] in
return self.acceptableContentTypes
}
return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
}
}
// MARK: -
extension DownloadRequest {
/// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a
/// destination URL, and returns whether the request was valid.
public typealias Validation = (
_ request: URLRequest?,
_ response: HTTPURLResponse,
_ fileURL: URL?)
-> ValidationResult
/// Validates that the response has a status code in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter range: The range of acceptable status codes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
return validate { [unowned self] (_, response, _) in
return self.validate(statusCode: acceptableStatusCodes, response: response)
}
}
/// Validates that the response has a content type in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
return validate { [unowned self] (_, response, fileURL) in
guard let validFileURL = fileURL else {
return .failure(AFError.responseValidationFailed(reason: .dataFileNil))
}
do {
let data = try Data(contentsOf: validFileURL)
return self.validate(contentType: acceptableContentTypes(), response: response, data: data)
} catch {
return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL)))
}
}
}
/// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
/// type matches any specified in the Accept HTTP header field.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - returns: The request.
@discardableResult
public func validate() -> Self {
let contentTypes = { [unowned self] in
return self.acceptableContentTypes
}
return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
}
}
| mit | 818555e06441b66a984f210d97f68dfc | 37.388235 | 150 | 0.641639 | 5.265734 | false | false | false | false |
protoman92/SwiftUtilities | SwiftUtilitiesTests/test/date/DatesTest.swift | 1 | 2667 | //
// DateUtilTest.swift
// SwiftUtilitiesTests
//
// Created by Hai Pham on 2/11/16.
// Copyright © 2016 Swiften. All rights reserved.
//
import XCTest
@testable import SwiftUtilities
public final class DatesTest: XCTestCase {
/// Test date comparison methods and ensure they work correctly.
public func test_dateComparison_shouldSucceed() {
/// Setup
let calendar = Calendar.current
/// Test date comparison using parameters. This closure accepts three
/// arguments, the first being the starting Date, to/from which an
/// offset value - the second argument - will be added/subtracted.
/// The third argument is a Calendar.Component instance that will
/// be used for granularity comparison.
let testDateComparison: (Date, Int, Calendar.Component) -> Void = {
/// Setup
let date = $0
// When
let fDate = calendar.date(byAdding: $2, value: -$1, to: $0)!
let sDate = calendar.date(byAdding: $2, value: $1, to: $0)!
// Then
/// Comparing from the Date instance itself.
XCTAssertTrue(date.sameAs(date: date))
XCTAssertTrue(date.notLaterThan(date: date))
XCTAssertTrue(date.notEarlierThan(date: date))
XCTAssertTrue(date.laterThan(date: fDate))
XCTAssertTrue(date.notEarlierThan(date: fDate))
XCTAssertTrue(date.earlierThan(date: sDate))
XCTAssertTrue(date.notLaterThan(date: sDate))
/// Comparing using a Calendar instance.
XCTAssertTrue(calendar.notLaterThan(compare: date, to: date, granularity: $2))
XCTAssertTrue(calendar.notEarlierThan(compare: date, to: date, granularity: $2))
XCTAssertTrue(calendar.notEarlierThan(compare: date, to: fDate, granularity: $2))
XCTAssertTrue(calendar.notLaterThan(compare: date, to: sDate, granularity: $2))
XCTAssertTrue(calendar.laterThan(compare: date, to: fDate, granularity: $2))
XCTAssertTrue(calendar.notLaterThan(compare: date, to: sDate, granularity: $2))
}
// When
for i in 1...1000 {
let dateComponents = DateComponents.random()
let date = calendar.date(from: dateComponents)!
let offset = Int.randomBetween(1, i)
let calendarComponent = Calendar.Component.random()
testDateComparison(date, offset, calendarComponent)
}
}
public func test_randomBetween_shouldWork() {
/// Setup
let startDate = Date.random()!
let endDate = startDate.addingTimeInterval(100000000)
/// When
for _ in 0..<1000 {
let randomized = Date.randomBetween(startDate, endDate)!
/// Then
XCTAssertTrue(randomized >= startDate)
XCTAssertTrue(randomized <= endDate)
}
}
}
| apache-2.0 | 86b655d2b4be3d8943dc266de12595cf | 34.078947 | 87 | 0.68117 | 4.313916 | false | true | false | false |
terryokay/learnAnimationBySwift | learnAnimation/learnAnimation/BackgroundLineView.swift | 1 | 4337 | //
// BackgroundLineView.swift
// learnAnimation
//
// Created by likai on 2017/4/17.
// Copyright © 2017年 terry. All rights reserved.
//
import UIKit
class BackgroundLineView: UIView {
var lineWidth : CGFloat{
get{ return backgroundView.lineWidth}
set(newVal){
backgroundView.lineWidth = newVal
backgroundView.setNeedsDisplay()
}
}
var lineGap : CGFloat {
get {return backgroundView.lineGap}
set(newVal){
backgroundView.lineGap = newVal
backgroundView.setNeedsDisplay()
}
}
var lineColor : UIColor{
get{return backgroundView.lineColor}
set(newVal){
backgroundView.lineColor = newVal
backgroundView.setNeedsDisplay()
}
}
var rotate : CGFloat {
get {return backgroundView.rotate}
set(newVal){
backgroundView.rotate = newVal
backgroundView.setNeedsDisplay()
}
}
convenience init(frame:CGRect, lineWidth : CGFloat, lineGap : CGFloat,lineColor : UIColor, rotate : CGFloat){
self.init(frame: frame)
self.lineWidth = lineWidth
self.lineGap = lineGap
self.lineColor = lineColor
self.rotate = rotate
}
override func layoutSubviews() {
super.layoutSubviews()
setupBackgroundView()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.masksToBounds = true
self.addSubview(backgroundView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate let backgroundView = LineBackground(length: 0)
fileprivate func setupBackgroundView(){
let drawLength = sqrt(self.bounds.size.width * self.bounds.size.width + self.bounds.size.height * self.bounds.size.height)
backgroundView.frame = CGRect(x: 0, y: 0, width: drawLength, height: drawLength)
backgroundView.center = CGPoint(x: self.bounds.size.width / 2.0, y: self.bounds.size.height / 2.0)
backgroundView.setNeedsDisplay()
}
}
private class LineBackground : UIView{
fileprivate var rotate : CGFloat = 0
fileprivate var lineWidth : CGFloat = 5
fileprivate var lineGap : CGFloat = 3
fileprivate var lineColor : UIColor = UIColor.gray
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(length : CGFloat){
self.init(frame: CGRect(x: 0, y: 0, width: length, height: length))
}
override func draw(_ rect: CGRect) {
super.draw(rect)
guard self.bounds.size.width > 0 && self.bounds.size.height > 0 else{
return
}
let context = UIGraphicsGetCurrentContext()
let width = self.bounds.size.width
let height = self.bounds.size.height
let drawLength = sqrt(width * width + height * height)
let outerX = (drawLength - width) / 2.0
let outerY = (drawLength - height) / 2.0
let tmpLineWidth = lineWidth <= 0 ? 5 : lineWidth
let tmpLineGap = lineGap <= 0 ? 3 : lineGap
var red : CGFloat = 0
var green : CGFloat = 0
var blue : CGFloat = 0
var alpha : CGFloat = 0
context?.translateBy(x: 0.5 * drawLength, y: 0.5 * drawLength)
context?.rotate(by: rotate)
context?.translateBy(x: -0.5 * drawLength, y: -0.5 * drawLength)
lineColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
context?.setFillColor(red: red, green: green, blue: blue, alpha: alpha)
var currentX = -outerX
while currentX < drawLength{
context?.addRect(CGRect(x: currentX, y: -outerY, width: tmpLineWidth, height: drawLength))
currentX += tmpLineWidth + tmpLineGap
}
context?.fillPath()
}
}
| mit | 2701b143720d36f0cad730cdc3a86001 | 26.605096 | 130 | 0.574988 | 4.757409 | false | false | false | false |
ttlock/iOS_TTLock_Demo | Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/DFUSelector/DFUServiceSelector.swift | 2 | 3375 | /*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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 CoreBluetooth
internal protocol DFUStarterPeripheralDelegate : BasePeripheralDelegate {
/**
Callback called when a DFU service has been found on a remote device.
- parameter ExecutorType: The type of the seleceted executor.
- returns: The executor type based on the found DFU Service:
SecureDFUExecutor or LegacyDFUExecutor.
*/
func peripheralDidSelectedExecutor(_ ExecutorType: DFUExecutorAPI.Type)
}
/**
This class has a responsibility to connect to a given peripheral and
determin which DFU implementation should be used based on the services
found on the device.
*/
internal class DFUServiceSelector : BaseDFUExecutor, DFUStarterPeripheralDelegate {
typealias DFUPeripheralType = DFUStarterPeripheral
internal let initiator: DFUServiceInitiator
internal let logger: LoggerHelper
internal let controller: DFUServiceController
internal let peripheral: DFUStarterPeripheral
internal var error: (error: DFUError, message: String)?
init(initiator: DFUServiceInitiator, controller: DFUServiceController) {
self.initiator = initiator
self.logger = LoggerHelper(initiator.logger, initiator.loggerQueue)
self.controller = controller
self.peripheral = DFUStarterPeripheral(initiator, logger)
self.peripheral.delegate = self
}
func start() {
delegate {
$0.dfuStateDidChange(to: .connecting)
}
peripheral.start()
}
func peripheralDidSelectedExecutor(_ ExecutorType: DFUExecutorAPI.Type) {
// Release the cyclic reference
peripheral.destroy()
let executor = ExecutorType.init(initiator, logger)
controller.executor = executor
executor.start()
}
}
| mit | ca289770f0610b7724d4360a809c2d2f | 43.407895 | 145 | 0.737778 | 5.265211 | false | false | false | false |
VBVMI/VerseByVerse-iOS | VBVMI/Model/Topic.swift | 1 | 1637 | import Foundation
import CoreData
import Decodable
extension String {
func latinize() -> String {
return self.folding(options: String.CompareOptions.diacriticInsensitive, locale: Locale.current)
}
func slugify(withSeparator separator: Character = "-") -> String {
let slugCharacterSet = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\(separator)")
return latinize().lowercased().components(separatedBy: slugCharacterSet.inverted).filter({ $0 != " " }).joined(separator: String(separator))
}
}
@objc(Topic)
open class Topic: _Topic {
// Custom logic goes here.
class func decodeJSON(_ JSONDict: NSDictionary, context: NSManagedObjectContext) throws -> (Topic?) {
guard let identifier = JSONDict["ID"] as? String else {
throw APIDataManagerError.missingID
}
var convertedIdentifier = identifier.replacingOccurrences(of: "+", with: " ")
convertedIdentifier = convertedIdentifier.slugify()
if convertedIdentifier.count == 0 {
return nil
}
if let name = try JSONDict => "topic" as? String , name.count > 0 {
let convertedName = name.capitalized
guard let topic = Topic.findFirstOrCreateWithDictionary(["identifier": convertedIdentifier], context: context) as? Topic else {
throw APIDataManagerError.modelCreationFailed
}
topic.identifier = convertedIdentifier
topic.name = convertedName
return topic
}
return nil
}
}
| mit | c5fc5915b6aaba9efb42cb66593059d2 | 35.377778 | 148 | 0.649359 | 5.474916 | false | false | false | false |
qingpengchen2011/BTNavigationDropdownMenu | Source/BTNavigationDropdownMenu.swift | 3 | 22439 | //
// BTConfiguration.swift
// BTNavigationDropdownMenu
//
// Created by Pham Ba Tho on 6/30/15.
// Copyright (c) 2015 PHAM BA THO. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
// MARK: BTNavigationDropdownMenu
public class BTNavigationDropdownMenu: UIView {
// The color of menu title. Default is darkGrayColor()
public var menuTitleColor: UIColor! {
get {
return self.configuration.menuTitleColor
}
set(value) {
self.configuration.menuTitleColor = value
}
}
// The height of the cell. Default is 50
public var cellHeight: CGFloat! {
get {
return self.configuration.cellHeight
}
set(value) {
self.configuration.cellHeight = value
}
}
// The color of the cell background. Default is whiteColor()
public var cellBackgroundColor: UIColor! {
get {
return self.configuration.cellBackgroundColor
}
set(color) {
self.configuration.cellBackgroundColor = color
}
}
public var cellSeparatorColor: UIColor! {
get {
return self.configuration.cellSeparatorColor
}
set(value) {
self.configuration.cellSeparatorColor = value
}
}
// The color of the text inside cell. Default is darkGrayColor()
public var cellTextLabelColor: UIColor! {
get {
return self.configuration.cellTextLabelColor
}
set(value) {
self.configuration.cellTextLabelColor = value
}
}
// The font of the text inside cell. Default is HelveticaNeue-Bold, size 19
public var cellTextLabelFont: UIFont! {
get {
return self.configuration.cellTextLabelFont
}
set(value) {
self.configuration.cellTextLabelFont = value
self.menuTitle.font = self.configuration.cellTextLabelFont
}
}
// The color of the cell when the cell is selected. Default is lightGrayColor()
public var cellSelectionColor: UIColor! {
get {
return self.configuration.cellSelectionColor
}
set(value) {
self.configuration.cellSelectionColor = value
}
}
// The checkmark icon of the cell
public var checkMarkImage: UIImage! {
get {
return self.configuration.checkMarkImage
}
set(value) {
self.configuration.checkMarkImage = value
}
}
// The animation duration of showing/hiding menu. Default is 0.3
public var animationDuration: NSTimeInterval! {
get {
return self.configuration.animationDuration
}
set(value) {
self.configuration.animationDuration = value
}
}
// The arrow next to navigation title
public var arrowImage: UIImage! {
get {
return self.configuration.arrowImage
}
set(value) {
self.configuration.arrowImage = value
self.menuArrow.image = self.configuration.arrowImage
}
}
// The padding between navigation title and arrow
public var arrowPadding: CGFloat! {
get {
return self.configuration.arrowPadding
}
set(value) {
self.configuration.arrowPadding = value
}
}
// The color of the mask layer. Default is blackColor()
public var maskBackgroundColor: UIColor! {
get {
return self.configuration.maskBackgroundColor
}
set(value) {
self.configuration.maskBackgroundColor = value
}
}
// The opacity of the mask layer. Default is 0.3
public var maskBackgroundOpacity: CGFloat! {
get {
return self.configuration.maskBackgroundOpacity
}
set(value) {
self.configuration.maskBackgroundOpacity = value
}
}
public var didSelectItemAtIndexHandler: ((indexPath: Int) -> ())?
private var navigationController: UINavigationController?
private var configuration = BTConfiguration()
private var topSeparator: UIView!
private var menuButton: UIButton!
private var menuTitle: UILabel!
private var menuArrow: UIImageView!
private var backgroundView: UIView!
private var tableView: BTTableView!
private var items: [AnyObject]!
private var isShown: Bool!
private var menuWrapper: UIView!
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public init(title: String, items: [AnyObject]) {
// Navigation controller
self.navigationController = UIApplication.sharedApplication().keyWindow?.rootViewController?.topMostViewController?.navigationController
// Get titleSize
let titleSize = (title as NSString).sizeWithAttributes([NSFontAttributeName:self.configuration.cellTextLabelFont])
// Set frame
let frame = CGRectMake(0, 0, titleSize.width + (self.configuration.arrowPadding + self.configuration.arrowImage.size.width)*2, self.navigationController!.navigationBar.frame.height)
super.init(frame:frame)
self.navigationController?.view.addObserver(self, forKeyPath: "frame", options: .New, context: nil)
self.isShown = false
self.items = items
// Init properties
self.setupDefaultConfiguration()
// Init button as navigation title
self.menuButton = UIButton(frame: frame)
self.menuButton.addTarget(self, action: "menuButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(self.menuButton)
self.menuTitle = UILabel(frame: frame)
self.menuTitle.text = title
self.menuTitle.textColor = self.menuTitleColor
self.menuTitle.textAlignment = NSTextAlignment.Center
self.menuTitle.font = self.configuration.cellTextLabelFont
self.menuButton.addSubview(self.menuTitle)
self.menuArrow = UIImageView(image: self.configuration.arrowImage)
self.menuButton.addSubview(self.menuArrow)
let window = UIApplication.sharedApplication().keyWindow!
let menuWrapperBounds = window.bounds
// Set up DropdownMenu
self.menuWrapper = UIView(frame: CGRectMake(menuWrapperBounds.origin.x, 0, menuWrapperBounds.width, menuWrapperBounds.height))
self.menuWrapper.clipsToBounds = true
self.menuWrapper.autoresizingMask = UIViewAutoresizing.FlexibleWidth.union(UIViewAutoresizing.FlexibleHeight)
// Init background view (under table view)
self.backgroundView = UIView(frame: menuWrapperBounds)
self.backgroundView.backgroundColor = self.configuration.maskBackgroundColor
self.backgroundView.autoresizingMask = UIViewAutoresizing.FlexibleWidth.union(UIViewAutoresizing.FlexibleHeight)
// Init table view
self.tableView = BTTableView(frame: CGRectMake(menuWrapperBounds.origin.x, menuWrapperBounds.origin.y + 0.5, menuWrapperBounds.width, menuWrapperBounds.height + 300), items: items, configuration: self.configuration)
self.tableView.selectRowAtIndexPathHandler = { (indexPath: Int) -> () in
self.didSelectItemAtIndexHandler!(indexPath: indexPath)
self.setMenuTitle("\(items[indexPath])")
self.hideMenu()
self.isShown = false
self.layoutSubviews()
}
// Add background view & table view to container view
self.menuWrapper.addSubview(self.backgroundView)
self.menuWrapper.addSubview(self.tableView)
// Add Line on top
self.topSeparator = UIView(frame: CGRectMake(0, 0, menuWrapperBounds.size.width, 0.5))
self.topSeparator.autoresizingMask = UIViewAutoresizing.FlexibleWidth
self.menuWrapper.addSubview(self.topSeparator)
// Add Menu View to container view
window.addSubview(self.menuWrapper)
// By default, hide menu view
self.menuWrapper.hidden = true
}
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "frame" {
// Set up DropdownMenu
self.menuWrapper.frame.origin.y = self.navigationController!.navigationBar.frame.maxY
self.tableView.reloadData()
}
}
override public func layoutSubviews() {
self.menuTitle.sizeToFit()
self.menuTitle.center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2)
self.menuArrow.sizeToFit()
self.menuArrow.center = CGPointMake(CGRectGetMaxX(self.menuTitle.frame) + self.configuration.arrowPadding, self.frame.size.height/2)
}
func setupDefaultConfiguration() {
self.menuTitleColor = self.navigationController?.navigationBar.titleTextAttributes?[NSForegroundColorAttributeName] as? UIColor // Setter
self.cellBackgroundColor = self.navigationController?.navigationBar.barTintColor
self.cellSeparatorColor = self.navigationController?.navigationBar.titleTextAttributes?[NSForegroundColorAttributeName] as? UIColor
self.cellTextLabelColor = self.navigationController?.navigationBar.titleTextAttributes?[NSForegroundColorAttributeName] as? UIColor
}
func showMenu() {
self.menuWrapper.frame.origin.y = self.navigationController!.navigationBar.frame.maxY
// Table view header
let headerView = UIView(frame: CGRectMake(0, 0, self.frame.width, 300))
headerView.backgroundColor = self.configuration.cellBackgroundColor
self.tableView.tableHeaderView = headerView
self.topSeparator.backgroundColor = self.configuration.cellSeparatorColor
// Rotate arrow
self.rotateArrow()
// Visible menu view
self.menuWrapper.hidden = false
// Change background alpha
self.backgroundView.alpha = 0
// Animation
self.tableView.frame.origin.y = -CGFloat(self.items.count) * self.configuration.cellHeight - 300
// Reload data to dismiss highlight color of selected cell
self.tableView.reloadData()
UIView.animateWithDuration(
self.configuration.animationDuration * 1.5,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.5,
options: [],
animations: {
self.tableView.frame.origin.y = CGFloat(-300)
self.backgroundView.alpha = self.configuration.maskBackgroundOpacity
}, completion: nil
)
}
func hideMenu() {
// Rotate arrow
self.rotateArrow()
// Change background alpha
self.backgroundView.alpha = self.configuration.maskBackgroundOpacity
UIView.animateWithDuration(
self.configuration.animationDuration * 1.5,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.5,
options: [],
animations: {
self.tableView.frame.origin.y = CGFloat(-200)
}, completion: nil
)
// Animation
UIView.animateWithDuration(self.configuration.animationDuration, delay: 0, options: UIViewAnimationOptions.TransitionNone, animations: {
self.tableView.frame.origin.y = -CGFloat(self.items.count) * self.configuration.cellHeight - 300
self.backgroundView.alpha = 0
}, completion: { _ in
self.menuWrapper.hidden = true
})
}
func rotateArrow() {
UIView.animateWithDuration(self.configuration.animationDuration, animations: {[weak self] () -> () in
if let selfie = self {
selfie.menuArrow.transform = CGAffineTransformRotate(selfie.menuArrow.transform, 180 * CGFloat(M_PI/180))
}
})
}
func setMenuTitle(title: String) {
self.menuTitle.text = title
}
func menuButtonTapped(sender: UIButton) {
self.isShown = !self.isShown
if self.isShown == true {
self.showMenu()
} else {
self.hideMenu()
}
}
}
// MARK: BTConfiguration
class BTConfiguration {
var menuTitleColor: UIColor?
var cellHeight: CGFloat!
var cellBackgroundColor: UIColor?
var cellSeparatorColor: UIColor?
var cellTextLabelColor: UIColor?
var cellTextLabelFont: UIFont!
var cellSelectionColor: UIColor?
var checkMarkImage: UIImage!
var arrowImage: UIImage!
var arrowPadding: CGFloat!
var animationDuration: NSTimeInterval!
var maskBackgroundColor: UIColor!
var maskBackgroundOpacity: CGFloat!
init() {
self.defaultValue()
}
func defaultValue() {
// Path for image
let bundle = NSBundle(forClass: BTConfiguration.self)
let url = bundle.URLForResource("BTNavigationDropdownMenu", withExtension: "bundle")
let imageBundle = NSBundle(URL: url!)
let checkMarkImagePath = imageBundle?.pathForResource("checkmark_icon", ofType: "png")
let arrowImagePath = imageBundle?.pathForResource("arrow_down_icon", ofType: "png")
// Default values
self.menuTitleColor = UIColor.darkGrayColor()
self.cellHeight = 50
self.cellBackgroundColor = UIColor.whiteColor()
self.cellSeparatorColor = UIColor.darkGrayColor()
self.cellTextLabelColor = UIColor.darkGrayColor()
self.cellTextLabelFont = UIFont(name: "HelveticaNeue-Bold", size: 17)
self.cellSelectionColor = UIColor.lightGrayColor()
self.checkMarkImage = UIImage(contentsOfFile: checkMarkImagePath!)
self.animationDuration = 0.5
self.arrowImage = UIImage(contentsOfFile: arrowImagePath!)
self.arrowPadding = 15
self.maskBackgroundColor = UIColor.blackColor()
self.maskBackgroundOpacity = 0.3
}
}
// MARK: Table View
class BTTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
// Public properties
var configuration: BTConfiguration!
var selectRowAtIndexPathHandler: ((indexPath: Int) -> ())?
// Private properties
private var items: [AnyObject]!
private var selectedIndexPath: Int!
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(frame: CGRect, items: [AnyObject], configuration: BTConfiguration) {
super.init(frame: frame, style: UITableViewStyle.Plain)
self.items = items
self.selectedIndexPath = 0
self.configuration = configuration
// Setup table view
self.delegate = self
self.dataSource = self
self.backgroundColor = UIColor.clearColor()
self.separatorStyle = UITableViewCellSeparatorStyle.None
self.autoresizingMask = UIViewAutoresizing.FlexibleWidth
self.tableFooterView = UIView(frame: CGRectZero)
}
// Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return self.configuration.cellHeight
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = BTTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell", configuration: self.configuration)
cell.textLabel?.text = self.items[indexPath.row] as? String
cell.checkmarkIcon.hidden = (indexPath.row == selectedIndexPath) ? false : true
return cell
}
// Table view delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedIndexPath = indexPath.row
self.selectRowAtIndexPathHandler!(indexPath: indexPath.row)
self.reloadData()
let cell = tableView.cellForRowAtIndexPath(indexPath) as? BTTableViewCell
cell?.contentView.backgroundColor = self.configuration.cellSelectionColor
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath) as? BTTableViewCell
cell?.checkmarkIcon.hidden = true
cell?.contentView.backgroundColor = self.configuration.cellBackgroundColor
}
}
// MARK: Table view cell
class BTTableViewCell: UITableViewCell {
var checkmarkIcon: UIImageView!
var cellContentFrame: CGRect!
var configuration: BTConfiguration!
init(style: UITableViewCellStyle, reuseIdentifier: String?, configuration: BTConfiguration) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.configuration = configuration
// Setup cell
cellContentFrame = CGRectMake(0, 0, (UIApplication.sharedApplication().keyWindow?.frame.width)!, self.configuration.cellHeight)
self.contentView.backgroundColor = self.configuration.cellBackgroundColor
self.selectionStyle = UITableViewCellSelectionStyle.None
self.textLabel!.textAlignment = NSTextAlignment.Left
self.textLabel!.textColor = self.configuration.cellTextLabelColor
self.textLabel!.font = self.configuration.cellTextLabelFont
self.textLabel!.frame = CGRectMake(20, 0, cellContentFrame.width, cellContentFrame.height)
// Checkmark icon
self.checkmarkIcon = UIImageView(frame: CGRectMake(cellContentFrame.width - 50, (cellContentFrame.height - 30)/2, 30, 30))
self.checkmarkIcon.hidden = true
self.checkmarkIcon.image = self.configuration.checkMarkImage
self.checkmarkIcon.contentMode = UIViewContentMode.ScaleAspectFill
self.contentView.addSubview(self.checkmarkIcon)
// Separator for cell
let separator = BTTableCellContentView(frame: cellContentFrame)
if let cellSeparatorColor = self.configuration.cellSeparatorColor {
separator.separatorColor = cellSeparatorColor
}
self.contentView.addSubview(separator)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
self.bounds = cellContentFrame
self.contentView.frame = self.bounds
}
}
// Content view of table view cell
class BTTableCellContentView: UIView {
var separatorColor: UIColor = UIColor.blackColor()
override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
func initialize() {
self.backgroundColor = UIColor.clearColor()
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
let context = UIGraphicsGetCurrentContext()
// Set separator color of dropdown menu based on barStyle
CGContextSetStrokeColorWithColor(context, self.separatorColor.CGColor)
CGContextSetLineWidth(context, 1)
CGContextMoveToPoint(context, 0, self.bounds.size.height)
CGContextAddLineToPoint(context, self.bounds.size.width, self.bounds.size.height)
CGContextStrokePath(context)
}
}
extension UIViewController {
// Get ViewController in top present level
var topPresentedViewController: UIViewController? {
var target: UIViewController? = self
while (target?.presentedViewController != nil) {
target = target?.presentedViewController
}
return target
}
// Get top VisibleViewController from ViewController stack in same present level.
// It should be visibleViewController if self is a UINavigationController instance
// It should be selectedViewController if self is a UITabBarController instance
var topVisibleViewController: UIViewController? {
if let navigation = self as? UINavigationController {
if let visibleViewController = navigation.visibleViewController {
return visibleViewController.topVisibleViewController
}
}
if let tab = self as? UITabBarController {
if let selectedViewController = tab.selectedViewController {
return selectedViewController.topVisibleViewController
}
}
return self
}
// Combine both topPresentedViewController and topVisibleViewController methods, to get top visible viewcontroller in top present level
var topMostViewController: UIViewController? {
return self.topPresentedViewController?.topVisibleViewController
}
}
| mit | 47c39ec9953ca589f4ac44d2a7f7061e | 37.032203 | 223 | 0.663131 | 5.537759 | false | true | false | false |
tmozii1/tripbee | tripbee/AppDelegate.swift | 1 | 6092 | //
// AppDelegate.swift
// tripbee
//
// Created by ParkJH on 2015. 10. 22..
// Copyright © 2015년 timworld. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "kr.co.timworld.tripbee" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("tripbee", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | cf2f7727395b761f3fa7e4f42a806ecf | 53.855856 | 291 | 0.719001 | 5.877413 | false | false | false | false |
zhangao0086/DKImagePickerController | Sources/DKImageDataManager/DKImageDataManager.swift | 1 | 14162 | //
// DKImageDataManager.swift
// DKImagePickerController
//
// Created by ZhangAo on 15/11/29.
// Copyright © 2015年 ZhangAo. All rights reserved.
//
import UIKit
import Photos
public typealias DKImageRequestID = Int32
public let DKImageInvalidRequestID: DKImageRequestID = 0
public func getImageDataManager() -> DKImageDataManager {
return DKImageDataManager.sharedInstance
}
public class DKImageDataManager {
public class func checkPhotoPermission(_ handler: @escaping (_ granted: Bool) -> Void) {
func hasPhotoPermission() -> Bool {
return PHPhotoLibrary.authorizationStatus() == .authorized
}
func needsToRequestPhotoPermission() -> Bool {
return PHPhotoLibrary.authorizationStatus() == .notDetermined
}
hasPhotoPermission() ? handler(true) : (needsToRequestPhotoPermission() ?
PHPhotoLibrary.requestAuthorization({ status in
DispatchQueue.main.async(execute: { () in
hasPhotoPermission() ? handler(true) : handler(false)
})
}) : handler(false))
}
static let sharedInstance = DKImageDataManager()
private let manager = PHCachingImageManager()
private lazy var imageRequestOptions: PHImageRequestOptions = {
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
return options
}()
private lazy var videoRequestOptions: PHVideoRequestOptions = {
let options = PHVideoRequestOptions()
options.deliveryMode = .mediumQualityFormat
options.isNetworkAccessAllowed = true
return options
}()
@discardableResult
public func fetchImage(for asset: DKAsset,
size: CGSize,
options: PHImageRequestOptions? = nil,
contentMode: PHImageContentMode = .aspectFill,
completeBlock: @escaping (_ image: UIImage?, _ info: [AnyHashable: Any]?) -> Void) -> DKImageRequestID {
return self.fetchImage(for: asset,
size: size,
options: options,
contentMode: contentMode,
oldRequestID: nil,
completeBlock: completeBlock)
}
@discardableResult
private func fetchImage(for asset: DKAsset,
size: CGSize,
options: PHImageRequestOptions?,
contentMode: PHImageContentMode,
oldRequestID: DKImageRequestID?,
completeBlock: @escaping (_ image: UIImage?, _ info: [AnyHashable: Any]?) -> Void) -> DKImageRequestID {
let requestID = oldRequestID ?? self.getSeed()
guard let originalAsset = asset.originalAsset else {
assertionFailure("Expect originalAsset")
completeBlock(nil, nil)
return requestID
}
let requestOptions = options ?? self.imageRequestOptions
let imageRequestID = self.manager.requestImage(
for: originalAsset,
targetSize: size,
contentMode: contentMode,
options: requestOptions,
resultHandler: { image, info in
self.update(requestID: requestID, with: info)
if let info = info, let isCancelled = info[PHImageCancelledKey] as? NSNumber, isCancelled.boolValue {
completeBlock(image, info)
return
}
if let isInCloud = info?[PHImageResultIsInCloudKey] as AnyObject?,
image == nil,
isInCloud.boolValue,
!requestOptions.isNetworkAccessAllowed {
if self.cancelledRequestIDs.contains(requestID) {
self.cancelledRequestIDs.remove(requestID)
completeBlock(nil, [PHImageCancelledKey : NSNumber(value: 1)])
return
}
guard let requestCloudOptions = requestOptions.copy() as? PHImageRequestOptions else {
assertionFailure("Expect PHImageRequestOptions")
completeBlock(nil, nil)
return
}
requestCloudOptions.isNetworkAccessAllowed = true
self.fetchImage(for: asset,
size: size,
options: requestCloudOptions,
contentMode: contentMode,
oldRequestID: requestID,
completeBlock: completeBlock)
} else {
completeBlock(image, info)
}
})
self.update(requestID: requestID, with: imageRequestID, old: oldRequestID)
return requestID
}
@discardableResult
public func fetchImageData(for asset: DKAsset, options: PHImageRequestOptions? = nil, completeBlock: @escaping (_ data: Data?, _ info: [AnyHashable: Any]?) -> Void) -> DKImageRequestID {
return self.fetchImageData(for: asset, options: options, oldRequestID: nil, completeBlock: completeBlock)
}
@discardableResult
private func fetchImageData(for asset: DKAsset,
options: PHImageRequestOptions?,
oldRequestID: DKImageRequestID?,
completeBlock: @escaping (_ data: Data?, _ info: [AnyHashable: Any]?) -> Void)
-> DKImageRequestID
{
let requestID = oldRequestID ?? self.getSeed()
guard let originalAsset = asset.originalAsset else {
assertionFailure("Expect originalAsset")
completeBlock(nil, nil)
return requestID
}
let requestOptions = options ?? self.imageRequestOptions
let imageRequestID = self.manager.requestImageData(
for: originalAsset,
options: requestOptions) { (data, dataUTI, orientation, info) in
self.update(requestID: requestID, with: info)
if let info = info, let isCancelled = info[PHImageCancelledKey] as? NSNumber, isCancelled.boolValue {
completeBlock(data, info)
return
}
if let isInCloud = info?[PHImageResultIsInCloudKey] as AnyObject?,
data == nil,
isInCloud.boolValue,
!requestOptions.isNetworkAccessAllowed
{
if self.cancelledRequestIDs.contains(requestID) {
self.cancelledRequestIDs.remove(requestID)
completeBlock(nil, [PHImageCancelledKey : NSNumber(value: 1)])
return
}
guard let requestCloudOptions = requestOptions.copy() as? PHImageRequestOptions else {
assertionFailure("Expect PHImageRequestOptions")
completeBlock(nil, nil)
return
}
requestCloudOptions.isNetworkAccessAllowed = true
self.fetchImageData(for: asset, options: requestCloudOptions, oldRequestID: requestID, completeBlock: completeBlock)
} else {
completeBlock(data, info)
}
}
self.update(requestID: requestID, with: imageRequestID, old: oldRequestID)
return requestID
}
@discardableResult
public func fetchAVAsset(for asset: DKAsset, options: PHVideoRequestOptions? = nil, completeBlock: @escaping (_ avAsset: AVAsset?, _ info: [AnyHashable: Any]?) -> Void) -> DKImageRequestID {
return self.fetchAVAsset(for: asset, options: options, oldRequestID: nil, completeBlock: completeBlock)
}
@discardableResult
private func fetchAVAsset(for asset: DKAsset,
options: PHVideoRequestOptions?,
oldRequestID: DKImageRequestID?,
completeBlock: @escaping (_ avAsset: AVAsset?, _ info: [AnyHashable: Any]?) -> Void)
-> DKImageRequestID
{
let requestID = oldRequestID ?? self.getSeed()
guard let originalAsset = asset.originalAsset else {
assertionFailure("Expect originalAsset")
completeBlock(nil, nil)
return requestID
}
let requestOptions = options ?? self.videoRequestOptions
let imageRequestID = self.manager.requestAVAsset(
forVideo: originalAsset,
options: requestOptions) { avAsset, audioMix, info in
self.update(requestID: requestID, with: info)
if let info = info, let isCancelled = info[PHImageCancelledKey] as? NSNumber, isCancelled.boolValue {
completeBlock(avAsset, info)
return
}
if let isInCloud = info?[PHImageResultIsInCloudKey] as AnyObject?,
avAsset == nil,
isInCloud.boolValue,
!requestOptions.isNetworkAccessAllowed
{
if self.cancelledRequestIDs.contains(requestID) {
self.cancelledRequestIDs.remove(requestID)
completeBlock(nil, [PHImageCancelledKey : NSNumber(value: 1)])
return
}
guard let requestCloudOptions = requestOptions.copy() as? PHVideoRequestOptions else {
assertionFailure("Expect PHImageRequestOptions")
completeBlock(nil, nil)
return
}
requestCloudOptions.isNetworkAccessAllowed = true
self.fetchAVAsset(for: asset, options: requestCloudOptions, oldRequestID: requestID, completeBlock: completeBlock)
} else {
completeBlock(avAsset, info)
}
}
self.update(requestID: requestID, with: imageRequestID, old: oldRequestID)
return requestID
}
public func cancelRequest(requestID: DKImageRequestID) {
self.cancelRequests(requestIDs: [requestID])
}
public func cancelRequests(requestIDs: [DKImageRequestID]) {
self.executeOnMainThread {
while self.cancelledRequestIDs.count > 100 {
let _ = self.cancelledRequestIDs.popFirst()
}
for requestID in requestIDs {
if let imageRequestID = self.requestIDs[requestID] {
self.manager.cancelImageRequest(imageRequestID)
self.cancelledRequestIDs.insert(requestID)
}
self.requestIDs[requestID] = nil
}
}
}
public func startCachingAssets(for assets: [PHAsset], targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?) {
self.manager.startCachingImages(for: assets, targetSize: targetSize, contentMode: contentMode, options: options)
}
public func stopCachingAssets(for assets: [PHAsset], targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?) {
self.manager.stopCachingImages(for: assets, targetSize: targetSize, contentMode: contentMode, options: options)
}
public func stopCachingForAllAssets() {
self.manager.stopCachingImagesForAllAssets()
}
// MARK: - RequestID
private var requestIDs = [DKImageRequestID : PHImageRequestID]()
private var finishedRequestIDs = Set<DKImageRequestID>()
private var cancelledRequestIDs = Set<DKImageRequestID>()
private var seed: DKImageRequestID = 0
private func getSeed() -> DKImageRequestID {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
seed += 1
return seed
}
private func update(requestID: DKImageRequestID,
with imageRequestID: PHImageRequestID?,
old oldImageRequestID: DKImageRequestID?) {
self.executeOnMainThread {
if let imageRequestID = imageRequestID {
if self.cancelledRequestIDs.contains(requestID) {
self.cancelledRequestIDs.remove(requestID)
self.manager.cancelImageRequest(imageRequestID)
} else {
if self.finishedRequestIDs.contains(requestID) {
self.finishedRequestIDs.remove(requestID)
} else {
self.requestIDs[requestID] = imageRequestID
}
}
} else {
self.requestIDs[requestID] = nil
}
}
}
private func update(requestID: DKImageRequestID, with info: [AnyHashable : Any]?) {
guard let info = info else { return }
if let isCancelled = info[PHImageCancelledKey] as? NSNumber, isCancelled.boolValue {
self.executeOnMainThread {
self.requestIDs[requestID] = nil
self.cancelledRequestIDs.remove(requestID)
}
} else if let isDegraded = (info[PHImageResultIsDegradedKey] as? NSNumber)?.boolValue {
if !isDegraded { // No more callbacks for the requested image.
self.executeOnMainThread {
if self.requestIDs[requestID] == nil {
self.finishedRequestIDs.insert(requestID)
} else {
self.requestIDs[requestID] = nil
}
}
}
}
}
private func executeOnMainThread(block: @escaping (() -> Void)) {
if Thread.isMainThread {
block()
} else {
DispatchQueue.main.async(execute: block)
}
}
}
| mit | 026ea7265d3f193af3100cf5fa8f4db3 | 39.454286 | 194 | 0.56593 | 6.301291 | false | false | false | false |
rockgarden/swift_language | Playground/FibonacciSequence.playground/Pages/FibonacciSequence.xcplaygroundpage/Contents.swift | 2 | 2673 | // Thinkful Playground
// Thinkful.com
// Fibonacci Sequence
// By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.
class FibonacciSequence {
let includesZero: Bool
let values: [UInt]
init(maxNumber: UInt, includesZero: Bool) {
self.includesZero = includesZero
if maxNumber == 0 && includesZero == false {
values = []
} else if maxNumber == 0 {
values = [0]
} else {
var sequence: [UInt] = [0,1,1]
var nextNumber: UInt = 2
while nextNumber <= maxNumber {
sequence.append(nextNumber)
let lastNumber = sequence.last!
let secondToLastNumber = sequence[sequence.count-2]
let (sum, didOverflow) = UInt.addWithOverflow(lastNumber, secondToLastNumber)
if didOverflow == true {
print("Overflow! The next number is too big to store in a UInt!")
break
}
nextNumber = sum
}
if includesZero == false {
sequence.remove(at: 0)
}
values = sequence
}
}
init(numberOfItemsInSequence: UInt, includesZero: Bool) {
self.includesZero = includesZero
if numberOfItemsInSequence == 0 {
values = []
} else if numberOfItemsInSequence == 1 {
if includesZero == true {
values = [0]
} else {
values = [1]
}
} else {
var sequence: [UInt]
if includesZero == true {
sequence = [0,1]
} else {
sequence = [1,1]
}
for _ in 2 ..< Int(numberOfItemsInSequence) {
let lastNumber = sequence.last!
let secondToLastNumber = sequence[sequence.count-2]
let (nextNumber, didOverflow) = UInt.addWithOverflow(lastNumber, secondToLastNumber)
if didOverflow == true {
print("Overflow! The next number is too big to store in a UInt!")
break
}
sequence.append(nextNumber)
}
values = sequence
}
}
}
let fibonacciSequence = FibonacciSequence(maxNumber:12345, includesZero: true)
print(fibonacciSequence.values)
let anotherSequence = FibonacciSequence(numberOfItemsInSequence: 113, includesZero: true)
print(anotherSequence.values)
UInt.max
| mit | 83fb0e19f8ecb66b758bd00b15ac3023 | 32.4125 | 205 | 0.542462 | 5.033898 | false | false | false | false |
abbeycode/Carthage | Source/CarthageKit/Project.swift | 1 | 25270 | //
// Project.swift
// Carthage
//
// Created by Alan Rogers on 12/10/2014.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Foundation
import Result
import ReactiveCocoa
/// Carthage’s bundle identifier.
public let CarthageKitBundleIdentifier = NSBundle(forClass: Project.self).bundleIdentifier!
/// ~/Library/Caches/org.carthage.CarthageKit/
private let CarthageUserCachesURL: NSURL = {
let URL: Result<NSURL, NSError> = try({ (error: NSErrorPointer) -> NSURL? in
NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.CachesDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: true, error: error)
})
let fallbackDependenciesURL = NSURL.fileURLWithPath("~/.carthage".stringByExpandingTildeInPath, isDirectory:true)!
switch URL {
case .Success:
NSFileManager.defaultManager().removeItemAtURL(fallbackDependenciesURL, error: nil)
case let .Failure(error):
NSLog("Warning: No Caches directory could be found or created: \(error.value.localizedDescription). (\(error.value))")
}
return URL.value?.URLByAppendingPathComponent(CarthageKitBundleIdentifier, isDirectory: true) ?? fallbackDependenciesURL
}()
/// The file URL to the directory in which downloaded release binaries will be
/// stored.
///
/// ~/Library/Caches/org.carthage.CarthageKit/binaries/
public let CarthageDependencyAssetsURL = CarthageUserCachesURL.URLByAppendingPathComponent("binaries", isDirectory: true)
/// The file URL to the directory in which cloned dependencies will be stored.
///
/// ~/Library/Caches/org.carthage.CarthageKit/dependencies/
public let CarthageDependencyRepositoriesURL = CarthageUserCachesURL.URLByAppendingPathComponent("dependencies", isDirectory: true)
/// The relative path to a project's Cartfile.
public let CarthageProjectCartfilePath = "Cartfile"
/// The relative path to a project's Cartfile.private.
public let CarthageProjectPrivateCartfilePath = "Cartfile.private"
/// The relative path to a project's Cartfile.resolved.
public let CarthageProjectResolvedCartfilePath = "Cartfile.resolved"
/// The text that needs to exist in a GitHub Release asset's name, for it to be
/// tried as a binary framework.
public let CarthageProjectBinaryAssetPattern = ".framework"
/// MIME types allowed for GitHub Release assets, for them to be considered as
/// binary frameworks.
public let CarthageProjectBinaryAssetContentTypes = [
"application/zip"
]
/// Describes an event occurring to or with a project.
public enum ProjectEvent {
/// The project is beginning to clone.
case Cloning(ProjectIdentifier)
/// The project is beginning a fetch.
case Fetching(ProjectIdentifier)
/// The project is being checked out to the specified revision.
case CheckingOut(ProjectIdentifier, String)
/// Any available binaries for the specified release of the project are
/// being downloaded. This may still be followed by `CheckingOut` event if
/// there weren't any viable binaries after all.
case DownloadingBinaries(ProjectIdentifier, String)
}
/// Represents a project that is using Carthage.
public final class Project {
/// File URL to the root directory of the project.
public let directoryURL: NSURL
/// The file URL to the project's Cartfile.
public var cartfileURL: NSURL {
return directoryURL.URLByAppendingPathComponent(CarthageProjectCartfilePath, isDirectory: false)
}
/// The file URL to the project's Cartfile.resolved.
public var resolvedCartfileURL: NSURL {
return directoryURL.URLByAppendingPathComponent(CarthageProjectResolvedCartfilePath, isDirectory: false)
}
/// Whether to prefer HTTPS for cloning (vs. SSH).
public var preferHTTPS = true
/// Whether to use submodules for dependencies, or just check out their
/// working directories.
public var useSubmodules = false
/// Whether to download binaries for dependencies, or just check out their
/// repositories.
public var useBinaries = false
/// Sends each event that occurs to a project underneath the receiver (or
/// the receiver itself).
public let projectEvents: Signal<ProjectEvent, NoError>
private let _projectEventsObserver: Signal<ProjectEvent, NoError>.Observer
public init(directoryURL: NSURL) {
precondition(directoryURL.fileURL)
let (signal, observer) = Signal<ProjectEvent, NoError>.pipe()
projectEvents = signal
_projectEventsObserver = observer
self.directoryURL = directoryURL
}
deinit {
sendCompleted(_projectEventsObserver)
}
private typealias CachedVersions = [ProjectIdentifier: [PinnedVersion]]
/// Caches versions to avoid expensive lookups, and unnecessary
/// fetching/cloning.
private var cachedVersions: CachedVersions = [:]
private let cachedVersionsQueue = ProducerQueue(name: "org.carthage.CarthageKit.Project.cachedVersionsQueue")
/// Attempts to load Cartfile or Cartfile.private from the given directory,
/// merging their dependencies.
public func loadCombinedCartfile() -> SignalProducer<Cartfile, CarthageError> {
let cartfileURL = directoryURL.URLByAppendingPathComponent(CarthageProjectCartfilePath, isDirectory: false)
let privateCartfileURL = directoryURL.URLByAppendingPathComponent(CarthageProjectPrivateCartfilePath, isDirectory: false)
let isNoSuchFileError = { (error: CarthageError) -> Bool in
switch error {
case let .ReadFailed(_, underlyingError):
if let underlyingError = underlyingError {
return underlyingError.domain == NSCocoaErrorDomain && underlyingError.code == NSFileReadNoSuchFileError
} else {
return false
}
default:
return false
}
}
let cartfile = SignalProducer.try {
return Cartfile.fromFile(cartfileURL)
}
|> catch { error -> SignalProducer<Cartfile, CarthageError> in
if isNoSuchFileError(error) && NSFileManager.defaultManager().fileExistsAtPath(privateCartfileURL.path!) {
return SignalProducer(value: Cartfile())
}
return SignalProducer(error: error)
}
let privateCartfile = SignalProducer.try {
return Cartfile.fromFile(privateCartfileURL)
}
|> catch { error -> SignalProducer<Cartfile, CarthageError> in
if isNoSuchFileError(error) {
return SignalProducer(value: Cartfile())
}
return SignalProducer(error: error)
}
return cartfile
|> zipWith(privateCartfile)
|> tryMap { (var cartfile, privateCartfile) -> Result<Cartfile, CarthageError> in
let duplicateDeps = cartfile.duplicateProjects().map { DuplicateDependency(project: $0, locations: ["\(CarthageProjectCartfilePath)"]) }
+ privateCartfile.duplicateProjects().map { DuplicateDependency(project: $0, locations: ["\(CarthageProjectPrivateCartfilePath)"]) }
+ duplicateProjectsInCartfiles(cartfile, privateCartfile).map { DuplicateDependency(project: $0, locations: ["\(CarthageProjectCartfilePath)", "\(CarthageProjectPrivateCartfilePath)"]) }
if duplicateDeps.count == 0 {
cartfile.appendCartfile(privateCartfile)
return .success(cartfile)
}
return .failure(.DuplicateDependencies(duplicateDeps))
}
}
/// Reads the project's Cartfile.resolved.
public func loadResolvedCartfile() -> SignalProducer<ResolvedCartfile, CarthageError> {
return SignalProducer.try {
var error: NSError?
let resolvedCartfileContents = NSString(contentsOfURL: self.resolvedCartfileURL, encoding: NSUTF8StringEncoding, error: &error)
if let resolvedCartfileContents = resolvedCartfileContents {
return ResolvedCartfile.fromString(resolvedCartfileContents as String)
} else {
return .failure(.ReadFailed(self.resolvedCartfileURL, error))
}
}
}
/// Writes the given Cartfile.resolved out to the project's directory.
public func writeResolvedCartfile(resolvedCartfile: ResolvedCartfile) -> Result<(), CarthageError> {
var error: NSError?
if resolvedCartfile.description.writeToURL(resolvedCartfileURL, atomically: true, encoding: NSUTF8StringEncoding, error: &error) {
return .success(())
} else {
return .failure(.WriteFailed(resolvedCartfileURL, error))
}
}
private let gitOperationQueue = ProducerQueue(name: "org.carthage.CarthageKit.Project.gitOperationQueue")
/// Clones the given dependency to the global repositories folder, or fetches
/// inside it if it has already been cloned.
///
/// Returns a signal which will send the URL to the repository's folder on
/// disk once cloning or fetching has completed.
private func cloneOrFetchDependency(project: ProjectIdentifier) -> SignalProducer<NSURL, CarthageError> {
return cloneOrFetchProject(project, preferHTTPS: self.preferHTTPS)
|> on(next: { event, _ in
sendNext(self._projectEventsObserver, event)
})
|> map { _, URL in URL }
|> takeLast(1)
|> startOnQueue(gitOperationQueue)
}
/// Sends all versions available for the given project.
///
/// This will automatically clone or fetch the project's repository as
/// necessary.
private func versionsForProject(project: ProjectIdentifier) -> SignalProducer<PinnedVersion, CarthageError> {
let fetchVersions = cloneOrFetchDependency(project)
|> flatMap(.Merge) { repositoryURL in listTags(repositoryURL) }
|> map { PinnedVersion($0) }
|> collect
|> on(next: { newVersions in
self.cachedVersions[project] = newVersions
})
|> flatMap(.Concat) { versions in SignalProducer(values: versions) }
return SignalProducer.try {
return .success(self.cachedVersions)
}
|> promoteErrors(CarthageError.self)
|> flatMap(.Merge) { versionsByProject -> SignalProducer<PinnedVersion, CarthageError> in
if let versions = versionsByProject[project] {
return SignalProducer(values: versions)
} else {
return fetchVersions
}
}
|> startOnQueue(cachedVersionsQueue)
}
/// Attempts to resolve a Git reference to a version.
private func resolvedGitReference(project: ProjectIdentifier, reference: String) -> SignalProducer<PinnedVersion, CarthageError> {
// We don't need the version list, but this takes care of
// cloning/fetching for us, while avoiding duplication.
return versionsForProject(project)
|> then(resolveReferenceInRepository(repositoryFileURLForProject(project), reference))
|> map { PinnedVersion($0) }
}
/// Attempts to determine the latest satisfiable version of the project's
/// Carthage dependencies.
///
/// This will fetch dependency repositories as necessary, but will not check
/// them out into the project's working directory.
public func updatedResolvedCartfile() -> SignalProducer<ResolvedCartfile, CarthageError> {
let resolver = Resolver(versionsForDependency: versionsForProject, cartfileForDependency: cartfileForDependency, resolvedGitReference: resolvedGitReference)
return loadCombinedCartfile()
|> flatMap(.Merge) { cartfile in resolver.resolveDependenciesInCartfile(cartfile) }
|> collect
|> map { ResolvedCartfile(dependencies: $0) }
}
/// Updates the dependencies of the project to the latest version. The
/// changes will be reflected in the working directory checkouts and
/// Cartfile.resolved.
public func updateDependencies() -> SignalProducer<(), CarthageError> {
return updatedResolvedCartfile()
|> tryMap { resolvedCartfile -> Result<(), CarthageError> in
return self.writeResolvedCartfile(resolvedCartfile)
}
|> then(checkoutResolvedDependencies())
}
/// Installs binaries for the given project, if available.
///
/// Sends a boolean indicating whether binaries were installed.
private func installBinariesForProject(project: ProjectIdentifier, atRevision revision: String) -> SignalProducer<Bool, CarthageError> {
return SignalProducer.try {
return .success(self.useBinaries)
}
|> flatMap(.Merge) { useBinaries -> SignalProducer<Bool, CarthageError> in
if !useBinaries {
return SignalProducer(value: false)
}
let checkoutDirectoryURL = self.directoryURL.URLByAppendingPathComponent(project.relativePath, isDirectory: true)
switch project {
case let .GitHub(repository):
return GitHubCredentials.loadFromGit()
|> flatMap(.Concat) { credentials in
return self.downloadMatchingBinariesForProject(project, atRevision: revision, fromRepository: repository, withCredentials: credentials)
|> catch { error in
if credentials == nil {
return SignalProducer(error: error)
}
return self.downloadMatchingBinariesForProject(project, atRevision: revision, fromRepository: repository, withCredentials: nil)
}
}
|> flatMap(.Concat, unzipArchiveToTemporaryDirectory)
|> flatMap(.Concat) { directoryURL in
return frameworksInDirectory(directoryURL)
|> flatMap(.Merge, self.copyFrameworkToBuildFolder)
|> on(completed: {
_ = NSFileManager.defaultManager().trashItemAtURL(checkoutDirectoryURL, resultingItemURL: nil, error: nil)
})
|> then(SignalProducer(value: directoryURL))
}
|> tryMap { (temporaryDirectoryURL: NSURL) -> Result<Bool, CarthageError> in
var error: NSError?
if NSFileManager.defaultManager().removeItemAtURL(temporaryDirectoryURL, error: &error) {
return .success(true)
} else {
return .failure(.WriteFailed(temporaryDirectoryURL, error))
}
}
|> concat(SignalProducer(value: false))
|> take(1)
case .Git:
return SignalProducer(value: false)
}
}
}
/// Downloads any binaries that may be able to be used instead of a
/// repository checkout.
///
/// Sends the URL to each downloaded zip, after it has been moved to a
/// less temporary location.
private func downloadMatchingBinariesForProject(project: ProjectIdentifier, atRevision revision: String, fromRepository repository: GitHubRepository, withCredentials credentials: GitHubCredentials?) -> SignalProducer<NSURL, CarthageError> {
return releaseForTag(revision, repository, credentials)
|> filter(binaryFrameworksCanBeProvidedByRelease)
|> on(next: { release in
sendNext(self._projectEventsObserver, ProjectEvent.DownloadingBinaries(project, release.nameWithFallback))
})
|> flatMap(.Concat) { release -> SignalProducer<NSURL, CarthageError> in
return SignalProducer(values: release.assets)
|> filter(binaryFrameworksCanBeProvidedByAsset)
|> flatMap(.Concat) { asset -> SignalProducer<NSURL, CarthageError> in
let fileURL = fileURLToCachedBinary(project, release, asset)
if NSFileManager.defaultManager().fileExistsAtPath(fileURL.path!) {
return SignalProducer(value: fileURL)
} else {
return downloadAsset(asset, credentials)
|> flatMap(.Concat) { downloadURL in cacheDownloadedBinary(downloadURL, toURL: fileURL) }
}
}
}
}
/// Copies the framework at the given URL into the current project's build
/// folder.
///
/// Sends the URL to the framework after copying.
private func copyFrameworkToBuildFolder(frameworkURL: NSURL) -> SignalProducer<NSURL, CarthageError> {
return architecturesInFramework(frameworkURL)
|> filter { arch in arch.hasPrefix("arm") }
|> map { _ in SDK.iPhoneOS }
|> concat(SignalProducer(value: SDK.MacOSX))
|> take(1)
|> map { sdk in sdk.platform }
|> map { platform in self.directoryURL.URLByAppendingPathComponent(platform.relativePath, isDirectory: true) }
|> map { platformFolderURL in platformFolderURL.URLByAppendingPathComponent(frameworkURL.lastPathComponent!) }
|> flatMap(.Merge) { destinationFrameworkURL in copyFramework(frameworkURL, destinationFrameworkURL.URLByResolvingSymlinksInPath!) }
}
/// Checks out the given project into its intended working directory,
/// cloning it first if need be.
private func checkoutOrCloneProject(project: ProjectIdentifier, atRevision revision: String, submodulesByPath: [String: Submodule]) -> SignalProducer<(), CarthageError> {
let repositoryURL = repositoryFileURLForProject(project)
let workingDirectoryURL = directoryURL.URLByAppendingPathComponent(project.relativePath, isDirectory: true)
let checkoutSignal = SignalProducer.try { () -> Result<Submodule?, CarthageError> in
var submodule: Submodule?
if var foundSubmodule = submodulesByPath[project.relativePath] {
foundSubmodule.URL = repositoryURLForProject(project, preferHTTPS: self.preferHTTPS)
foundSubmodule.SHA = revision
submodule = foundSubmodule
} else if self.useSubmodules {
submodule = Submodule(name: project.relativePath, path: project.relativePath, URL: repositoryURLForProject(project, preferHTTPS: self.preferHTTPS), SHA: revision)
}
return .success(submodule)
}
|> flatMap(.Merge) { submodule -> SignalProducer<(), CarthageError> in
if let submodule = submodule {
return addSubmoduleToRepository(self.directoryURL, submodule, GitURL(repositoryURL.path!))
|> startOnQueue(self.gitOperationQueue)
} else {
return checkoutRepositoryToDirectory(repositoryURL, workingDirectoryURL, revision: revision)
}
}
|> on(started: {
sendNext(self._projectEventsObserver, .CheckingOut(project, revision))
})
return commitExistsInRepository(repositoryURL, revision: revision)
|> promoteErrors(CarthageError.self)
|> flatMap(.Merge) { exists -> SignalProducer<NSURL, CarthageError> in
if exists {
return .empty
} else {
return self.cloneOrFetchDependency(project)
}
}
|> then(checkoutSignal)
}
/// Checks out the dependencies listed in the project's Cartfile.resolved.
public func checkoutResolvedDependencies() -> SignalProducer<(), CarthageError> {
/// Determine whether the repository currently holds any submodules (if
/// it even is a repository).
let submodulesSignal = submodulesInRepository(self.directoryURL)
|> reduce([:]) { (var submodulesByPath: [String: Submodule], submodule) in
submodulesByPath[submodule.path] = submodule
return submodulesByPath
}
return loadResolvedCartfile()
|> zipWith(submodulesSignal)
|> flatMap(.Merge) { resolvedCartfile, submodulesByPath -> SignalProducer<(), CarthageError> in
return SignalProducer(values: resolvedCartfile.dependencies)
|> flatMap(.Merge) { dependency in
let project = dependency.project
let revision = dependency.version.commitish
return self.installBinariesForProject(project, atRevision: revision)
|> flatMap(.Merge) { installed in
if installed {
return .empty
} else {
return self.checkoutOrCloneProject(project, atRevision: revision, submodulesByPath: submodulesByPath)
}
}
}
}
|> then(.empty)
}
/// Attempts to build each Carthage dependency that has been checked out.
///
/// Returns a producer-of-producers representing each scheme being built.
public func buildCheckedOutDependenciesWithConfiguration(configuration: String, forPlatform platform: Platform?) -> SignalProducer<BuildSchemeProducer, CarthageError> {
return loadResolvedCartfile()
|> flatMap(.Merge) { resolvedCartfile in SignalProducer(values: resolvedCartfile.dependencies) }
|> flatMap(.Concat) { dependency -> SignalProducer<BuildSchemeProducer, CarthageError> in
let dependencyPath = self.directoryURL.URLByAppendingPathComponent(dependency.project.relativePath, isDirectory: true).path!
if !NSFileManager.defaultManager().fileExistsAtPath(dependencyPath) {
return .empty
}
return buildDependencyProject(dependency.project, self.directoryURL, withConfiguration: configuration, platform: platform)
}
}
}
/// Constructs a file URL to where the binary corresponding to the given
/// arguments should live.
private func fileURLToCachedBinary(project: ProjectIdentifier, release: GitHubRelease, asset: GitHubRelease.Asset) -> NSURL {
// ~/Library/Caches/org.carthage.CarthageKit/binaries/ReactiveCocoa/v2.3.1/1234-ReactiveCocoa.framework.zip
return CarthageDependencyAssetsURL.URLByAppendingPathComponent("\(project.name)/\(release.tag)/\(asset.ID)-\(asset.name)", isDirectory: false)
}
/// Caches the downloaded binary at the given URL, moving it to the other URL
/// given.
///
/// Sends the final file URL upon .success.
private func cacheDownloadedBinary(downloadURL: NSURL, toURL cachedURL: NSURL) -> SignalProducer<NSURL, CarthageError> {
return SignalProducer(value: cachedURL)
|> try { fileURL in
var error: NSError?
let parentDirectoryURL = fileURL.URLByDeletingLastPathComponent!
if NSFileManager.defaultManager().createDirectoryAtURL(parentDirectoryURL, withIntermediateDirectories: true, attributes: nil, error: &error) {
return .success(())
} else {
return .failure(.WriteFailed(parentDirectoryURL, error))
}
}
|> try { newDownloadURL in
if rename(downloadURL.fileSystemRepresentation, newDownloadURL.fileSystemRepresentation) == 0 {
return .success(())
} else {
return .failure(.TaskError(.POSIXError(errno)))
}
}
}
/// Sends the URL to each framework bundle found in the given directory.
private func frameworksInDirectory(directoryURL: NSURL) -> SignalProducer<NSURL, CarthageError> {
return NSFileManager.defaultManager().carthage_enumeratorAtURL(directoryURL, includingPropertiesForKeys: [ NSURLTypeIdentifierKey ], options: NSDirectoryEnumerationOptions.SkipsHiddenFiles | NSDirectoryEnumerationOptions.SkipsPackageDescendants, catchErrors: true)
|> map { enumerator, URL in URL }
|> filter { URL in
var typeIdentifier: AnyObject?
if URL.getResourceValue(&typeIdentifier, forKey: NSURLTypeIdentifierKey, error: nil) {
if let typeIdentifier: AnyObject = typeIdentifier {
if UTTypeConformsTo(typeIdentifier as! String, kUTTypeFramework) != 0 {
return true
}
}
}
return false
}
|> filter { URL in
// Skip nested frameworks
let frameworksInURL = URL.pathComponents?.filter { pathComponent in
return (pathComponent as? String)?.pathExtension == "framework"
}
return frameworksInURL?.count == 1
}
}
/// Determines whether a Release is a suitable candidate for binary frameworks.
private func binaryFrameworksCanBeProvidedByRelease(release: GitHubRelease) -> Bool {
return !release.draft && !release.prerelease && !release.assets.isEmpty
}
/// Determines whether a release asset is a suitable candidate for binary
/// frameworks.
private func binaryFrameworksCanBeProvidedByAsset(asset: GitHubRelease.Asset) -> Bool {
let name = asset.name as NSString
if name.rangeOfString(CarthageProjectBinaryAssetPattern).location == NSNotFound {
return false
}
return contains(CarthageProjectBinaryAssetContentTypes, asset.contentType)
}
/// Returns the file URL at which the given project's repository will be
/// located.
private func repositoryFileURLForProject(project: ProjectIdentifier) -> NSURL {
return CarthageDependencyRepositoriesURL.URLByAppendingPathComponent(project.name, isDirectory: true)
}
/// Loads the Cartfile for the given dependency, at the given version.
private func cartfileForDependency(dependency: Dependency<PinnedVersion>) -> SignalProducer<Cartfile, CarthageError> {
let repositoryURL = repositoryFileURLForProject(dependency.project)
return contentsOfFileInRepository(repositoryURL, CarthageProjectCartfilePath, revision: dependency.version.commitish)
|> catch { _ in .empty }
|> tryMap { Cartfile.fromString($0) }
}
/// Returns the URL that the project's remote repository exists at.
private func repositoryURLForProject(project: ProjectIdentifier, #preferHTTPS: Bool) -> GitURL {
switch project {
case let .GitHub(repository):
if preferHTTPS {
return repository.HTTPSURL
} else {
return repository.SSHURL
}
case let .Git(URL):
return URL
}
}
/// Clones the given project to the global repositories folder, or fetches
/// inside it if it has already been cloned.
///
/// Returns a signal which will send the operation type once started, and
/// the URL to where the repository's folder will exist on disk, then complete
/// when the operation completes.
public func cloneOrFetchProject(project: ProjectIdentifier, #preferHTTPS: Bool) -> SignalProducer<(ProjectEvent, NSURL), CarthageError> {
let repositoryURL = repositoryFileURLForProject(project)
return SignalProducer.try { () -> Result<GitURL, CarthageError> in
var error: NSError?
if !NSFileManager.defaultManager().createDirectoryAtURL(CarthageDependencyRepositoriesURL, withIntermediateDirectories: true, attributes: nil, error: &error) {
return .failure(.WriteFailed(CarthageDependencyRepositoriesURL, error))
}
return .success(repositoryURLForProject(project, preferHTTPS: preferHTTPS))
}
|> flatMap(.Merge) { remoteURL in
if NSFileManager.defaultManager().createDirectoryAtURL(repositoryURL, withIntermediateDirectories: false, attributes: nil, error: nil) {
// If we created the directory, we're now responsible for
// cloning it.
let cloneSignal = cloneRepository(remoteURL, repositoryURL)
return SignalProducer(value: (ProjectEvent.Cloning(project), repositoryURL))
|> concat(cloneSignal |> then(.empty))
} else {
let fetchSignal = fetchRepository(repositoryURL, remoteURL: remoteURL, refspec: "+refs/heads/*:refs/heads/*") /* lol syntax highlighting */
return SignalProducer(value: (ProjectEvent.Fetching(project), repositoryURL))
|> concat(fetchSignal |> then(.empty))
}
}
}
| mit | a8f19d9ed9495579e7140e06f6f40e87 | 40.153094 | 265 | 0.750396 | 4.550333 | false | false | false | false |
jkolb/midnightbacon | MidnightBacon/Reddit/OAuth/OAuthAuthorizeResponse.swift | 1 | 3906 | //
// OAuthAuthorizeResponse.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import FranticApparatus
import ModestProposal
public class OAuthAuthorizeResponse : CustomStringConvertible {
let code: String
let state: String
public init(code: String, state: String) {
self.code = code
self.state = state
}
public var description: String {
return "code: \(code) state: \(state)"
}
public class func parseFromQuery(redirectURL: NSURL, expectedState: String) throws -> OAuthAuthorizeResponse {
if let components = NSURLComponents(URL: redirectURL, resolvingAgainstBaseURL: true) {
if let query = components.percentEncodedQuery {
return try parse(query, expectedState: expectedState)
} else {
throw OAuthError.MissingURLQuery
}
} else {
throw OAuthError.MalformedURL
}
}
public class func parseFromFragment(redirectURL: NSURL, expectedState: String) throws -> OAuthAuthorizeResponse {
if let components = NSURLComponents(URL: redirectURL, resolvingAgainstBaseURL: true) {
if let fragment = components.percentEncodedFragment {
return try parse(fragment, expectedState: expectedState)
} else {
throw OAuthError.MissingURLFragment
}
} else {
throw OAuthError.MalformedURL
}
}
public class func parse(formEncoded: String, expectedState: String) throws -> OAuthAuthorizeResponse {
let components = NSURLComponents()
components.percentEncodedQuery = formEncoded
let queryItems = components.parameters ?? [:]
if queryItems.count == 0 { throw OAuthError.EmptyURLQuery }
if let errorString = queryItems["error"] {
if "access_denied" == errorString {
throw OAuthError.AccessDenied
} else if "unsupported_response_type" == errorString {
throw OAuthError.UnsupportedResponseType
} else if "invalid_scope" == errorString {
throw OAuthError.InvalidScope
} else if "invalid_request" == errorString {
throw OAuthError.InvalidRequest
} else {
throw OAuthError.UnexpectedError(errorString)
}
}
let state = queryItems["state"] ?? ""
if expectedState != state {
throw OAuthError.UnexpectedState(state)
}
let code = queryItems["code"] ?? ""
if code == "" {
throw OAuthError.MissingCode
}
return OAuthAuthorizeResponse(code: code, state: state)
}
}
| mit | 9f56161acdc2cc29d9c83df872d8d04e | 37.294118 | 117 | 0.647721 | 5.409972 | false | false | false | false |
arturjaworski/Colorizer | Sources/colorizer/Extensions/NSColor.swift | 1 | 914 | import AppKit.NSColor
enum NSColorError: Error {
case wrongString
}
extension NSColor {
convenience init(hex: UInt32) {
let red = (hex >> 24) & 0xff
let green = (hex >> 16) & 0xff
let blue = (hex >> 8) & 0xff
let alpha = hex & 0xff
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha) / 255.0)
}
convenience init(hexString hex: String) throws {
var hex = hex.withoutPrefix("#").withoutPrefix("0x").uppercased()
if hex.characters.count == 6 {
hex = hex + "FF" // if there is no alpha
}
if hex.characters.count != 8 {
throw NSColorError.wrongString
}
var rgbValue: UInt32 = 0
Scanner(string: hex).scanHexInt32(&rgbValue)
self.init(hex: rgbValue)
}
} | mit | bab79f593d895ad2c433e716bee310af | 25.911765 | 143 | 0.54267 | 3.872881 | false | false | false | false |
ahoppen/swift | test/decl/ext/protocol.swift | 2 | 25184 | // RUN: %target-typecheck-verify-swift -warn-redundant-requirements
// ----------------------------------------------------------------------------
// Using protocol requirements from inside protocol extensions
// ----------------------------------------------------------------------------
protocol P1 {
@discardableResult
func reqP1a() -> Bool
}
extension P1 {
func extP1a() -> Bool { return !reqP1a() }
var extP1b: Bool {
return self.reqP1a()
}
var extP1c: Bool {
return extP1b && self.extP1a()
}
}
protocol P2 {
associatedtype AssocP2 : P1
func reqP2a() -> AssocP2
}
extension P2 {
func extP2a() -> AssocP2? { return reqP2a() }
func extP2b() {
self.reqP2a().reqP1a()
}
func extP2c() -> Self.AssocP2 { return extP2a()! }
}
protocol P3 {
associatedtype AssocP3 : P2
func reqP3a() -> AssocP3
}
extension P3 {
func extP3a() -> AssocP3.AssocP2 {
return reqP3a().reqP2a()
}
}
protocol P4 {
associatedtype AssocP4
func reqP4a() -> AssocP4
}
// ----------------------------------------------------------------------------
// Using generics from inside protocol extensions
// ----------------------------------------------------------------------------
func acceptsP1<T : P1>(_ t: T) { }
extension P1 {
func extP1d() { acceptsP1(self) }
}
func acceptsP2<T : P2>(_ t: T) { }
extension P2 {
func extP2acceptsP1() { acceptsP1(reqP2a()) }
func extP2acceptsP2() { acceptsP2(self) }
}
// Use of 'Self' as a return type within a protocol extension.
protocol SelfP1 {
associatedtype AssocType
}
protocol SelfP2 {
}
func acceptSelfP1<T, U : SelfP1>(_ t: T, _ u: U) -> T where U.AssocType == T {
return t
}
extension SelfP1 {
func tryAcceptSelfP1<Z : SelfP1>(_ z: Z)-> Self where Z.AssocType == Self {
return acceptSelfP1(self, z)
}
}
// ----------------------------------------------------------------------------
// Initializers in protocol extensions
// ----------------------------------------------------------------------------
protocol InitP1 {
init(string: String)
}
extension InitP1 {
init(int: Int) { self.init(string: "integer") }
}
struct InitS1 : InitP1 {
init(string: String) { }
}
class InitC1 : InitP1 {
required init(string: String) { }
}
func testInitP1() {
var is1 = InitS1(int: 5)
is1 = InitS1(string: "blah") // check type
_ = is1
var ic1 = InitC1(int: 5)
ic1 = InitC1(string: "blah") // check type
_ = ic1
}
// ----------------------------------------------------------------------------
// Subscript in protocol extensions
// ----------------------------------------------------------------------------
protocol SubscriptP1 {
func readAt(_ i: Int) -> String
func writeAt(_ i: Int, string: String)
}
extension SubscriptP1 {
subscript(i: Int) -> String {
get { return readAt(i) }
set(newValue) { writeAt(i, string: newValue) }
}
}
struct SubscriptS1 : SubscriptP1 {
func readAt(_ i: Int) -> String { return "hello" }
func writeAt(_ i: Int, string: String) { }
}
struct SubscriptC1 : SubscriptP1 {
func readAt(_ i: Int) -> String { return "hello" }
func writeAt(_ i: Int, string: String) { }
}
func testSubscriptP1(_ ss1: SubscriptS1, sc1: SubscriptC1,
i: Int, s: String) {
var ss1 = ss1
var sc1 = sc1
_ = ss1[i]
ss1[i] = s
_ = sc1[i]
sc1[i] = s
}
// ----------------------------------------------------------------------------
// Using protocol extensions on types that conform to the protocols.
// ----------------------------------------------------------------------------
struct S1 : P1 {
@discardableResult
func reqP1a() -> Bool { return true }
func once() -> Bool {
return extP1a() && extP1b
}
}
func useS1(_ s1: S1) -> Bool {
s1.reqP1a()
return s1.extP1a() && s1.extP1b
}
extension S1 {
func twice() -> Bool {
return extP1a() && extP1b
}
}
// ----------------------------------------------------------------------------
// Protocol extensions with redundant requirements
// ----------------------------------------------------------------------------
protocol FooProtocol {}
extension FooProtocol where Self: FooProtocol {} // expected-warning {{redundant conformance constraint 'Self' : 'FooProtocol'}}
protocol AnotherFooProtocol {}
protocol BazProtocol {}
extension AnotherFooProtocol where Self: BazProtocol, Self: AnotherFooProtocol {} // expected-warning {{redundant conformance constraint 'Self' : 'AnotherFooProtocol'}}
protocol AnotherBazProtocol {
associatedtype BazValue
}
extension AnotherBazProtocol where BazValue: AnotherBazProtocol {} // ok, does not warn because BazValue is not Self
// ----------------------------------------------------------------------------
// Protocol extensions with additional requirements
// ----------------------------------------------------------------------------
extension P4 where Self.AssocP4 : P1 {
// expected-note@-1 {{candidate requires that 'Int' conform to 'P1' (requirement specified as 'Self.AssocP4' : 'P1')}}
// expected-note@-2 {{candidate requires that 'S4aHelper' conform to 'P1' (requirement specified as 'Self.AssocP4' : 'P1')}}
func extP4a() {
acceptsP1(reqP4a())
}
}
struct S4aHelper { }
struct S4bHelper : P1 {
func reqP1a() -> Bool { return true }
}
struct S4a : P4 {
func reqP4a() -> S4aHelper { return S4aHelper() }
}
struct S4b : P4 {
func reqP4a() -> S4bHelper { return S4bHelper() }
}
struct S4c : P4 {
func reqP4a() -> Int { return 0 }
}
struct S4d : P4 {
func reqP4a() -> Bool { return false }
}
extension P4 where Self.AssocP4 == Int { // expected-note {{where 'Self.AssocP4' = 'Bool'}}
func extP4Int() { }
}
extension P4 where Self.AssocP4 == Bool {
// expected-note@-1 {{candidate requires that the types 'Int' and 'Bool' be equivalent (requirement specified as 'Self.AssocP4' == 'Bool')}}
// expected-note@-2 {{candidate requires that the types 'S4aHelper' and 'Bool' be equivalent (requirement specified as 'Self.AssocP4' == 'Bool')}}
func extP4a() -> Bool { return reqP4a() }
}
func testP4(_ s4a: S4a, s4b: S4b, s4c: S4c, s4d: S4d) {
s4a.extP4a() // expected-error{{no exact matches in call to instance method 'extP4a'}}
s4b.extP4a() // ok
s4c.extP4a() // expected-error{{no exact matches in call to instance method 'extP4a'}}
s4c.extP4Int() // okay
var b1 = s4d.extP4a() // okay, "Bool" version
b1 = true // checks type above
s4d.extP4Int() // expected-error{{referencing instance method 'extP4Int()' on 'P4' requires the types 'Bool' and 'Int' be equivalent}}
_ = b1
}
// ----------------------------------------------------------------------------
// Protocol extensions with a superclass constraint on Self
// ----------------------------------------------------------------------------
protocol ConformedProtocol {
typealias ConcreteConformanceAlias = Self
}
class BaseWithAlias<T> : ConformedProtocol {
typealias ConcreteAlias = T
struct NestedNominal {}
func baseMethod(_: T) {}
}
class DerivedWithAlias : BaseWithAlias<Int> {}
protocol ExtendedProtocol {
typealias AbstractConformanceAlias = Self
}
extension ExtendedProtocol where Self : DerivedWithAlias {
func f0(x: T) {} // expected-error {{cannot find type 'T' in scope}}
func f1(x: ConcreteAlias) {
let _: Int = x
baseMethod(x)
}
func f2(x: ConcreteConformanceAlias) {
let _: DerivedWithAlias = x
}
func f3(x: AbstractConformanceAlias) {
let _: DerivedWithAlias = x
}
func f4(x: NestedNominal) {}
}
// rdar://problem/21991470 & https://bugs.swift.org/browse/SR-5022
class NonPolymorphicInit {
init() { } // expected-note {{selected non-required initializer 'init()'}}
}
protocol EmptyProtocol { }
// The diagnostic is not very accurate, but at least we reject this.
extension EmptyProtocol where Self : NonPolymorphicInit {
init(string: String) {
self.init()
// expected-error@-1 {{constructing an object of class type 'Self' with a metatype value must use a 'required' initializer}}
}
}
// ----------------------------------------------------------------------------
// Using protocol extensions to satisfy requirements
// ----------------------------------------------------------------------------
protocol P5 {
func reqP5a()
}
// extension of P5 provides a witness for P6
extension P5 {
func reqP6a() { reqP5a() }
}
protocol P6 {
func reqP6a()
}
// S6a uses P5.reqP6a
struct S6a : P5 {
func reqP5a() { }
}
extension S6a : P6 { }
// S6b uses P5.reqP6a
struct S6b : P5, P6 {
func reqP5a() { }
}
// S6c uses P5.reqP6a
struct S6c : P6 {
}
extension S6c : P5 {
func reqP5a() { }
}
// S6d does not use P5.reqP6a
struct S6d : P6 {
func reqP6a() { }
}
extension S6d : P5 {
func reqP5a() { }
}
protocol P7 {
associatedtype P7Assoc
func getP7Assoc() -> P7Assoc
}
struct P7FromP8<T> { }
protocol P8 {
associatedtype P8Assoc
func getP8Assoc() -> P8Assoc
}
// extension of P8 provides conformance to P7Assoc
extension P8 {
func getP7Assoc() -> P7FromP8<P8Assoc> { return P7FromP8() }
}
// Okay, P7 requirements satisfied by P8
struct P8a : P8, P7 {
func getP8Assoc() -> Bool { return true }
}
func testP8a(_ p8a: P8a) {
var p7 = p8a.getP7Assoc()
p7 = P7FromP8<Bool>() // okay, check type of above
_ = p7
}
// Okay, P7 requirements explicitly specified
struct P8b : P8, P7 {
func getP7Assoc() -> Int { return 5 }
func getP8Assoc() -> Bool { return true }
}
func testP8b(_ p8b: P8b) {
var p7 = p8b.getP7Assoc()
p7 = 17 // check type of above
_ = p7
}
protocol PConforms1 {
}
extension PConforms1 {
func pc2() { } // expected-note{{candidate exactly matches}}
}
protocol PConforms2 : PConforms1, MakePC2Ambiguous {
func pc2() // expected-note{{multiple matching functions named 'pc2()' with type '() -> ()'}}
}
protocol MakePC2Ambiguous {
}
extension MakePC2Ambiguous {
func pc2() { } // expected-note{{candidate exactly matches}}
}
struct SConforms2a : PConforms2 { } // expected-error{{type 'SConforms2a' does not conform to protocol 'PConforms2'}}
struct SConforms2b : PConforms2 {
func pc2() { }
}
// Satisfying requirements via protocol extensions for fun and profit
protocol _MySeq { }
protocol MySeq : _MySeq {
associatedtype Generator : IteratorProtocol
func myGenerate() -> Generator
}
protocol _MyCollection : _MySeq {
associatedtype Index : Strideable
var myStartIndex : Index { get }
var myEndIndex : Index { get }
associatedtype _Element
subscript (i: Index) -> _Element { get }
}
protocol MyCollection : _MyCollection {
}
struct MyIndexedIterator<C : _MyCollection> : IteratorProtocol {
var container: C
var index: C.Index
mutating func next() -> C._Element? {
if index == container.myEndIndex { return nil }
let result = container[index]
index = index.advanced(by: 1)
return result
}
}
struct OtherIndexedIterator<C : _MyCollection> : IteratorProtocol {
var container: C
var index: C.Index
mutating func next() -> C._Element? {
if index == container.myEndIndex { return nil }
let result = container[index]
index = index.advanced(by: 1)
return result
}
}
extension _MyCollection {
func myGenerate() -> MyIndexedIterator<Self> {
return MyIndexedIterator(container: self, index: self.myEndIndex)
}
}
struct SomeCollection1 : MyCollection {
var myStartIndex: Int { return 0 }
var myEndIndex: Int { return 10 }
subscript (i: Int) -> String {
return "blah"
}
}
struct SomeCollection2 : MyCollection {
var myStartIndex: Int { return 0 }
var myEndIndex: Int { return 10 }
subscript (i: Int) -> String {
return "blah"
}
func myGenerate() -> OtherIndexedIterator<SomeCollection2> {
return OtherIndexedIterator(container: self, index: self.myEndIndex)
}
}
func testSomeCollections(_ sc1: SomeCollection1, sc2: SomeCollection2) {
var mig = sc1.myGenerate()
mig = MyIndexedIterator(container: sc1, index: sc1.myStartIndex)
_ = mig
var ig = sc2.myGenerate()
ig = MyIndexedIterator(container: sc2, index: sc2.myStartIndex) // expected-error {{cannot assign value of type 'MyIndexedIterator<SomeCollection2>' to type 'OtherIndexedIterator<SomeCollection2>'}}
_ = ig
}
public protocol PConforms3 {}
extension PConforms3 {
public var z: Int {
return 0
}
}
public protocol PConforms4 : PConforms3 {
var z: Int { get }
}
struct PConforms4Impl : PConforms4 {}
let pc4z = PConforms4Impl().z
// rdar://problem/20608438
protocol PConforms5 {
func f() -> Int
}
protocol PConforms6 : PConforms5 {}
extension PConforms6 {
func f() -> Int { return 42 }
}
func test<T: PConforms6>(_ x: T) -> Int { return x.f() }
struct PConforms6Impl : PConforms6 { }
// Extensions of a protocol that directly satisfy requirements (i.e.,
// default implementations hack N+1).
protocol PConforms7 {
func method()
var property: Int { get }
subscript (i: Int) -> Int { get }
}
extension PConforms7 {
func method() { }
var property: Int { return 5 }
subscript (i: Int) -> Int { return i }
}
struct SConforms7a : PConforms7 { }
protocol PConforms8 {
associatedtype Assoc
func method() -> Assoc
var property: Assoc { get }
subscript (i: Assoc) -> Assoc { get }
}
extension PConforms8 {
func method() -> Int { return 5 }
var property: Int { return 5 }
subscript (i: Int) -> Int { return i }
}
struct SConforms8a : PConforms8 { }
struct SConforms8b : PConforms8 {
func method() -> String { return "" }
var property: String { return "" }
subscript (i: String) -> String { return i }
}
func testSConforms8b() {
let s: SConforms8b.Assoc = "hello"
_ = s
}
struct SConforms8c : PConforms8 {
func method() -> String { return "" } // no warning in type definition
}
func testSConforms8c() {
let s: SConforms8c.Assoc = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'SConforms8c.Assoc' (aka 'Int')}}
_ = s
let i: SConforms8c.Assoc = 5
_ = i
}
protocol DefaultInitializable {
init()
}
extension String : DefaultInitializable { }
extension Int : DefaultInitializable { }
protocol PConforms9 {
associatedtype Assoc : DefaultInitializable // expected-note{{protocol requires nested type 'Assoc'}}
func method() -> Assoc
var property: Assoc { get }
subscript (i: Assoc) -> Assoc { get }
}
extension PConforms9 {
func method() -> Self.Assoc { return Assoc() }
var property: Self.Assoc { return Assoc() }
subscript (i: Self.Assoc) -> Self.Assoc { return Assoc() }
}
struct SConforms9a : PConforms9 { // expected-error{{type 'SConforms9a' does not conform to protocol 'PConforms9'}}
}
struct SConforms9b : PConforms9 {
typealias Assoc = Int
}
func testSConforms9b(_ s9b: SConforms9b) {
var p = s9b.property
p = 5
_ = p
}
struct SConforms9c : PConforms9 {
typealias Assoc = String
}
func testSConforms9c(_ s9c: SConforms9c) {
var p = s9c.property
p = "hello"
_ = p
}
struct SConforms9d : PConforms9 {
func method() -> Int { return 5 }
}
func testSConforms9d(_ s9d: SConforms9d) {
var p = s9d.property
p = 6
_ = p
}
protocol PConforms10 {}
extension PConforms10 {
func f() {}
}
protocol PConforms11 {
func f()
}
struct SConforms11 : PConforms10, PConforms11 {}
// ----------------------------------------------------------------------------
// Typealiases in protocol extensions.
// ----------------------------------------------------------------------------
// Basic support
protocol PTypeAlias1 {
associatedtype AssocType1
}
extension PTypeAlias1 {
typealias ArrayOfAssocType1 = [AssocType1]
}
struct STypeAlias1a: PTypeAlias1 {
typealias AssocType1 = Int
}
struct STypeAlias1b<T>: PTypeAlias1 {
typealias AssocType1 = T
}
func testPTypeAlias1() {
var a: STypeAlias1a.ArrayOfAssocType1 = []
a.append(1)
var b: STypeAlias1b<String>.ArrayOfAssocType1 = []
b.append("hello")
}
// Defaulted implementations to satisfy a requirement.
struct TypeAliasHelper<T> { }
protocol PTypeAliasSuper2 {
}
extension PTypeAliasSuper2 {
func foo() -> TypeAliasHelper<Self> { return TypeAliasHelper() }
}
protocol PTypeAliasSub2 : PTypeAliasSuper2 {
associatedtype Helper
func foo() -> Helper
}
struct STypeAliasSub2a : PTypeAliasSub2 { }
struct STypeAliasSub2b<T, U> : PTypeAliasSub2 { }
// ----------------------------------------------------------------------------
// Partial ordering of protocol extension members
// ----------------------------------------------------------------------------
// Partial ordering between members of protocol extensions and members
// of concrete types.
struct S1b : P1 {
func reqP1a() -> Bool { return true }
func extP1a() -> Int { return 0 }
}
func useS1b(_ s1b: S1b) {
var x = s1b.extP1a() // uses S1b.extP1a due to partial ordering
x = 5 // checks that "x" deduced to "Int" above
_ = x
var _: Bool = s1b.extP1a() // still uses P1.ext1Pa due to type annotation
}
// Partial ordering between members of protocol extensions for
// different protocols.
protocol PInherit1 { }
protocol PInherit2 : PInherit1 { }
protocol PInherit3 : PInherit2 { }
protocol PInherit4 : PInherit2 { }
extension PInherit1 {
func order1() -> Int { return 0 }
}
extension PInherit2 {
func order1() -> Bool { return true }
}
extension PInherit3 {
func order1() -> Double { return 1.0 }
}
extension PInherit4 {
func order1() -> String { return "hello" }
}
struct SInherit1 : PInherit1 { }
struct SInherit2 : PInherit2 { }
struct SInherit3 : PInherit3 { }
struct SInherit4 : PInherit4 { }
func testPInherit(_ si2 : SInherit2, si3: SInherit3, si4: SInherit4) {
var b1 = si2.order1() // PInherit2.order1
b1 = true // check that the above returned Bool
_ = b1
var d1 = si3.order1() // PInherit3.order1
d1 = 3.14159 // check that the above returned Double
_ = d1
var s1 = si4.order1() // PInherit4.order1
s1 = "hello" // check that the above returned String
_ = s1
// Other versions are still visible, since they may have different
// types.
b1 = si3.order1() // PInherit2.order1
var _: Int = si3.order1() // PInherit1.order1
}
protocol PConstrained1 {
associatedtype AssocTypePC1
}
extension PConstrained1 {
func pc1() -> Int { return 0 }
}
extension PConstrained1 where AssocTypePC1 : PInherit2 {
func pc1() -> Bool { return true }
}
extension PConstrained1 where Self.AssocTypePC1 : PInherit3 {
func pc1() -> String { return "hello" }
}
struct SConstrained1 : PConstrained1 {
typealias AssocTypePC1 = SInherit1
}
struct SConstrained2 : PConstrained1 {
typealias AssocTypePC1 = SInherit2
}
struct SConstrained3 : PConstrained1 {
typealias AssocTypePC1 = SInherit3
}
func testPConstrained1(_ sc1: SConstrained1, sc2: SConstrained2,
sc3: SConstrained3) {
var i = sc1.pc1() // PConstrained1.pc1
i = 17 // checks type of above
_ = i
var b = sc2.pc1() // PConstrained1 (with PInherit2).pc1
b = true // checks type of above
_ = b
var s = sc3.pc1() // PConstrained1 (with PInherit3).pc1
s = "hello" // checks type of above
_ = s
}
protocol PConstrained2 {
associatedtype AssocTypePC2
}
protocol PConstrained3 : PConstrained2 {
}
extension PConstrained2 where Self.AssocTypePC2 : PInherit1 {
func pc2() -> Bool { return true }
}
extension PConstrained3 {
func pc2() -> String { return "hello" }
}
struct SConstrained3a : PConstrained3 {
typealias AssocTypePC2 = Int
}
struct SConstrained3b : PConstrained3 {
typealias AssocTypePC2 = SInherit3
}
func testSConstrained3(_ sc3a: SConstrained3a, sc3b: SConstrained3b) {
var s = sc3a.pc2() // PConstrained3.pc2
s = "hello"
_ = s
_ = sc3b.pc2()
s = sc3b.pc2()
var _: Bool = sc3b.pc2()
}
extension PConstrained3 where AssocTypePC2 : PInherit1 { }
// Extending via a superclass constraint.
class Superclass {
func foo() { }
static func bar() { }
typealias Foo = Int
}
protocol PConstrained4 { }
extension PConstrained4 where Self : Superclass {
func testFoo() -> Foo {
foo()
self.foo()
return Foo(5)
}
static func testBar() {
bar()
self.bar()
}
}
protocol PConstrained5 { }
protocol PConstrained6 {
associatedtype Assoc
func foo()
}
protocol PConstrained7 { }
extension PConstrained6 {
var prop1: Int { return 0 }
var prop2: Int { return 0 } // expected-note{{'prop2' previously declared here}}
subscript (key: Int) -> Int { return key }
subscript (key: Double) -> Double { return key } // expected-note{{'subscript(_:)' previously declared here}}
}
extension PConstrained6 {
var prop2: Int { return 0 } // expected-error{{invalid redeclaration of 'prop2'}}
subscript (key: Double) -> Double { return key } // expected-error{{invalid redeclaration of 'subscript(_:)'}}
}
extension PConstrained6 where Assoc : PConstrained5 {
var prop1: Int { return 0 } // okay
var prop3: Int { return 0 } // expected-note{{'prop3' previously declared here}}
subscript (key: Int) -> Int { return key } // ok
subscript (key: String) -> String { return key } // expected-note{{'subscript(_:)' previously declared here}}
func foo() { } // expected-note{{'foo()' previously declared here}}
}
extension PConstrained6 where Assoc : PConstrained5 {
var prop3: Int { return 0 } // expected-error{{invalid redeclaration of 'prop3'}}
subscript (key: String) -> String { return key } // expected-error{{invalid redeclaration of 'subscript(_:)'}}
func foo() { } // expected-error{{invalid redeclaration of 'foo()'}}
}
extension PConstrained6 where Assoc : PConstrained7 {
var prop1: Int { return 0 } // okay
subscript (key: Int) -> Int { return key } // okay
func foo() { } // okay
}
extension PConstrained6 where Assoc == Int {
var prop4: Int { return 0 }
subscript (key: Character) -> Character { return key }
func foo() { } // okay
}
extension PConstrained6 where Assoc == Double {
var prop4: Int { return 0 } // okay
subscript (key: Character) -> Character { return key } // okay
func foo() { } // okay
}
// Interaction between RawRepresentable and protocol extensions.
public protocol ReallyRaw : RawRepresentable {
}
public extension ReallyRaw where RawValue: SignedInteger {
// expected-warning@+1 {{'public' modifier is redundant for initializer declared in a public extension}}
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
}
enum Foo : Int, ReallyRaw {
case a = 0
}
// ----------------------------------------------------------------------------
// Semantic restrictions
// ----------------------------------------------------------------------------
// Extension cannot have an inheritance clause.
protocol BadProto1 { }
protocol BadProto2 { }
extension BadProto1 : BadProto2 { } // expected-error{{extension of protocol 'BadProto1' cannot have an inheritance clause}}
extension BadProto2 {
struct S { } // expected-error{{type 'S' cannot be nested in protocol extension of 'BadProto2'}}
class C { } // expected-error{{type 'C' cannot be nested in protocol extension of 'BadProto2'}}
enum E { } // expected-error{{type 'E' cannot be nested in protocol extension of 'BadProto2'}}
}
extension BadProto1 {
func foo() { }
var prop: Int { return 0 }
subscript (i: Int) -> String {
return "hello"
}
}
// rdar://problem/20756244
protocol BadProto3 { }
typealias BadProto4 = BadProto3
extension BadProto4 { } // okay
typealias RawRepresentableAlias = RawRepresentable
extension RawRepresentableAlias { } // okay
extension AnyObject { } // expected-error{{non-nominal type 'AnyObject' cannot be extended}}
// Members of protocol extensions cannot be overridden.
// rdar://problem/21075287
class BadClass1 : BadProto1 {
func foo() { }
override var prop: Int { return 5 } // expected-error{{property does not override any property from its superclass}}
}
protocol BadProto5 {
associatedtype T1 // expected-note{{protocol requires nested type 'T1'}}
associatedtype T2 // expected-note{{protocol requires nested type 'T2'}}
associatedtype T3 // expected-note{{protocol requires nested type 'T3'}}
}
class BadClass5 : BadProto5 {} // expected-error{{type 'BadClass5' does not conform to protocol 'BadProto5'}}
typealias A = BadProto1
typealias B = BadProto1
extension A & B {} // expected-warning {{extending a protocol composition is not supported; extending 'BadProto1' instead}}
// Suppress near-miss warning for unlabeled initializers.
protocol P9 {
init(_: Int)
init(_: Double)
}
extension P9 {
init(_ i: Int) {
self.init(Double(i))
}
}
struct X9 : P9 {
init(_: Float) { }
}
extension X9 {
init(_: Double) { }
}
// Suppress near-miss warning for unlabeled subscripts.
protocol P10 {
subscript (_: Int) -> Int { get }
subscript (_: Double) -> Double { get }
}
extension P10 {
subscript(i: Int) -> Int {
return Int(self[Double(i)])
}
}
struct X10 : P10 {
subscript(f: Float) -> Float { return f }
}
extension X10 {
subscript(d: Double) -> Double { return d }
}
protocol Empty1 {}
protocol Empty2 {}
struct Concrete1 {}
extension Concrete1 : Empty1 & Empty2 {}
typealias TA = Empty1 & Empty2
struct Concrete2 {}
extension Concrete2 : TA {}
func f<T : Empty1 & Empty2>(_: T) {}
func useF() {
f(Concrete1())
f(Concrete2())
}
| apache-2.0 | 358389cb21aca3a6872d0a97711595e6 | 22.961941 | 200 | 0.627581 | 3.713359 | false | false | false | false |
MyHammer/MHAppIndexing | Example/MHAppIndexing/ViewController.swift | 1 | 3860 | //
// ViewController.swift
// MHAppIndexing
//
// Created by Frank Lienkamp on 02/03/2016.
// Copyright (c) 2016 Frank Lienkamp. All rights reserved.
//
import UIKit
import MHAppIndexing
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func indexCoreSpotlightObjects(sender: AnyObject) {
let exampleOne = self.exampleObject1()
let exampleTwo = self.exampleObject2()
let exampleThree = self.exampleObject3()
MHCoreSpotlightManager.sharedInstance.addObjectToSearchIndex(exampleOne)
MHCoreSpotlightManager.sharedInstance.addObjectToSearchIndex(exampleTwo)
MHCoreSpotlightManager.sharedInstance.addObjectToSearchIndex(exampleThree)
}
@IBAction func indexUserActivityObjects(sender: AnyObject) {
let exampleOne = self.exampleObject1()
let exampleTwo = self.exampleObject2()
let exampleThree = self.exampleObject3()
MHUserActivityManager.sharedInstance.addObjectToSearchIndex(exampleOne)
MHUserActivityManager.sharedInstance.addObjectToSearchIndex(exampleTwo)
MHUserActivityManager.sharedInstance.addObjectToSearchIndex(exampleThree)
}
/*
// MARK: example creation methods
*/
func exampleObject1() -> ExampleObject {
let example = ExampleObject()
example.mhDomainIdentifier = "com.some.what.here"
example.mhUniqueIdentifier = "1234567891"
example.mhTitle = "Lisa"
example.mhContentDescription = "This is a content description for Lisa"
example.mhKeywords = ["apple", "cherry", "banana"]
example.mhImageInfo = MHImageInfo(imageURL: NSURL(string: "https://upload.wikimedia.org/wikipedia/en/e/ec/Lisa_Simpson.png")!)
//UserActivity stuff
example.mhUserInfo = ["objectId":example.mhUniqueIdentifier]
example.mhEligibleForSearch = true
example.mhEligibleForPublicIndexing = true
example.mhEligibleForHandoff = false
example.mhWebpageURL = NSURL(string: "https://en.wikipedia.org/wiki/Lisa_Simpson")
return example
}
func exampleObject2() -> ExampleObject {
let example = ExampleObject()
example.mhDomainIdentifier = "com.some.what.here"
example.mhUniqueIdentifier = "987654321"
example.mhTitle = "Homer"
example.mhContentDescription = "Here is a content description for Homer"
example.mhKeywords = ["orange", "melon", "pineapple"]
example.mhImageInfo = MHImageInfo(bundleImageName: "homer", bundleImageType: "png")
//UserActivity stuff
example.mhUserInfo = ["objectId":example.mhUniqueIdentifier]
example.mhEligibleForSearch = true
example.mhEligibleForPublicIndexing = true
example.mhEligibleForHandoff = false
example.mhWebpageURL = NSURL(string: "https://en.wikipedia.org/wiki/Homer_Simpson")
return example
}
func exampleObject3() -> ExampleObject {
let example = ExampleObject()
example.mhDomainIdentifier = "com.some.what.here"
example.mhUniqueIdentifier = "47110822"
example.mhTitle = "Carl"
example.mhContentDescription = "Content description here for Carl"
example.mhKeywords = ["strawberry", "kiwi", "lemon"]
example.mhImageInfo = MHImageInfo(assetImageName: "carl")
//UserActivity stuff
example.mhUserInfo = ["objectId":example.mhUniqueIdentifier]
example.mhEligibleForSearch = true
example.mhEligibleForPublicIndexing = true
example.mhEligibleForHandoff = false
example.mhWebpageURL = NSURL(string: "https://en.wikipedia.org/wiki/Lenny_and_Carl#Carl_Carlson")
return example
}
}
| apache-2.0 | eb0b787f208e286e61ef65c37296b9e3 | 35.761905 | 134 | 0.694819 | 4.673123 | false | false | false | false |
rnystrom/GitHawk | Classes/Notifications/NoNewNotificationsCell.swift | 1 | 6098 | //
// NoNewNotificationsCell.swift
// Freetime
//
// Created by Ryan Nystrom on 6/30/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import SnapKit
protocol NoNewNotificationsCellReviewAccessDelegate: class {
func didTapReviewAccess(cell: NoNewNotificationsCell)
}
final class NoNewNotificationsCell: UICollectionViewCell {
private let emojiLabel = UILabel()
private let messageLabel = UILabel()
private let shadow = CAShapeLayer()
private let reviewGitHubAccessButton = UIButton()
private weak var reviewGitHubAccessDelegate: NoNewNotificationsCellReviewAccessDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
emojiLabel.isAccessibilityElement = false
emojiLabel.textAlignment = .center
emojiLabel.backgroundColor = .clear
emojiLabel.font = .systemFont(ofSize: 60)
contentView.addSubview(emojiLabel)
emojiLabel.snp.makeConstraints { make in
make.centerX.equalTo(contentView)
make.centerY.equalTo(contentView).offset(-Styles.Sizes.tableSectionSpacing)
}
shadow.fillColor = UIColor(white: 0, alpha: 0.05).cgColor
contentView.layer.addSublayer(shadow)
messageLabel.isAccessibilityElement = false
messageLabel.textAlignment = .center
messageLabel.backgroundColor = .clear
messageLabel.font = Styles.Text.body.preferredFont
messageLabel.textColor = Styles.Colors.Gray.light.color
contentView.addSubview(messageLabel)
messageLabel.snp.makeConstraints { make in
make.centerX.equalTo(emojiLabel)
make.top.equalTo(emojiLabel.snp.bottom).offset(Styles.Sizes.tableSectionSpacing)
make.height.greaterThanOrEqualTo(messageLabel.font.pointSize)
}
resetAnimations()
// CAAnimations will be removed from layers on background. restore when foregrounding.
NotificationCenter.default
.addObserver(self,
selector: #selector(resetAnimations),
name: .UIApplicationWillEnterForeground,
object: nil
)
contentView.isAccessibilityElement = true
contentView.accessibilityLabel = NSLocalizedString("You have no new notifications!", comment: "Inbox Zero Accessibility Label")
//configure reviewGitHubAcess button
reviewGitHubAccessButton.setTitle(NSLocalizedString("Missing notifications?", comment: ""), for: .normal)
reviewGitHubAccessButton.isAccessibilityElement = false
reviewGitHubAccessButton.titleLabel?.textAlignment = .center
reviewGitHubAccessButton.backgroundColor = .clear
reviewGitHubAccessButton.titleLabel?.font = Styles.Text.finePrint.preferredFont
reviewGitHubAccessButton.setTitleColor(Styles.Colors.Gray.light.color, for: .normal)
reviewGitHubAccessButton.addTarget(self, action: #selector(reviewGitHubAccessButtonTapped),
for: .touchUpInside)
contentView.addSubview(reviewGitHubAccessButton)
let buttonWidth = (reviewGitHubAccessButton.titleLabel?.intrinsicContentSize.width ?? 0) + Styles.Sizes.gutter
let buttonHeight = (reviewGitHubAccessButton.titleLabel?.intrinsicContentSize.height ?? 0) + Styles.Sizes.gutter
reviewGitHubAccessButton.snp.makeConstraints { make in
make.centerX.equalTo(messageLabel)
make.width.equalTo(buttonWidth)
make.height.equalTo(buttonHeight)
make.top.greaterThanOrEqualTo(messageLabel.snp.bottom)
make.bottom.equalTo(contentView.snp.bottom).offset(-Styles.Sizes.tableSectionSpacing).priority(.low)
make.bottom.lessThanOrEqualTo(contentView.snp.bottom)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layoutContentView()
let width: CGFloat = 30
let height: CGFloat = 12
let rect = CGRect(origin: .zero, size: CGSize(width: width, height: height))
shadow.path = UIBezierPath(ovalIn: rect).cgPath
let bounds = contentView.bounds
shadow.bounds = rect
shadow.position = CGPoint(
x: bounds.width/2,
y: bounds.height/2 + 15
)
}
override func prepareForReuse() {
super.prepareForReuse()
resetAnimations()
}
override func didMoveToWindow() {
super.didMoveToWindow()
resetAnimations()
}
// MARK: Public API
func configure(
emoji: String,
message: String,
reviewGitHubAccessDelegate: NoNewNotificationsCellReviewAccessDelegate?
) {
emojiLabel.text = emoji
messageLabel.text = message
self.reviewGitHubAccessDelegate = reviewGitHubAccessDelegate
}
// MARK: Private API
@objc private func resetAnimations() {
guard trueUnlessReduceMotionEnabled else { return }
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let duration: TimeInterval = 1
let emojiBounce = CABasicAnimation(keyPath: "transform.translation.y")
emojiBounce.toValue = -10
emojiBounce.repeatCount = .greatestFiniteMagnitude
emojiBounce.autoreverses = true
emojiBounce.duration = duration
emojiBounce.timingFunction = timingFunction
emojiLabel.layer.add(emojiBounce, forKey: "nonewnotificationscell.emoji")
let shadowScale = CABasicAnimation(keyPath: "transform.scale")
shadowScale.toValue = 0.9
shadowScale.repeatCount = .greatestFiniteMagnitude
shadowScale.autoreverses = true
shadowScale.duration = duration
shadowScale.timingFunction = timingFunction
shadow.add(shadowScale, forKey: "nonewnotificationscell.shadow")
}
@objc func reviewGitHubAccessButtonTapped() {
reviewGitHubAccessDelegate?.didTapReviewAccess(cell: self)
}
}
| mit | e459989e28316bcb22a4fc8b72cabe5d | 36.869565 | 135 | 0.690832 | 5.593578 | false | false | false | false |
tmandry/Swindler | Sources/Application.swift | 1 | 27570 | import AXSwift
import Cocoa
import PromiseKit
// MARK: - Application
/// A running application.
public final class Application {
internal let delegate: ApplicationDelegate
// An Application holds a strong reference to the State (and therefore the StateDelegate).
// It should not be held internally by delegates, or it would create a reference cycle.
internal var state_: State!
internal init(delegate: ApplicationDelegate, stateDelegate: StateDelegate) {
self.delegate = delegate
state_ = State(delegate: stateDelegate)
}
/// This initializer only fails if the StateDelegate has been destroyed.
internal convenience init?(delegate: ApplicationDelegate) {
guard let stateDelegate = delegate.stateDelegate else {
log.debug("Application for delegate \(delegate) failed to initialize because of "
+ "unreachable StateDelegate")
return nil
}
self.init(delegate: delegate, stateDelegate: stateDelegate)
}
public var processIdentifier: pid_t { return delegate.processIdentifier }
public var bundleIdentifier: String? { return delegate.bundleIdentifier }
/// The global Swindler state.
public var swindlerState: State { return state_ }
/// The known windows of the application. Windows on spaces that we haven't seen yet aren't
/// included.
public var knownWindows: [Window] {
return delegate.knownWindows.compactMap({ Window(delegate: $0) })
}
/// The main window of the application.
/// -Note: Setting this will bring the window forward to just below the main window of the
/// frontmost application.
public var mainWindow: WriteableProperty<OfOptionalType<Window>> { return delegate.mainWindow }
/// The focused (or key) window of the application, the one currently accepting keyboard input.
/// Usually the same as the main window, or one of its helper windows such as a file open
/// dialog.
///
/// -Note: Sometimes the focused "window" is a sheet and not a window (i.e. it has no title bar
/// and cannot be moved by the user). In that case the value will be nil.
public var focusedWindow: Property<OfOptionalType<Window>> { return delegate.focusedWindow }
/// Whether the application is hidden.
public var isHidden: WriteableProperty<OfType<Bool>> { return delegate.isHidden }
}
public func ==(lhs: Application, rhs: Application) -> Bool {
return lhs.delegate.equalTo(rhs.delegate)
}
extension Application: Equatable {}
extension Application: CustomStringConvertible {
public var description: String {
return "Application(\(String(describing: delegate)))"
}
}
protocol ApplicationDelegate: AnyObject {
var processIdentifier: pid_t! { get }
var bundleIdentifier: String? { get }
var stateDelegate: StateDelegate? { get }
var knownWindows: [WindowDelegate] { get }
var mainWindow: WriteableProperty<OfOptionalType<Window>>! { get }
var focusedWindow: Property<OfOptionalType<Window>>! { get }
var isHidden: WriteableProperty<OfType<Bool>>! { get }
func equalTo(_ other: ApplicationDelegate) -> Bool
}
// MARK: - OSXApplicationDelegate
/// Implements ApplicationDelegate using the AXUIElement API.
final class OSXApplicationDelegate<
UIElement,
ApplicationElement: ApplicationElementType,
Observer: ObserverType
>: ApplicationDelegate
where Observer.UIElement == UIElement, ApplicationElement.UIElement == UIElement {
typealias Object = Application
typealias WinDelegate = OSXWindowDelegate<UIElement, ApplicationElement, Observer>
weak var stateDelegate: StateDelegate?
fileprivate weak var notifier: EventNotifier?
internal let axElement: UIElement // internal for testing only
internal var observer: Observer! // internal for testing only
fileprivate var windows: [WinDelegate] = []
// Used internally for deferring code until an OSXWindowDelegate has been initialized for a
// given UIElement.
fileprivate var newWindowHandler = NewWindowHandler<UIElement>()
fileprivate var initialized: Promise<Void>!
var mainWindow: WriteableProperty<OfOptionalType<Window>>!
var focusedWindow: Property<OfOptionalType<Window>>!
var isHidden: WriteableProperty<OfType<Bool>>!
var processIdentifier: pid_t!
lazy var runningApplication: NSRunningApplication =
NSRunningApplication(processIdentifier: self.processIdentifier)!
lazy var bundleIdentifier: String? =
self.runningApplication.bundleIdentifier
var knownWindows: [WindowDelegate] {
return windows.map({ $0 as WindowDelegate })
}
/// Initializes the object and returns it as a Promise that resolves once it's ready.
static func initialize(
axElement: ApplicationElement,
stateDelegate: StateDelegate,
notifier: EventNotifier
) -> Promise<OSXApplicationDelegate> {
return firstly { () -> Promise<OSXApplicationDelegate> in // capture thrown errors in promise chain
let appDelegate = try OSXApplicationDelegate(axElement, stateDelegate, notifier)
return appDelegate.initialized.map { appDelegate }
}
}
private init(_ axElement: ApplicationElement,
_ stateDelegate: StateDelegate,
_ notifier: EventNotifier) throws {
// TODO: filter out applications by activation policy
self.axElement = axElement.toElement
self.stateDelegate = stateDelegate
self.notifier = notifier
processIdentifier = try axElement.pid()
let notifications: [AXNotification] = [
.windowCreated,
.mainWindowChanged,
.focusedWindowChanged,
.applicationHidden,
.applicationShown
]
// Watch for notifications on app asynchronously.
let appWatched = watchApplicationElement(notifications)
// Get the list of windows asynchronously (after notifications are subscribed so we can't
// miss one).
let windowsFetched = fetchWindows(after: appWatched)
// Create a promise for the attribute dictionary we'll get from fetchAttributes.
let (attrsFetched, attrsSeal) = Promise<[AXSwift.Attribute: Any]>.pending()
// Some properties can't initialize until we fetch the windows. (WindowPropertyAdapter)
let initProperties =
PromiseKit.when(fulfilled: attrsFetched, windowsFetched)
.map { fetchedAttrs, _ in fetchedAttrs }
// Configure properties.
mainWindow = WriteableProperty(
MainWindowPropertyDelegate(axElement,
windowFinder: self,
windowDelegate: WinDelegate.self,
initProperties),
withEvent: ApplicationMainWindowChangedEvent.self,
receivingObject: Application.self,
notifier: self)
focusedWindow = Property(
WindowPropertyAdapter(AXPropertyDelegate(axElement, .focusedWindow, initProperties),
windowFinder: self,
windowDelegate: WinDelegate.self),
withEvent: ApplicationFocusedWindowChangedEvent.self,
receivingObject: Application.self,
notifier: self)
isHidden = WriteableProperty(
AXPropertyDelegate(axElement, .hidden, initProperties),
withEvent: ApplicationIsHiddenChangedEvent.self,
receivingObject: Application.self,
notifier: self)
let properties: [PropertyType] = [
mainWindow,
focusedWindow,
isHidden
]
let attributes: [Attribute] = [
.mainWindow,
.focusedWindow,
.hidden
]
// Fetch attribute values, after subscribing to notifications so there are no gaps.
fetchAttributes(attributes,
forElement: axElement,
after: appWatched,
seal: attrsSeal)
initialized = initializeProperties(properties).asVoid()
}
/// Called during initialization to set up an observer on the application element.
fileprivate func watchApplicationElement(_ notifications: [AXNotification]) -> Promise<Void> {
do {
weak var weakSelf = self
observer = try Observer(processID: processIdentifier, callback: { o, e, n in
weakSelf?.handleEvent(observer: o, element: e, notification: n)
})
} catch {
return Promise(error: error)
}
return Promise.value(()).done(on: .global()) {
for notification in notifications {
try traceRequest(self.axElement, "addNotification", notification) {
try self.observer.addNotification(notification, forElement: self.axElement)
}
}
}
}
func onSpaceChanged() -> Promise<Void> {
return fetchWindows(after: .value(())).then { _ in
return when(resolved: [
self.mainWindow.refresh().asVoid(),
self.focusedWindow.refresh().asVoid(),
]).asVoid()
}
}
/// Called during initialization to fetch a list of window elements and initialize window
/// delegates for them.
fileprivate func fetchWindows(after promise: Promise<Void>) -> Promise<Void> {
return promise.map(on: .global()) { () -> [UIElement]? in
// Fetch the list of window elements.
try traceRequest(self.axElement, "arrayAttribute", AXSwift.Attribute.windows) {
return try self.axElement.arrayAttribute(.windows)
}
}.then { maybeWindowElements -> Promise<Void> in
guard let windowElements = maybeWindowElements else {
throw OSXDriverError.missingAttribute(attribute: .windows,
onElement: self.axElement)
}
// Initialize OSXWindowDelegates from the window elements.
let windowPromises = windowElements.map({ windowElement in
self.createWindowForElementIfNotExists(windowElement)
})
return successes(windowPromises, onError: { index, error in
// Log any errors we encounter, but don't fail.
let windowElement = windowElements[index]
log.debug({
let description: String =
(try? windowElement.attribute(.description) ?? "") ?? ""
return "Couldn't initialize window for element \(windowElement) "
+ "(\(description)) of \(self): \(error)"
}())
}).asVoid()
}
}
var initializingWindows: [(UIElement, Promise<WinDelegate?>)] = []
/// Initializes an OSXWindowDelegate for the given axElement and adds it to `windows`, then
/// calls newWindowHandler handlers for that window, if any. If the window has already been
/// added, does nothing, and the returned promise resolves to nil.
fileprivate func createWindowForElementIfNotExists(_ axElement: UIElement)
-> Promise<WinDelegate?> {
guard let systemScreens = stateDelegate?.systemScreens else {
return .value(nil)
}
// Defer to the existing promise if the window is being initialized.
if let entry = initializingWindows.first(where: { $0.0 == axElement }) {
return entry.1.map({ _ in nil })
}
// Early return if the element already exists.
if self.windows.contains(where: { $0.axElement == axElement }) {
return .value(nil)
}
let promise = WinDelegate.initialize(
appDelegate: self, notifier: notifier, axElement: axElement, observer: observer,
systemScreens: systemScreens
).map { windowDelegate in
self.initializingWindows.removeAll(where: { $0.0 == axElement })
// This check needs to happen (again) here, because it's possible
// (though rare) to call this method from two different places
// (fetchWindows and onWindowCreated) before initialization of
// either one is complete.
if self.windows.contains(where: { $0.axElement == axElement }) {
return nil
}
self.windows.append(windowDelegate)
self.newWindowHandler.windowCreated(axElement)
return windowDelegate
}.recover { error -> Promise<WinDelegate?> in
// If this initialization of WinDelegate failed, the window is somehow invalid and we
// won't be seeing it again. Here we assume that if there were other initializations
// requested, they won't succeed either.
self.newWindowHandler.removeAllForUIElement(axElement)
throw error
}
initializingWindows.append((axElement, promise))
return promise
}
func equalTo(_ rhs: ApplicationDelegate) -> Bool {
if let other = rhs as? OSXApplicationDelegate {
return axElement == other.axElement
} else {
return false
}
}
}
/// Event handlers
extension OSXApplicationDelegate {
fileprivate func handleEvent(observer: Observer.Context,
element: UIElement,
notification: AXSwift.AXNotification) {
assert(Thread.current.isMainThread)
log.trace("Received \(notification) on \(element)")
switch notification {
case .windowCreated:
onWindowCreated(element)
case .mainWindowChanged:
onWindowTypePropertyChanged(mainWindow, element: element)
case .focusedWindowChanged:
onWindowTypePropertyChanged(focusedWindow, element: element)
case .applicationShown, .applicationHidden:
isHidden.refresh()
default:
onWindowLevelEvent(notification, windowElement: element)
}
}
fileprivate func onWindowCreated(_ windowElement: UIElement) {
addWindowElement(windowElement).catch { error in
log.trace("Could not watch window element on \(self): \(error)")
}
}
// Also used by FakeSwindler.
internal func addWindowElement(_ windowElement: UIElement) -> Promise<WinDelegate?> {
return firstly {
createWindowForElementIfNotExists(windowElement)
}.map { windowDelegate in
guard let windowDelegate = windowDelegate,
let window = Window(delegate: windowDelegate)
else { return nil }
self.notifier?.notify(WindowCreatedEvent(external: true, window: window))
return windowDelegate
}
}
/// Does special handling for updating of properties that hold windows (mainWindow,
/// focusedWindow).
fileprivate func onWindowTypePropertyChanged(_ property: Property<OfOptionalType<Window>>,
element: UIElement) {
if element == axElement {
// Was passed the application (this means there is no main/focused window); we can
// refresh immediately.
property.refresh()
} else if windows.contains(where: { $0.axElement == element }) {
// Was passed an already-initialized window; we can refresh immediately.
property.refresh()
} else {
// We don't know about the element that has been passed. Wait until the window is
// initialized.
addWindowElement(element)
.done { _ in property.refresh() }
.recover { err in
log.error("Error while updating window property: \(err)")
}
// In some cases, the element is actually IS the application element, but equality
// checks inexplicably return false. (This has been observed for Finder.) In this case
// we will never see a new window for this element. Asynchronously check the element
// role to handle this case.
checkIfWindowPropertyElementIsActuallyApplication(element, property: property)
}
}
fileprivate func checkIfWindowPropertyElementIsActuallyApplication(
_ element: UIElement,
property: Property<OfOptionalType<Window>>
) {
Promise.value(()).map(on: .global()) { () -> Role? in
guard let role: String = try element.attribute(.role) else { return nil }
return Role(rawValue: role)
}.done { role in
if role == .application {
// There is no main window; we can refresh immediately.
property.refresh()
// Remove the handler that will never be called.
self.newWindowHandler.removeAllForUIElement(element)
}
}.catch { error in
switch error {
case AXError.invalidUIElement:
// The window is already gone.
property.refresh()
self.newWindowHandler.removeAllForUIElement(element)
default:
// TODO: Retry on timeout
// Just refresh and hope for the best. Leave the handler in case the element does
// show up again.
property.refresh()
log.warn("Received MainWindowChanged on unknown element \(element), then \(error) "
+ "when trying to read its role")
}
}
// _______________________________
// < Now that's a long method name >
// -------------------------------
// \ . .
// \ / `. .' "
// \ .---. < > < > .---.
// \ | \ \ - ~ ~ - / / |
// _____ ..-~ ~-..-~
// | | \~~~\.' `./~~~/
// --------- \__/ \__/
// .' O \ / / \ "
// (_____, `._.' | } \/~~~/
// `----. / } | / \__/
// `-. | / | / `. ,~~|
// ~-.__| /_ - ~ ^| /- _ `..-'
// | / | / ~-. `-. _ _ _
// |_____| |_____| ~ - . _ _ _ _ _>
}
fileprivate func onWindowLevelEvent(_ notification: AXSwift.AXNotification,
windowElement: UIElement) {
func handleEvent(_ windowDelegate: WinDelegate) {
windowDelegate.handleEvent(notification, observer: observer)
if .uiElementDestroyed == notification {
// Remove window.
windows = windows.filter({ !$0.equalTo(windowDelegate) })
guard let window = Window(delegate: windowDelegate) else { return }
notifier?.notify(WindowDestroyedEvent(external: true, window: window))
}
}
if let windowDelegate = findWindowDelegateByElement(windowElement) {
handleEvent(windowDelegate)
} else {
log.debug("Notification \(notification) on unknown element \(windowElement), deferring")
newWindowHandler.performAfterWindowCreatedForElement(windowElement) {
if let windowDelegate = self.findWindowDelegateByElement(windowElement) {
handleEvent(windowDelegate)
} else {
// Window was already destroyed.
log.debug("Deferred notification \(notification) on window element "
+ "\(windowElement) never reached delegate")
}
}
}
}
fileprivate func findWindowDelegateByElement(_ axElement: UIElement) -> WinDelegate? {
return windows.filter({ $0.axElement == axElement }).first
}
}
extension OSXApplicationDelegate: PropertyNotifier {
func notify<Event: PropertyEventType>(_ event: Event.Type,
external: Bool,
oldValue: Event.PropertyType,
newValue: Event.PropertyType)
where Event.Object == Application {
guard let application = Application(delegate: self) else { return }
notifier?.notify(
Event(external: external, object: application, oldValue: oldValue, newValue: newValue)
)
}
func notifyInvalid() {
log.debug("Application invalidated: \(self)")
// TODO:
}
}
extension OSXApplicationDelegate: CustomStringConvertible {
var description: String {
do {
let pid = try self.axElement.pid()
if let app = NSRunningApplication(processIdentifier: pid),
let bundle = app.bundleIdentifier {
return bundle
}
return "pid=\(pid)"
} catch {
return "Invalid"
}
}
}
// MARK: Support
/// Stores internal new window handlers for OSXApplicationDelegate.
private struct NewWindowHandler<UIElement: Equatable> {
fileprivate var handlers: [HandlerType<UIElement>] = []
mutating func performAfterWindowCreatedForElement(_ windowElement: UIElement,
handler: @escaping () -> Void) {
assert(Thread.current.isMainThread)
handlers.append(HandlerType(windowElement: windowElement, handler: handler))
}
mutating func removeAllForUIElement(_ windowElement: UIElement) {
assert(Thread.current.isMainThread)
handlers = handlers.filter({ $0.windowElement != windowElement })
}
mutating func windowCreated(_ windowElement: UIElement) {
assert(Thread.current.isMainThread)
handlers.filter({ $0.windowElement == windowElement }).forEach { entry in
entry.handler()
}
removeAllForUIElement(windowElement)
}
}
private struct HandlerType<UIElement> {
let windowElement: UIElement
let handler: () -> Void
}
// MARK: PropertyDelegates
/// Used by WindowPropertyAdapter to match a UIElement to a Window object.
protocol WindowFinder: AnyObject {
// This would be more elegantly implemented by passing the list of delegates with every refresh
// request, but currently we don't have a way of piping that through.
associatedtype UIElement: UIElementType
func findWindowByElement(_ element: UIElement) -> Window?
}
extension OSXApplicationDelegate: WindowFinder {
func findWindowByElement(_ element: UIElement) -> Window? {
if let windowDelegate = findWindowDelegateByElement(element) {
return Window(delegate: windowDelegate)
} else {
return nil
}
}
}
protocol OSXDelegateType {
associatedtype UIElement: UIElementType
var axElement: UIElement { get }
var isValid: Bool { get }
}
extension OSXWindowDelegate: OSXDelegateType {}
/// Custom PropertyDelegate for the mainWindow property.
private final class MainWindowPropertyDelegate<
AppElement: ApplicationElementType,
WinFinder: WindowFinder,
WinDelegate: OSXDelegateType
>: PropertyDelegate
where WinFinder.UIElement == WinDelegate.UIElement {
typealias T = Window
typealias UIElement = WinFinder.UIElement
let readDelegate: WindowPropertyAdapter<AXPropertyDelegate<UIElement, AppElement>,
WinFinder, WinDelegate>
init(_ appElement: AppElement,
windowFinder: WinFinder,
windowDelegate: WinDelegate.Type,
_ initPromise: Promise<[Attribute: Any]>) {
readDelegate = WindowPropertyAdapter(
AXPropertyDelegate(appElement, .mainWindow, initPromise),
windowFinder: windowFinder,
windowDelegate: windowDelegate)
}
func initialize() -> Promise<Window?> {
return readDelegate.initialize()
}
func readValue() throws -> Window? {
return try readDelegate.readValue()
}
func writeValue(_ newValue: Window) throws {
// Extract the element from the window delegate.
guard let winDelegate = newValue.delegate as? WinDelegate else {
throw PropertyError.illegalValue
}
// Check early to see if the element is still valid. If it becomes invalid after this check,
// the same error will get thrown, it will just take longer.
guard winDelegate.isValid else {
throw PropertyError.illegalValue
}
// Note: This is happening on a background thread, so only properties that don't change
// should be accessed (the axElement).
// To set the main window, we have to access the .main attribute of the window element and
// set it to true.
let writeDelegate = AXPropertyDelegate<Bool, UIElement>(
winDelegate.axElement, .main, Promise.value([:])
)
try writeDelegate.writeValue(true)
}
}
/// Converts a UIElement attribute into a readable Window property.
private final class WindowPropertyAdapter<
Delegate: PropertyDelegate,
WinFinder: WindowFinder,
WinDelegate: OSXDelegateType
>: PropertyDelegate
where Delegate.T == WinFinder.UIElement, WinFinder.UIElement == WinDelegate.UIElement {
typealias T = Window
let delegate: Delegate
weak var windowFinder: WinFinder?
init(_ delegate: Delegate, windowFinder: WinFinder, windowDelegate: WinDelegate.Type) {
self.delegate = delegate
self.windowFinder = windowFinder
}
func readValue() throws -> Window? {
guard let element = try delegate.readValue() else {
return nil
}
let window = findWindowByElement(element)
if window == nil {
// This can happen if, for instance, the window was destroyed since the refresh was
// requested.
log.debug("While updating property value, could not find window matching element: "
+ String(describing: element))
}
return window
}
func writeValue(_ newValue: Window) throws {
// If we got here, a property is wrongly configured.
fatalError("Writing directly to an \"object\" property is not supported by the AXUIElement "
+ "API")
}
func initialize() -> Promise<Window?> {
return delegate.initialize().map { maybeElement in
guard let element = maybeElement else {
return nil
}
return self.findWindowByElement(element)
}
}
fileprivate func findWindowByElement(_ element: Delegate.T) -> Window? {
// Avoid using locks by forcing calls out to `windowFinder` to happen on the main thead.
var window: Window?
if Thread.current.isMainThread {
window = windowFinder?.findWindowByElement(element)
} else {
DispatchQueue.main.sync {
window = self.windowFinder?.findWindowByElement(element)
}
}
return window
}
}
| mit | 55344e1ebd562ef289a58c1ed649ed19 | 39.484581 | 107 | 0.606783 | 5.478935 | false | false | false | false |
AzenXu/Memo | Memo/Common/Helpers/SmartTask.swift | 1 | 1313 | //
// SmartTask.swift
// Base
//
// Created by kenneth wang on 16/5/8.
// Copyright © 2016年 st. All rights reserved.
//
import Foundation
import UIKit
public typealias CancelableTask = (cancel: Bool) -> Void
/**
延迟执行任务
- parameter time: 延迟时间
- parameter work: 任务闭包
- returns:
*/
public func delay(time: NSTimeInterval, work: dispatch_block_t) -> CancelableTask? {
var finalTask: CancelableTask?
let cancelableTask: CancelableTask = { cancel in
if cancel {
finalTask = nil // key
} else {
dispatch_async(dispatch_get_main_queue(), work)
}
}
finalTask = cancelableTask
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
if let task = finalTask {
task(cancel: false)
}
}
return finalTask
}
/**
取消执行任务
- parameter cancelableTask:
*/
public func cancel(cancelableTask: CancelableTask?) {
cancelableTask?(cancel: true)
}
/**
测量函数的执行时间
- parameter f: 函数
*/
public func measure(f: () -> ()) {
let start = CACurrentMediaTime()
f()
let end = CACurrentMediaTime()
print("测量时间:\(end - start)")
}
| mit | 8a8e4673a6011e62c4ad181672a4386c | 18.046154 | 117 | 0.6042 | 3.856698 | false | false | false | false |
coderZsq/coderZsq.target.swift | StudyNotes/Swift Note/LiveBroadcast/Client/LiveBroadcast/Classes/Main/View/PageView/ContentView.swift | 1 | 4770 | //
// ContentView.swift
// LiveBroadcast
//
// Created by 朱双泉 on 2018/12/10.
// Copyright © 2018 Castie!. All rights reserved.
//
import UIKit
private let kContentCellID = "kContentCellID"
protocol ContentViewDelegate: class {
func contentView(_ contentView: ContentView, targetIndex: Int)
func contentView(_ contentView: ContentView, targetIndex: Int, progress: CGFloat)
}
class ContentView: UIView {
weak var delegate: ContentViewDelegate?
fileprivate var childVcs: [UIViewController]
fileprivate var parentVc: UIViewController
fileprivate var startOffsetX: CGFloat = 0
fileprivate var isForbidScroll = false
fileprivate lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = self.bounds.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kContentCellID)
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.scrollsToTop = false
collectionView.showsHorizontalScrollIndicator = false
return collectionView
}()
init(frame: CGRect, childVcs: [UIViewController], parentVc: UIViewController) {
self.childVcs = childVcs
self.parentVc = parentVc
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ContentView {
fileprivate func setupUI() {
for childVc in childVcs {
parentVc.addChild(childVc)
}
addSubview(collectionView)
}
}
extension ContentView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kContentCellID, for: indexPath)
for subView in cell.contentView.subviews {
subView.removeFromSuperview()
}
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
extension ContentView: UICollectionViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
contentEndScroll()
scrollView.isScrollEnabled = true
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
contentEndScroll()
} else {
scrollView.isScrollEnabled = false
}
}
private func contentEndScroll() {
guard !isForbidScroll else { return }
let currentIndex = Int(collectionView.contentOffset.x / collectionView.bounds.width)
delegate?.contentView(self, targetIndex: currentIndex)
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScroll = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard startOffsetX != scrollView.contentOffset.x, !isForbidScroll else {
return
}
var targetIndex = 0
var progress: CGFloat = 0.0
let currentIndex = Int(startOffsetX / scrollView.bounds.width)
if startOffsetX < scrollView.contentOffset.x {
targetIndex = currentIndex + 1
if targetIndex > childVcs.count - 1 {
targetIndex = childVcs.count - 1
}
progress = (scrollView.contentOffset.x - startOffsetX) / scrollView.bounds.width
} else {
targetIndex = currentIndex - 1
if targetIndex < 0 {
targetIndex = 0
}
progress = (startOffsetX - scrollView.contentOffset.x) / scrollView.bounds.width
}
delegate?.contentView(self, targetIndex: targetIndex, progress: progress)
}
}
extension ContentView: TitleViewDelegate {
func titleView(_ titleView: TitleView, targetIndex: Int) {
isForbidScroll = true
let indexPath = IndexPath(item: targetIndex, section: 0)
collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
}
}
| mit | 8d095d7434d7461041d5bfbc54f1cfb7 | 33.021429 | 121 | 0.669746 | 5.623377 | false | false | false | false |
pnhechim/Fiestapp-iOS | Fiestapp/Fiestapp/ViewControllers/Home/HomeViewController.swift | 1 | 2134 | //
// HomeViewController.swift
// Fiestapp
//
// Created by Nicolás Hechim on 2/7/17.
// Copyright © 2017 Mint. All rights reserved.
//
import UIKit
class HomeViewController: UITabBarController, UITabBarControllerDelegate {
// UITabBarDelegate
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
if item.title == "Cerrar sesión" {
let alertController = UIAlertController(title: "Cerrar sesión", message: "¿Seguro que querés cerrar sesión? Necesitás estar logueado para utilizar Fiestapp!", preferredStyle: UIAlertControllerStyle.actionSheet)
alertController.addAction(UIAlertAction(title: "Cancelar", style: UIAlertActionStyle.cancel) {
(result : UIAlertAction) -> Void in
})
alertController.addAction(UIAlertAction(title: "Sí", style: UIAlertActionStyle.destructive)
{
(result : UIAlertAction) -> Void in
FirebaseService.shared.cerrarSesion()
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") {
UIApplication.shared.keyWindow?.rootViewController = viewController
self.dismiss(animated: true, completion: nil)
}
})
self.present(alertController, animated: true, completion: nil)
}
else if item.title == "Mis fiestas" {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.currentSelectedIndex = 0
}
else if item.title == "Nueva fiesta" {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.currentSelectedIndex = 1
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 166b46c753818c3e8cb22eaed665e37b | 36.946429 | 222 | 0.619294 | 5.407125 | false | false | false | false |
youprofit/firefox-ios | Client/Frontend/Settings/SearchSettingsTableViewController.swift | 14 | 10348 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class SearchSettingsTableViewController: UITableViewController {
private let SectionDefault = 0
private let ItemDefaultEngine = 0
private let ItemDefaultSuggestions = 1
private let NumberOfItemsInSectionDefault = 2
private let SectionOrder = 1
private let NumberOfSections = 2
private let IconSize = CGSize(width: OpenSearchEngine.PreferredIconSize, height: OpenSearchEngine.PreferredIconSize)
private let SectionHeaderIdentifier = "SectionHeaderIdentifier"
var model: SearchEngines!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("Search", comment: "Navigation title for search settings.")
// To allow re-ordering the list of search engines at all times.
tableView.editing = true
// So that we push the default search engine controller on selection.
tableView.allowsSelectionDuringEditing = true
tableView.registerClass(SettingsTableSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
// Insert Done button if being presented outside of the Settings Nav stack
if !(self.navigationController is SettingsNavigationController) {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Done", comment: "Done button label for search settings table"), style: .Done, target: self, action: "SELDismiss")
}
tableView.tableFooterView = UIView()
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell!
var engine: OpenSearchEngine!
if indexPath.section == SectionDefault {
switch indexPath.item {
case ItemDefaultEngine:
engine = model.defaultEngine
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.editingAccessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.accessibilityLabel = NSLocalizedString("Default Search Engine", comment: "Accessibility label for default search engine setting.")
cell.accessibilityValue = engine.shortName
cell.textLabel?.text = engine.shortName
cell.imageView?.image = engine.image?.createScaled(IconSize)
case ItemDefaultSuggestions:
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.textLabel?.text = NSLocalizedString("Show Search Suggestions", comment: "Label for show search suggestions setting.")
let toggle = UISwitch()
toggle.onTintColor = UIConstants.ControlTintColor
toggle.addTarget(self, action: "SELdidToggleSearchSuggestions:", forControlEvents: UIControlEvents.ValueChanged)
toggle.on = model.shouldShowSearchSuggestions
cell.editingAccessoryView = toggle
cell.selectionStyle = .None
default:
// Should not happen.
break
}
} else {
// The default engine is not a quick search engine.
let index = indexPath.item + 1
engine = model.orderedEngines[index]
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.showsReorderControl = true
let toggle = UISwitch()
toggle.onTintColor = UIConstants.ControlTintColor
// This is an easy way to get from the toggle control to the corresponding index.
toggle.tag = index
toggle.addTarget(self, action: "SELdidToggleEngine:", forControlEvents: UIControlEvents.ValueChanged)
toggle.on = model.isEngineEnabled(engine)
cell.editingAccessoryView = toggle
cell.textLabel?.text = engine.shortName
cell.imageView?.image = engine.image?.createScaled(IconSize)
cell.selectionStyle = .None
}
// So that the seperator line goes all the way to the left edge.
cell.separatorInset = UIEdgeInsetsZero
return cell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return NumberOfSections
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == SectionDefault {
return NumberOfItemsInSectionDefault
} else {
// The first engine -- the default engine -- is not shown in the quick search engine list.
return model.orderedEngines.count - 1
}
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if indexPath.section == SectionDefault && indexPath.item == ItemDefaultEngine {
let searchEnginePicker = SearchEnginePicker()
// Order alphabetically, so that picker is always consistently ordered.
// Every engine is a valid choice for the default engine, even the current default engine.
searchEnginePicker.engines = model.orderedEngines.sort { e, f in e.shortName < f.shortName }
searchEnginePicker.delegate = self
searchEnginePicker.selectedSearchEngineName = model.defaultEngine.shortName
navigationController?.pushViewController(searchEnginePicker, animated: true)
}
return nil
}
// Don't show delete button on the left.
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.None
}
// Don't reserve space for the delete button on the left.
override func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
// Hide a thin vertical line that iOS renders between the accessoryView and the reordering control.
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.editing {
for v in cell.subviews {
if v.frame.width == 1.0 {
v.backgroundColor = UIColor.clearColor()
}
}
}
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderView
var sectionTitle: String
if section == SectionDefault {
sectionTitle = NSLocalizedString("Default Search Engine", comment: "Title for default search engine settings section.")
} else {
sectionTitle = NSLocalizedString("Quick-search Engines", comment: "Title for quick-search engines settings section.")
}
headerView.titleLabel.text = sectionTitle
return headerView
}
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if indexPath.section == SectionDefault {
return false
} else {
return true
}
}
override func tableView(tableView: UITableView, moveRowAtIndexPath indexPath: NSIndexPath, toIndexPath newIndexPath: NSIndexPath) {
// The first engine (default engine) is not shown in the list, so the indices are off-by-1.
let index = indexPath.item + 1
let newIndex = newIndexPath.item + 1
let engine = model.orderedEngines.removeAtIndex(index)
model.orderedEngines.insert(engine, atIndex: newIndex)
tableView.reloadData()
}
// Snap to first or last row of the list of engines.
override func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath {
// You can't drag or drop on the default engine.
if sourceIndexPath.section == SectionDefault || proposedDestinationIndexPath.section == SectionDefault {
return sourceIndexPath
}
if (sourceIndexPath.section != proposedDestinationIndexPath.section) {
var row = 0
if (sourceIndexPath.section < proposedDestinationIndexPath.section) {
row = tableView.numberOfRowsInSection(sourceIndexPath.section) - 1
}
return NSIndexPath(forRow: row, inSection: sourceIndexPath.section)
}
return proposedDestinationIndexPath
}
func SELdidToggleEngine(toggle: UISwitch) {
let engine = model.orderedEngines[toggle.tag] // The tag is 1-based.
if toggle.on {
model.enableEngine(engine)
} else {
model.disableEngine(engine)
}
}
func SELdidToggleSearchSuggestions(toggle: UISwitch) {
// Setting the value in settings dismisses any opt-in.
model.shouldShowSearchSuggestionsOptIn = false
model.shouldShowSearchSuggestions = toggle.on
}
func SELcancel() {
navigationController?.popViewControllerAnimated(true)
}
func SELDismiss() {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
extension SearchSettingsTableViewController: SearchEnginePickerDelegate {
func searchEnginePicker(searchEnginePicker: SearchEnginePicker, didSelectSearchEngine searchEngine: OpenSearchEngine?) {
if let engine = searchEngine {
model.defaultEngine = engine
self.tableView.reloadData()
}
navigationController?.popViewControllerAnimated(true)
}
}
| mpl-2.0 | 1eeb2bcdf15a0175b40396b3b6dcdc6a | 43.796537 | 207 | 0.68448 | 6.012783 | false | false | false | false |
TalkingBibles/Talking-Bible-iOS | TalkingBible/Player.swift | 1 | 12297 | //
// Copyright 2015 Talking Bibles International
//
// 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 Swift
import Foundation
import AVFoundation
import TMReachability
final class Player: NSObject {
class var sharedManager: Player {
struct Singleton {
static let player = Player()
}
return Singleton.player
}
let reach: TMReachability
var machine: StateMachine<Player>!
enum PlayerState: Int {
case Unknown = 0
case NoConnection = 1
case Unplayable = 2
case NotReady = 3
case AlmostReady = 4
case Ready = 5
case Playing = 6
case Paused = 7
func description() -> String {
let descriptions = [
"Unknown",
"NoConnection",
"Unplayable",
"NotReady",
"AlmostReady",
"Ready",
"Playing",
"Paused"
]
return descriptions[self.hashValue]
}
}
var onReady: (() -> ())?
typealias PlayerItemQueue = [AVPlayerItem]
struct Constants {
struct KeyPaths {
static let currentItem = "currentItem"
static let status = "status"
static let rate = "rate"
static let duration = "duration"
}
static let interval = CMTimeMakeWithSeconds(1.0, Int32(NSEC_PER_SEC))
}
private var player: AVPlayer! {
willSet {
if let player = player {
log.info("Removing player observers")
player.removeObserver(self, forKeyPath: Constants.KeyPaths.currentItem)
player.removeObserver(self, forKeyPath: Constants.KeyPaths.status)
player.removeObserver(self, forKeyPath: Constants.KeyPaths.rate)
for timeObserver in timeObservers {
player.removeTimeObserver(timeObserver)
}
timeObservers = []
}
}
didSet {
log.info("Adding player observers")
player.addObserver(self, forKeyPath: Constants.KeyPaths.currentItem, options: .New, context: nil)
player.addObserver(self, forKeyPath: Constants.KeyPaths.status, options: .New, context: nil)
player.addObserver(self, forKeyPath: Constants.KeyPaths.rate, options: [.Initial, .New], context: nil)
timeObservers.append(player.addPeriodicTimeObserverForInterval(Constants.interval, queue: nil) { time in
if time.flags == CMTimeFlags.Valid {
postNotification(playerTimeUpdatedNotification, value: time)
}
})
}
}
private var mp3Queue: [String]!
private var playerItemQueue: PlayerItemQueue! {
willSet {
if let queue = playerItemQueue {
log.info("Removing \(queue.count) observers from playerItemQueue")
for playerItem in queue {
playerItem.removeObserver(self, forKeyPath: Constants.KeyPaths.status, context: nil)
}
}
}
didSet {
log.info("Adding \(playerItemQueue.count) observers to playerItemQueue")
for playerItem in playerItemQueue {
playerItem.addObserver(self, forKeyPath: Constants.KeyPaths.status, options: .New, context: nil)
}
}
}
var currentTime: CMTime {
return player.currentTime()
}
var duration: CMTime {
return player.currentItem?.duration ?? CMTimeMake(0, 16)
}
private var _currentPlayerItemIndex: Int = 0
var currentPlayerItemIndex: Int {
get {
return _currentPlayerItemIndex
}
}
/// Strong Links
private var timeObservers = [AnyObject]()
/// Time Tracking
private var _currentPercentComplete: Float {
let currentTime = player.currentTime()
if let currentDuration = player.currentItem?.duration {
return Float(CMTimeGetSeconds(currentTime)) / Float(CMTimeGetSeconds(currentDuration))
}
return Float(0)
}
override init() {
reach = TMReachability.reachabilityForInternetConnection()
super.init()
machine = StateMachine(initialState: .NotReady, delegate: self)
replacePlayer()
}
// MARK: Setup
private func replaceQueue() {
var tempPlayerItemQueue = [AVPlayerItem]()
for mp3 in mp3Queue {
guard let url = NSURL(string: mp3) else {
return
}
let playerItem = AVPlayerItem(URL: url)
tempPlayerItemQueue.append(playerItem)
}
playerItemQueue = tempPlayerItemQueue
}
private func replacePlayer() {
log.info("Replacing player")
machine.state = .NotReady
player = AVPlayer()
}
private func recoverFromFailure() {
dispatch_async(dispatch_get_main_queue()) {
self.replaceQueue()
self.replacePlayer()
self.selectPlayerItem(self._currentPlayerItemIndex, timeInterval: 0.0)
}
}
// MARK: Public methods
func playItem() {
player.play()
}
func pauseItem() {
onReady = nil
player.pause()
}
func toggleItem() {
switch machine.state {
case .Playing:
onReady = nil
player.pause()
case .Ready, .Paused:
player.play()
default:
break
}
}
func nextPlayerItem() {
let nextPlayerItemIndex = _currentPlayerItemIndex + 1
if nextPlayerItemIndex < playerItemQueue.count {
selectPlayerItem(nextPlayerItemIndex, timeInterval: 0.0)
}
}
func previousPlayerItem() {
if player.rate > 0.0 && player.error == nil {
if _currentPercentComplete > 0.1 || _currentPlayerItemIndex == 0 {
seekToTime(Float(0)) { _ in }
return
}
}
let previousPlayerItemIndex = _currentPlayerItemIndex - 1
if previousPlayerItemIndex >= 0 {
selectPlayerItem(previousPlayerItemIndex, timeInterval: 0.0)
}
}
func seekToTime(time: Float, completionHandler: (Bool) -> ()) {
guard let currentItem = player.currentItem else {
return
}
let status = currentItem.status as AVPlayerItemStatus
if status == .ReadyToPlay {
currentItem.seekToTime(CMTimeMakeWithSeconds(Float64(time), currentItem.duration.timescale), completionHandler: completionHandler)
} else {
completionHandler(false)
}
}
func seekIncrementally() {
let currentTime = player.currentTime()
if let currentDuration = player.currentItem?.duration {
let playerItem = playerItemQueue[_currentPlayerItemIndex]
let fifteenSecondsLater = CMTimeMakeWithSeconds(CMTimeGetSeconds(currentTime) + 15, currentTime.timescale)
if CMTimeCompare(fifteenSecondsLater, currentDuration) <= 0 {
playerItem.seekToTime(fifteenSecondsLater)
} else {
playerItem.seekToTime(currentDuration)
}
}
}
func seekDecrementally() {
let currentTime = player.currentTime()
if let currentDuration = player.currentItem?.duration {
let playerItem = playerItemQueue[_currentPlayerItemIndex]
let fifteenSecondsEarlier = CMTimeMakeWithSeconds(CMTimeGetSeconds(currentTime) - 15, currentTime.timescale)
if CMTimeCompare(fifteenSecondsEarlier, currentDuration) >= 0 {
playerItem.seekToTime(fifteenSecondsEarlier)
} else {
playerItem.seekToTime(CMTimeMakeWithSeconds(0, currentTime.timescale))
}
}
}
func replaceQueue(queue: [String]) {
mp3Queue = queue
_currentPlayerItemIndex = 0
replaceQueue()
replacePlayer()
}
func selectPlayerItem(index: Int, timeInterval: NSTimeInterval) {
if playerItemQueue.count <= index {
return
}
_currentPlayerItemIndex = index
postNotification(playerItemInQueueChangedNotification, value: _currentPlayerItemIndex)
self.player.replaceCurrentItemWithPlayerItem(playerItemQueue[index])
onReady = {
self.onReady = nil
self.seekToTime(Float(timeInterval), completionHandler: { success in
if success {
self.playItem()
}
})
return
}
}
// MARK: Observers
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard let keyPath = keyPath else { return }
switch (object, keyPath) {
case (let player as AVPlayer, Constants.KeyPaths.status):
switch player.status {
case .Failed:
handleFailure(player: player)
default:
log.info("AVPlayer is \(player.status.rawValue)")
}
case (let player as AVPlayer, Constants.KeyPaths.rate):
if player.rate > 0.0 && player.error == nil {
machine.state = .Playing
} else {
machine.state = .Paused
}
case (_, Constants.KeyPaths.currentItem):
machine.state = .AlmostReady
case (let currentItem as AVPlayerItem, Constants.KeyPaths.status):
switch currentItem.status {
case .ReadyToPlay:
machine.state = .Ready
case .Failed:
handleFailure(playerItem: currentItem)
default:
log.warning("AVPlayerItem status is unknown")
}
default:
log.warning("\(keyPath) happened with \(object), which is unimplemented")
}
}
// MARK: Error Handling
private func handleFailure(player player: AVPlayer) {
guard let error = player.error else {
return recoverFromFailure()
}
log.error("AVPlayer failed because: [\(error.code)] \(error.localizedDescription)")
machine.state = .Unplayable
recoverFromFailure()
}
private func handleFailure(playerItem item: AVPlayerItem) {
guard let error = item.error else {
return recoverFromFailure()
}
log.error("AVPlayerItem [\(item.asset)] failed because: [\(error.code)] \(error.localizedDescription)")
switch error.code {
case -1003:
fallthrough
case -1100:
log.warning("AVPlayerItem is unplayable")
machine.state = .Unplayable
case -1005, -1009:
log.warning("AVPlayer has no connection")
machine.state = .NoConnection
default:
recoverFromFailure()
}
}
private func doWhenReachable(completionHandler: () -> ()) {
reach.reachableBlock = { (reach: TMReachability!) in
reach.stopNotifier()
completionHandler()
}
reach.startNotifier()
}
}
extension Player: StateMachineDelegateProtocol{
typealias StateType = PlayerState
func shouldTransitionFrom(from:StateType, to:StateType)->Bool{
// log.debug("should? from: \(from.description()), to: \(to.description())")
switch (from, to){
case (.NoConnection, .NoConnection), (.NotReady, .NotReady), (.AlmostReady, .AlmostReady):
return false
case (_, .NoConnection):
doWhenReachable { [unowned self] in
self.recoverFromFailure()
}
return true
case (.NoConnection, _):
return reach.isReachable()
case (_, .Unplayable):
if !reach.isReachable() {
machine.state = .NoConnection
return false
}
return true
case (_, .Ready):
if !reach.isReachable() {
machine.state = .NoConnection
return false
}
if let currentItem = self.player.currentItem {
postNotification(playerDurationUpdatedNotification, value: currentItem.duration)
}
onReady?()
return true
case (.NotReady, .Paused), (.AlmostReady, .Paused), (.Ready, .Paused):
return false
case (_, .AlmostReady), (_, .NotReady), (_, .Unknown), (_, .Paused), (_, .Playing):
return true
default:
return false
}
}
func didTransitionFrom(from:StateType, to:StateType){
postNotification(playerStateChangedNotification, value: to)
// log.debug("did. from: \(from.description()), to: \(to.description())")
}
} | apache-2.0 | fae5d66183bebbeffa20cc2d44aa7436 | 26.088106 | 155 | 0.639099 | 4.841339 | false | false | false | false |
WCByrne/CBToolkit | CBToolkit/CBToolkit/CBSliderCollectionViewLayout.swift | 1 | 6000 | // CBSliderCell.swift
//
// Created by Wes Byrne on 2/11/15.
// Copyright (c) 2015 WCBMedia. All rights reserved.
//
import Foundation
import UIKit
/// A very simple full size 'slider' CollectionViewLayout for horizontal sliding
public class CBSliderCollectionViewLayout : UICollectionViewFlowLayout {
/// The currently displayed row in the collectionView. This must be set to handle autoscrolling.
public var currentIndex: Int = 0
/// Start and stop the collection view autoscroll.
public var autoScroll: Bool = false {
didSet {
if autoScroll {
startAutoScroll()
}
else {
cancelAutoScroll()
}
}
}
/// The delay between scroll animations
public var autoScrollDelay: TimeInterval = 5
private var autoScrollTimer: Timer?
public override init() {
super.init()
self.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
self.minimumInteritemSpacing = 0
self.minimumLineSpacing = 0
self.scrollDirection = UICollectionViewScrollDirection.horizontal
}
/**
Initialize the layout with a collectionView
- parameter collectionView: The collectionView to apply the layout to
- returns: The intialized layout
*/
public convenience init(collectionView: UICollectionView) {
self.init()
collectionView.collectionViewLayout = self;
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
Start the autoscroll timer to begin animated slides through the cells. Repeats until cancel is called.
*/
public func startAutoScroll() {
if autoScrollTimer != nil { return }
if autoScroll {
autoScrollTimer = Timer.scheduledTimer(timeInterval: autoScrollDelay, target: self, selector: #selector(CBSliderCollectionViewLayout.animateScroll), userInfo: nil, repeats: true)
}
}
/**
Cancel the autoscroll animations if they were previously started
*/
public func cancelAutoScroll() {
autoScrollTimer?.invalidate()
autoScrollTimer = nil
}
@objc internal func animateScroll() {
guard let cv = self.collectionView,
cv.numberOfSections > 0,
cv.numberOfItems(inSection: 0) > 0
else { return }
currentIndex += 1
if currentIndex >= cv.numberOfItems(inSection: 0) {
currentIndex = 0
}
self.collectionView?.scrollToItem(at: IndexPath(item: currentIndex, section: 0), at: UICollectionViewScrollPosition.left, animated: true)
}
override public var collectionViewContentSize : CGSize {
if collectionView?.numberOfSections == 0 {
return CGSize.zero
}
var contentWidth: CGFloat = 0
for section in 0...collectionView!.numberOfSections-1 {
let numItems = collectionView!.numberOfItems(inSection: section)
contentWidth = contentWidth + (CGFloat(numItems) * minimumLineSpacing) + (CGFloat(numItems) * collectionView!.frame.size.width)
}
return CGSize(width: CGFloat(contentWidth), height: collectionView!.bounds.size.height)
}
override public func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
if !collectionView!.bounds.size.equalTo(newBounds.size) {
return true;
}
return false;
}
var attributes : [UICollectionViewLayoutAttributes] = []
var contentSize : CGSize = CGSize.zero
override public func prepare() {
super.prepare()
let slideCount = self.collectionView?.dataSource?.collectionView(self.collectionView!, numberOfItemsInSection: 0) ?? 0
attributes.removeAll(keepingCapacity: false)
var x: CGFloat = 0
for idx in 0..<slideCount {
let height: CGFloat = collectionView!.frame.size.height
let width: CGFloat = collectionView!.frame.size.width
let y: CGFloat = 0
let attrs = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: idx, section: 0))
attrs.frame = CGRect(x: x, y: y, width: width, height: height)
x += width
attributes.append(attrs)
}
self.contentSize = CGSize(width: x, height: self.collectionView!.bounds.height)
}
override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributes : [UICollectionViewLayoutAttributes] = []
if let numSections = collectionView?.numberOfSections {
if numSections > 0 {
for section in 0...numSections-1 {
let numItems = collectionView!.numberOfItems(inSection: section)
if numItems > 0 {
for row in 0...numItems-1 {
let indexPath = IndexPath(item: row, section: section)
attributes.append(layoutAttributesForItem(at: indexPath)!)
}
}
}
}
}
return attributes
}
public override func prepare(forAnimatedBoundsChange oldBounds: CGRect) {
super.prepare(forAnimatedBoundsChange: oldBounds)
collectionView!.contentOffset = CGPoint(x: CGFloat(currentIndex) * collectionView!.frame.size.width, y: 0)
}
override public func finalizeAnimatedBoundsChange() {
super.finalizeAnimatedBoundsChange()
collectionView!.contentOffset = CGPoint(x: CGFloat(currentIndex) * collectionView!.frame.size.width, y: 0)
}
override public func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return attributes[indexPath.item]
}
}
| mit | f661d2453b6b536a6c331b2561847e81 | 34.714286 | 190 | 0.623333 | 5.479452 | false | false | false | false |
richeterre/jumu-nordost-ios | JumuNordost/Application/PerformanceFilterView.swift | 1 | 2307 | //
// PerformanceFilterView.swift
// JumuNordost
//
// Created by Martin Richter on 20/02/16.
// Copyright © 2016 Martin Richter. All rights reserved.
//
import Cartography
import ReactiveCocoa
class PerformanceFilterView: UIView {
let selectedDateIndex = MutableProperty<Int?>(nil)
let selectedVenueIndex = MutableProperty<Int?>(nil)
private let dateSwitcher: UISegmentedControl
private let venueSwitcher: UISegmentedControl
// MARK: - Lifecycle
init(dateStrings: [String], venueNames: [String]) {
dateSwitcher = UISegmentedControl(items: dateStrings)
venueSwitcher = UISegmentedControl(items: venueNames)
super.init(frame: CGRectZero)
selectedDateIndex.producer.startWithNext { [weak self] index in
self?.dateSwitcher.selectedSegmentIndex = index ?? -1
}
selectedVenueIndex.producer.startWithNext { [weak self] index in
self?.venueSwitcher.selectedSegmentIndex = index ?? -1
}
dateSwitcher.addTarget(self, action: #selector(dateSwitcherChanged(_:)), forControlEvents: .ValueChanged)
venueSwitcher.addTarget(self, action: #selector(venueSwitcherChanged(_:)), forControlEvents: .ValueChanged)
addSubview(dateSwitcher)
addSubview(venueSwitcher)
makeConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Layout
private func makeConstraints() {
constrain(self, dateSwitcher, venueSwitcher) { superview, dateSwitcher, venueSwitcher in
dateSwitcher.top == superview.topMargin
dateSwitcher.left == superview.leftMargin
dateSwitcher.right == superview.rightMargin
venueSwitcher.top == dateSwitcher.bottom + 8
venueSwitcher.left == superview.leftMargin
venueSwitcher.right == superview.rightMargin
venueSwitcher.bottom == superview.bottomMargin
}
}
// MARK: - User Interaction
func dateSwitcherChanged(switcher: UISegmentedControl) {
selectedDateIndex.value = switcher.selectedSegmentIndex
}
func venueSwitcherChanged(switcher: UISegmentedControl) {
selectedVenueIndex.value = switcher.selectedSegmentIndex
}
}
| mit | aa5e6d65383a838887318436439c15f7 | 31.027778 | 115 | 0.689072 | 5.350348 | false | false | false | false |
AlbanPerli/HandWriting-Recognition-iOS | HandWriting-Learner/UIImage+Processing.swift | 1 | 2290 | import UIKit
extension UIImage {
// Retreive intensity (alpha) of each pixel from this image
func pixelsArray()->(pixelValues: [Float], width: Int, height: Int){
let width = Int(self.size.width)
let height = Int(self.size.height)
var pixelsArray = [Float]()
let pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage))
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let bytesPerRow = CGImageGetBytesPerRow(self.CGImage)
let bytesPerPixel = (CGImageGetBitsPerPixel(self.CGImage) / 8)
var position = 0
for _ in 0..<height {
for _ in 0..<width {
let alpha = Float(data[position + 3])
pixelsArray.append(alpha / 255)
position += bytesPerPixel
}
if position % bytesPerRow != 0 {
position += (bytesPerRow - (position % bytesPerRow))
}
}
return (pixelsArray,width,height)
}
// Resize UIImage to the given size
// No ratio check - no scale check
func toSize(newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContext(newSize)
self.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
// Extract sub image based on the given frame
// x,y top left | x,y bottom right | pixels margin above this frame
func extractFrame(var topLeft: CGPoint, var bottomRight: CGPoint, pixelMargin: CGFloat) ->UIImage {
topLeft.x = topLeft.x - pixelMargin
topLeft.y = topLeft.y - pixelMargin
bottomRight.x = bottomRight.x + pixelMargin
bottomRight.y = bottomRight.y + pixelMargin
let size:CGSize = CGSizeMake(bottomRight.x-topLeft.x, bottomRight.y-topLeft.y)
let rect = CGRectMake(-topLeft.x, -topLeft.y, self.size.width, self.size.height)
UIGraphicsBeginImageContext(size)
self.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
} | mit | fe2930cda01578627957775a3874cc74 | 33.712121 | 103 | 0.6131 | 5.077605 | false | false | false | false |
RamonGilabert/Prodam | Prodam/Prodam/LaunchStarter.swift | 1 | 2236 | import Cocoa
class LaunchStarter: NSObject {
class func toggleLaunchAtStartup() {
let itemReferences = itemReferencesInLoginItems()
let shouldBeToggled = (itemReferences.existingReference == nil)
if let loginItemsRef = LSSharedFileListCreate( nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue() as LSSharedFileListRef? {
if shouldBeToggled {
if let appUrl : CFURLRef = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath) {
LSSharedFileListInsertItemURL(loginItemsRef, itemReferences.lastReference, nil, nil, appUrl, nil, nil)
}
} else {
if let itemRef = itemReferences.existingReference {
LSSharedFileListItemRemove(loginItemsRef,itemRef);
}
}
}
}
class func applicationIsInStartUpItems() -> Bool {
return (itemReferencesInLoginItems().existingReference != nil)
}
class func itemReferencesInLoginItems() -> (existingReference: LSSharedFileListItemRef?, lastReference: LSSharedFileListItemRef?) {
if let appURL : NSURL = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath) {
if let loginItemsRef = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue() as LSSharedFileListRef? {
let loginItems: NSArray = LSSharedFileListCopySnapshot(loginItemsRef, nil).takeRetainedValue() as NSArray
let lastItemRef: LSSharedFileListItemRef = loginItems.lastObject as! LSSharedFileListItemRef
for var i = 0; i < loginItems.count; ++i {
let currentItemRef: LSSharedFileListItemRef = loginItems.objectAtIndex(i) as! LSSharedFileListItemRef
if let itemURL = LSSharedFileListItemCopyResolvedURL(currentItemRef, 0, nil) {
if (itemURL.takeRetainedValue() as NSURL).isEqual(appURL) {
return (currentItemRef, lastItemRef)
}
}
}
return (nil, lastItemRef)
}
}
return (nil, nil)
}
}
| mit | 319c4ce6e2433b00eea1912240ca226d | 46.574468 | 169 | 0.636404 | 5.733333 | false | false | false | false |
John-Connolly/SwiftQ | Sources/SwiftQ/Worker/Worker.swift | 1 | 3773 | //
// Worker.swift
// SwiftQ
//
// Created by John Connolly on 2017-05-07.
// Copyright © 2017 John Connolly. All rights reserved.
//
import Foundation
import Dispatch
final class Worker {
private let concurrentQueue = DispatchQueue(label: "com.swiftq.concurrent", attributes: .concurrent)
private let queue: ReliableQueue
private let decoder: Decoder
private let semaphore: DispatchSemaphore
private let middlewares: MiddlewareCollection
init(decoder: Decoder,
config: RedisConfig,
concurrency: Int,
queue: String,
consumerName: String?,
middleware: [Middleware]) throws {
self.semaphore = DispatchSemaphore(value: concurrency)
self.decoder = decoder
self.middlewares = MiddlewareCollection(middleware)
self.queue = try ReliableQueue(queue: queue,
config: config,
consumer: consumerName,
concurrency: concurrency)
try self.queue.prepare()
}
/// Atomically transfers a task from the work queue into the
/// processing queue then enqueues it to the worker.
func run() {
repeat {
semaphore.wait()
AsyncWorker(queue: concurrentQueue) {
defer {
self.semaphore.signal()
}
do {
let task = try self.queue.bdequeue { data in
return try self.decoder.decode(data: data)
}
task.map(self.execute)
} catch {
Logger.log(error)
}
}.run()
} while true
}
private func execute(_ task: Task) {
do {
middlewares.before(task: task)
try task.execute()
middlewares.after(task: task)
complete(task: task)
} catch {
middlewares.after(task: task, with: error)
failure(task, error: error)
}
}
/// Called when a task is successfully completed. If the task is
/// periodic it is re-queued into the zset.
private func complete(task: Task) {
do {
if let task = task as? PeriodicTask {
let box = try PeriodicBox(task)
try queue.requeue(item: box, success: true)
} else {
try queue.complete(item: try EnqueueingBox(task), success: true)
}
} catch {
Logger.log(error)
}
}
/// Called when the tasks fails. Note: If the tasks recovery
/// stategy is none it will never be ran again.
private func failure(_ task: Task, error: Error) {
do {
switch task.recoveryStrategy {
case .none:
try queue.complete(item: EnqueueingBox(task), success: false)
case .retry(let retries):
if task.shouldRetry(retries) {
task.retry()
try queue.requeue(item: EnqueueingBox(task), success: false)
} else {
try queue.complete(item: EnqueueingBox(task), success: false)
}
case .log:
try queue.log(task: task, error: error)
}
} catch {
Logger.log(error)
}
}
}
enum Result<T> {
case success(T)
case failure(Error)
}
| mit | 070c8070fa77bf6e1b6dafd32d721c78 | 27.575758 | 104 | 0.486214 | 5.246175 | false | false | false | false |
castial/Quick-Start-iOS | Quick-Start-iOS/Vendors/HYKeychainHelper/HYKeychainHelper.swift | 1 | 2655 | //
// HYKeychainHelper.swift
// Quick-Start-iOS
//
// Created by hyyy on 2017/1/18.
// Copyright © 2017年 hyyy. All rights reserved.
//
import Foundation
struct HYKeychainHelper {
static func password(service: String, account: String, accessGroup: String? = nil) -> String? {
var item = HYKeychainItem (service: service, account: account)
item.accessGroup = accessGroup
do {
try item.queryPassword()
}catch {
fatalError("Error fetching password item - \(error)")
}
return item.password
}
static func passwordData(service: String, account: String, accessGroup: String? = nil) -> Data? {
var item = HYKeychainItem (service: service, account: account)
item.accessGroup = accessGroup
do {
try item.queryPassword()
}catch {
fatalError("Error fetching passwordData item - \(error)")
}
return item.passwordData
}
static func deletePassword(service: String, account: String, accessGroup: String? = nil) {
var item = HYKeychainItem (service: service, account: account)
item.accessGroup = accessGroup
do {
try item.delete()
} catch {
fatalError("Error deleting password item - \(error)")
}
}
static func set(password: String, service: String, account: String, accessGroup: String? = nil) {
var item = HYKeychainItem (service: service, account: account)
item.accessGroup = accessGroup
item.password = password
do {
try item.save()
} catch {
fatalError("Error setting password item - \(error)")
}
}
static func set(passwordData: Data, service: String, account: String, accessGroup: String? = nil) {
var item = HYKeychainItem (service: service, account: account)
item.accessGroup = accessGroup
item.passwordData = passwordData
do {
try item.save()
}catch {
fatalError("Error setting password item - \(error)")
}
}
static func allAccount() -> Array<[String : AnyObject]> {
return allAccounts(forService: nil)
}
static func allAccounts(forService service: String?) -> Array<[String : AnyObject]> {
var item = HYKeychainItem ()
item.service = service
var allAccountsArr: Array<[String : AnyObject]>
do {
try allAccountsArr = item.queryAll()
} catch {
fatalError("Error setting password item - \(error)")
}
return allAccountsArr
}
}
| mit | d188ee469191c60623bc2692f8dc8e1f | 31.341463 | 103 | 0.591629 | 4.830601 | false | false | false | false |
an23lm/Player | Player/PauseView.swift | 1 | 1095 | //
// PauseView.swift
// Player
//
// Created by Ansèlm Joseph on 11/07/2017.
// Copyright © 2017 Ansèlm Joseph. All rights reserved.
//
import Cocoa
@IBDesignable
class PauseView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
let width = self.frame.width
let height = self.frame.height
let center = CGPoint(x: width/2, y: height/2)
let lineWidth = width / 4
let lineHeight = height - 4
let rect1 = NSRect(x: center.x - lineWidth - lineWidth/3, y: center.y - lineHeight/2, width: lineWidth, height: lineHeight)
let path1 = NSBezierPath(roundedRect: rect1, xRadius: 2, yRadius: 2)
NSColor.black.setFill()
let rect2 = NSRect(x: center.x + lineWidth/3, y: center.y - lineHeight/2, width: lineWidth, height: lineHeight)
let path2 = NSBezierPath(roundedRect: rect2, xRadius: 2, yRadius: 2)
NSColor.black.setFill()
path1.fill()
path2.fill()
}
}
| apache-2.0 | 4882916f4d9de23375f2864a467aa76f | 26.3 | 131 | 0.591575 | 3.913978 | false | false | false | false |
Rochester-Ting/DouyuTVDemo | RRDouyuTV/RRDouyuTV/Classes/Home(首页)/ViewController/FunnyVC.swift | 1 | 2895 | //
// FunnyVC.swift
// RRDouyuTV
//
// Created by 丁瑞瑞 on 18/10/16.
// Copyright © 2016年 Rochester. All rights reserved.
//
import UIKit
fileprivate let kItemMargin : CGFloat = 10
fileprivate let kItemWidth : CGFloat = (kScreenW - 3 * kItemMargin) / 2
fileprivate let kItemHeight : CGFloat = kItemWidth * 3 / 4
fileprivate let kNormalCellId = "kNormalCellId"
class FunnyVC: BaseViewController {
let funnyVM : FunnyViewModel = FunnyViewModel()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemWidth, height: kItemHeight)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.scrollDirection = .vertical
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.register(UINib(nibName: "RecommandNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellId)
collectionView.contentInset = UIEdgeInsets(top: kItemMargin, left: 0, bottom: kStatusBarH + kNavigationH + kTabBarH + kTitleViewH, right: 0)
collectionView.delegate = self
collectionView.dataSource = self
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = UIColor.white
setUpUI()
}
}
extension FunnyVC{
override func setUpUI() {
// super.setUpUI()
view.addSubview(collectionView)
contentView = collectionView
super.setUpUI()
funnyVM.requestFunnyData {
self.collectionView.reloadData()
self.stopAnimation()
}
}
}
extension FunnyVC : UICollectionViewDelegate{
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let isVertical = funnyVM.funnyModels[indexPath.item].isVertical
isVertical == 0 ? pushVC() : presentVC()
}
func pushVC() {
navigationController?.pushViewController(RoomNormalVC(), animated: true)
}
func presentVC(){
present(RoomBeatifulVC(), animated: true, completion: nil)
}
}
extension FunnyVC : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return funnyVM.funnyModels.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellId, for: indexPath) as! RecommandNormalCell
cell.achor = funnyVM.funnyModels[indexPath.row]
return cell
}
}
| mit | 3bde51e011043e65b83920e5f1226ceb | 32.172414 | 148 | 0.697852 | 5.247273 | false | false | false | false |
rajeejones/SavingPennies | Pods/IBAnimatable/IBAnimatable/ActivityIndicatorAnimationBallGridBeat.swift | 5 | 2015 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallGridBeat: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSpacing: CGFloat = 2
let circleSize = (size.width - circleSpacing * 2) / 3
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let durations = [0.96, 0.93, 1.19, 1.13, 1.34, 0.94, 1.2, 0.82, 1.19]
let beginTime = CACurrentMediaTime()
let beginTimes = [0.36, 0.4, 0.68, 0.41, 0.71, -0.15, -0.12, 0.01, 0.32]
let animation = self.animation
// Draw circles
for i in 0 ..< 3 {
for j in 0 ..< 3 {
let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: x + circleSize * CGFloat(j) + circleSpacing * CGFloat(j),
y: y + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
width: circleSize,
height: circleSize)
animation.duration = durations[3 * i + j]
animation.beginTime = beginTime + beginTimes[3 * i + j]
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallGridBeat {
var animation: CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: "opacity")
animation.keyTimes = [0, 0.5, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.7, 1]
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
}
| gpl-3.0 | 7998343183f12a381bdc2970b50efe31 | 33.152542 | 127 | 0.649628 | 4.112245 | false | false | false | false |
iOS-Swift-Developers/Swift | 基础语法/Switch/main.swift | 1 | 3527 | //
// main.swift
// Switch
//
// Created by 韩俊强 on 2017/6/8.
// Copyright © 2017年 HaRi. All rights reserved.
//
import Foundation
/*
Swith
格式: switch(需要匹配的值) case 匹配的值: 需要执行的语句 break;
OC:
char rank = 'A';
switch (rank) {
case 'A':
NSLog(@"优");
break;
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
default:
NSLog(@"没有评级");
break;
}
可以穿透
char rank = 'A';
switch (rank) {
case 'A':
NSLog(@"优");
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
default:
NSLog(@"没有评级");
break;
}
可以不写default
char rank = 'A';
switch (rank) {
case 'A':
NSLog(@"优");
break;
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
}
default位置可以随便放
char rank = 'E';
switch (rank) {
default:
NSLog(@"没有评级");
break;
case 'A':
{
int score = 100;
NSLog(@"优");
break;
}
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
}
在case中定义变量需要加大括号, 否则作用域混乱
char rank = 'A';
switch (rank) {
case 'A':
{
int score = 100;
NSLog(@"优");
break;
}
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
}
不能判断对象类型
NSNumber *num = @100;
switch (num) {
case @100:
NSLog(@"优");
break;
default:
NSLog(@"没有评级");
break;
}
*/
/** Swift:可以判断对象类型, OC必须是整数 **/
//不可以穿透
//可以不写break
var rank = "A"
switch rank{
case "A": // 相当于if
print("A")
case "B": // 相当于 else if
print("B")
case "C": // 相当于 else if
print("C")
default: // 相当于 else
print("其他")
}
/*
因为不能穿透所以不能这么写
var rank1 = "A"
switch rank1{
case "A":
case "B":
print("B")
case "C":
print("C")
default:
print("其他")
}
*/
//只能这么写
var rank1 = "A"
switch rank1{
case "A", "B": // 注意OC不能这样写
print("A&&B")
case "C":
print("C")
default:
print("其他")
}
/*
//不能不写default
var rank2 = "A"
switch rank2{
case "A":
print("A")
case "B":
print("B")
case "C":
print("C")
}
*/
/*
//default位置只能在最后
var rank3 = "A"
switch rank3{
default:
print("其他")
case "A":
print("A")
case "B":
print("B")
case "C":
print("C")
}
*/
//在case中定义变量不用加大括号
var rank4 = "A"
switch rank4{
case "A":
var num = 10
print("A")
case "B":
print("B")
case "C":
print("C")
default:
print("其他")
}
/*
区间和元组匹配
var num = 10
switch num{
case 1...9:
print("个位数")
case 10...99:
print("十位数")
default:
print("其他数")
}
var point = (10, 15)
switch point{
case (0, 0):
print("坐标原点")
case (1...10, 10...20):
print("坐标的X和Y在1~10之间") // 可以在元组中再加上区间
default:
print("Other")
}
*/
/*
//值绑定
var point = (1, 10)
switch point{
case (var x, 10): // 会将point中的x赋值给
print("x = \(x)")
case (var x, var y): // 会将point中xy的值赋值给xy
print("x = \(x) y = \(y)")
case var(x,y):
print("x = \(x) y =\(y)")
default:
print("Other")
}
//根据条件绑定
var point = (101, 100)
switch point{
// 只有where后面的条件表达式为真才赋值并执行case后的语句
case var(x, y) where x > y:
print("x = \(x) y = \(y)")
default:
print("Other")
}
*/
| mit | 78c80c72299926140c8d7d1cdac31f0d | 11.365145 | 48 | 0.526846 | 2.514768 | false | false | false | false |
HabitRPG/habitrpg-ios | Habitica Database/Habitica Database/Models/Content/RealmSpecialItem.swift | 1 | 643 | //
// RealmSpecialItem.swift
// Habitica Database
//
// Created by Phillip Thelen on 08.06.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import RealmSwift
class RealmSpecialItem: RealmItem, SpecialItemProtocol {
var target: String?
var immediateUse: Bool = false
var silent: Bool = false
convenience init(_ specialItem: SpecialItemProtocol) {
self.init(item: specialItem)
target = specialItem.target
immediateUse = specialItem.immediateUse
silent = specialItem.silent
itemType = ItemType.special.rawValue
}
}
| gpl-3.0 | 1117b67927fc27c193f1147ae9fcb3c4 | 23.692308 | 58 | 0.694704 | 4.458333 | false | false | false | false |
andrea-prearo/SwiftExamples | ParallaxAndScale/ParallaxAndScale/MainViewController.swift | 1 | 5334 | //
// MainViewController.swift
// ParallaxAndScale
//
// Created by Andrea Prearo on 8/31/18.
// Copyright © 2018 Andrea Prearo. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
// MARK: - Constants
struct Constants {
static fileprivate let headerHeight: CGFloat = 210
}
// MARK: - Properties
private var scrollView: UIScrollView!
private var label: UILabel!
private var headerContainerView: UIView!
private var headerImageView: UIImageView!
private var headerTopConstraint: NSLayoutConstraint!
private var headerHeightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
scrollView = createScrollView()
headerContainerView = createHeaderContainerView()
headerImageView = createHeaderImageView()
label = createLabel()
headerContainerView.addSubview(headerImageView)
scrollView.addSubview(headerContainerView)
scrollView.addSubview(label)
view.addSubview(scrollView)
arrangeConstraints()
}
}
private extension MainViewController {
func createScrollView() -> UIScrollView {
let scrollView = UIScrollView()
scrollView.delegate = self
scrollView.alwaysBounceVertical = true
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}
func createHeaderContainerView() -> UIView {
let view = UIView()
view.clipsToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}
func createHeaderImageView() -> UIImageView {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
if let image = UIImage(named: "Coffee") {
imageView.image = image
}
imageView.clipsToBounds = true
return imageView
}
func createLabel() -> UILabel {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = .white
let titleFont = UIFont.preferredFont(forTextStyle: .title1)
if let boldDescriptor = titleFont.fontDescriptor.withSymbolicTraits(.traitBold) {
label.font = UIFont(descriptor: boldDescriptor, size: 0)
} else {
label.font = titleFont
}
label.textAlignment = .center
label.adjustsFontForContentSizeCategory = true
label.text = "Your content here"
return label
}
func arrangeConstraints() {
let scrollViewConstraints: [NSLayoutConstraint] = [
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
]
NSLayoutConstraint.activate(scrollViewConstraints)
headerTopConstraint = headerContainerView.topAnchor.constraint(equalTo: view.topAnchor)
headerHeightConstraint = headerContainerView.heightAnchor.constraint(equalToConstant: 210)
let headerContainerViewConstraints: [NSLayoutConstraint] = [
headerTopConstraint,
headerContainerView.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 1.0),
headerHeightConstraint
]
NSLayoutConstraint.activate(headerContainerViewConstraints)
let headerImageViewConstraints: [NSLayoutConstraint] = [
headerImageView.topAnchor.constraint(equalTo: headerContainerView.topAnchor),
headerImageView.leadingAnchor.constraint(equalTo: headerContainerView.leadingAnchor),
headerImageView.trailingAnchor.constraint(equalTo: headerContainerView.trailingAnchor),
headerImageView.bottomAnchor.constraint(equalTo: headerContainerView.bottomAnchor)
]
NSLayoutConstraint.activate(headerImageViewConstraints)
let labelConstraints: [NSLayoutConstraint] = [
label.topAnchor.constraint(equalTo: headerContainerView.bottomAnchor),
label.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 1.0),
label.heightAnchor.constraint(equalToConstant: 800)
]
NSLayoutConstraint.activate(labelConstraints)
}
}
extension MainViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y < 0.0 {
headerHeightConstraint?.constant = Constants.headerHeight - scrollView.contentOffset.y
} else {
let parallaxFactor: CGFloat = 0.25
let offsetY = scrollView.contentOffset.y * parallaxFactor
let minOffsetY: CGFloat = 8.0
let availableOffset = min(offsetY, minOffsetY)
let contentRectOffsetY = availableOffset / Constants.headerHeight
headerTopConstraint?.constant = view.frame.origin.y
headerHeightConstraint?.constant = Constants.headerHeight - scrollView.contentOffset.y
headerImageView.layer.contentsRect = CGRect(x: 0, y: -contentRectOffsetY, width: 1, height: 1)
}
}
}
| mit | d35b423a0812f6de055fab65847728a6 | 38.503704 | 106 | 0.695293 | 5.998875 | false | false | false | false |
OHeroJ/twicebook | Sources/App/Controllers/UserController.swift | 1 | 7737 | //
// UserController.swift
// seesometop
//
// Created by laijihua on 29/08/2017.
//
//
import Foundation
import Vapor
final class UserController: ControllerRoutable {
init(builder: RouteBuilder) {
/// 用户修改 /user/update
builder.put("update",Int.parameter, handler: update)
/// 绑定微信信息
builder.post("bindwx", handler: bindWx)
/// 用户登出
builder.get("logout", Int.parameter, handler: logout)
/// 获取用户信息
builder.get("/", Int.parameter, handler: show)
/// 获取用户列表
builder.get("list", handler: getNewerUserList)
/// 朋友关系
builder.post("friend", handler: friendAdd)
builder.delete("friend", handler: friendRemove)
builder.get("friend", Int.parameter, handler:haveFriend)
builder.get("friends", handler: userFriends)
/// 举报
builder.post("report", handler: report)
}
// 绑定微信
func bindWx(req: Request) throws -> ResponseRepresentable {
guard let sign = req.data[User.Key.wxSign]?.string,
let number = req.data[User.Key.wxNumber]?.string,
let userId = req.data[User.Key.id] else {
return try ApiRes.error(code: 1, msg: "参数错误")
}
guard let user = try User.find(userId) else {
return try ApiRes.error(code: 2, msg: "未找到该用户")
}
if user.wxSign.count > 0 && user.wxSign != sign {
return try ApiRes.error(code: 3, msg: "该账号已绑定")
}
user.wxSign = sign
user.wxNumber = number
try user.save()
return try ApiRes.success(data:["user": user])
}
/// 获取最新的用户信息
func getNewerUserList(req: Request) throws -> ResponseRepresentable {
let isNewer = req.data["isNew"]?.int ?? 0 // 0 not | 1 newer
var query = try User.makeQuery()
if isNewer == 1 {
query = try query.sort(User.Key.createTime, .descending)
}
var friendIds = [Identifier]()
if let userId = req.data["userId"]?.int {
friendIds = try Friend.makeQuery()
.filter(Friend.Key.masterId, userId)
.all()
.map({ $0.friendId })
}
return try User.page(request: req, query: query, resultJSONHook: { (user) -> User in
if let thisId = user.id {
if friendIds.contains(thisId) {
user.isFriend = true
}
}
return user
})
}
func report(request: Request) throws -> ResponseRepresentable {
guard let userId = request.data["userId"]?.int else {
return try ApiRes.error(code: 1, msg: "MISS USERID")
}
guard let reportId = request.data["reportId"]?.int else {
return try ApiRes.error(code: 2, msg: "miss report ID")
}
if userId == reportId {return try ApiRes.error(code: 3, msg: "miss UserId")}
guard let reportUser = try User.find(reportId) else {
return try ApiRes.error(code: 3, msg: "miss user")
}
reportUser.reportCount += 1
try reportUser.save()
return try ApiRes.success(data:["success": true])
}
func userFriends(request: Request) throws -> ResponseRepresentable {
guard let masterId = request.data[Friend.Key.masterId]?.int else {
return try ApiRes.error(code: 1, msg: "miss masterId")
}
let friends = try Friend.makeQuery().filter(Friend.Key.masterId, masterId).all()
var users = [User]()
for friend in friends {
if let user = try User.find(friend.friendId) {
users.append(user)
}
}
return try ApiRes.success(data:["friends": users])
}
func haveFriend(request: Request) throws -> ResponseRepresentable {
let friendId = try request.parameters.next(Int.self)
guard let userId = request.data[Friend.Key.masterId]?.int else {
return try ApiRes.error(code: 1, msg: "misss master_id")
}
let friends = try Friend.makeQuery().and { (andGroup) in
try andGroup.filter(Friend.Key.masterId, userId)
try andGroup.filter(Friend.Key.friendId, friendId)
}
if let _ = try friends.first(){
return try ApiRes.success(data:["isFriend": true])
} else {
return try ApiRes.success(data:["isFriend": false])
}
}
func friendRemove(request: Request) throws -> ResponseRepresentable {
guard let userId = request.data[Friend.Key.masterId]?.int else {
return try ApiRes.error(code: 1, msg: "misss master_id")
}
guard let friendId = request.data[Friend.Key.friendId]?.int else {
return try ApiRes.error(code: 2, msg: "miss friend_id")
}
let friends = try Friend.makeQuery().and { (andGroup) in
try andGroup.filter(Friend.Key.masterId, userId)
try andGroup.filter(Friend.Key.friendId, friendId)
}
guard let friend = try friends.first() else {
return try ApiRes.error(code: 3, msg: "not found friend ship")
}
try friend.delete()
return try ApiRes.success(data:["ret": true])
}
func friendAdd(request: Request) throws -> ResponseRepresentable {
guard let userId = request.data[Friend.Key.masterId]?.int else {
return try ApiRes.error(code: 1, msg: "misss master_id")
}
guard let friendId = request.data[Friend.Key.friendId]?.int else {
return try ApiRes.error(code: 2, msg: "miss friend_id")
}
let friends = try Friend.makeQuery().and { (andGroup) in
try andGroup.filter(Friend.Key.masterId, userId)
try andGroup.filter(Friend.Key.friendId, friendId)
}
if let _ = try friends.first() {
// 已收藏
} else {
let frindship = Friend(masterId: Identifier(userId), friendId: Identifier(friendId))
try frindship.save()
}
return try ApiRes.success(data:["ret": true])
}
func show(request: Request) throws -> ResponseRepresentable {
let userId = try request.parameters.next(Int.self)
guard let user = try User.find(userId) else {
return try ApiRes.error(code: 1, msg:"user not found")
}
return try ApiRes.success(data:["user": user])
}
func logout(request: Request) throws -> ResponseRepresentable {
let userId = try request.parameters.next(Int.self)
if let token = try UserToken.makeQuery().filter(UserToken.Key.userId, userId).first() {
try token.delete()
}
return try ApiRes.success(data:"success")
}
func update(request: Request) throws -> ResponseRepresentable {
let userId = try request.parameters.next(Int.self)
guard let user = try User.find(userId) else {
return try ApiRes.error(code: 1, msg: "user not found")
}
// 修改昵称
if let name = request.data[User.Key.name]?.string {
user.name = name
}
// 修改密码
if let pwd = request.data[User.Key.password]?.string {
user.password = pwd
}
// 修改昵称
if let avator = request.data[User.Key.avator]?.string {
user.avator = avator
}
// 修改用户简洁
if let info = request.data[User.Key.info]?.string {
user.info = info
}
try user.save()
return try ApiRes.success(data:["user": user])
}
}
| mit | c3e9e3db797c2b94295e725a630b5979 | 35.061905 | 96 | 0.575598 | 4.163277 | false | false | false | false |
kmalkic/LazyKit | LazyKit/Classes/Theming/Sets/Models/LazyParagraph.swift | 1 | 2007 | //
// LazyParagraph.swift
// LazyKit
//
// Created by Kevin Malkic on 28/04/2015.
// Copyright (c) 2015 Malkic Kevin. All rights reserved.
//
import UIKit
internal class LazyParagraph {
var lineSpacing: LazyMeasure?
var paragraphSpacing: LazyMeasure?
var headIndent: LazyMeasure?
var alignment: LazyTextAlignment?
var lineBreakMode: LazyLineBreakMode?
func convertWordWrap(_ wordWrap: String) -> NSLineBreakMode {
switch wordWrap {
case "word-wrapping":
return .byWordWrapping
case "char-wrapping":
return .byCharWrapping
case "clipping":
return .byClipping
case "truncating-head":
return .byTruncatingHead
case "truncating-tail":
return .byTruncatingTail
case "truncating-middle":
return .byTruncatingMiddle
default:
break
}
return .byTruncatingTail
}
func paragraphStyle() -> NSParagraphStyle! {
let paragraphStyle = NSMutableParagraphStyle()
if let value = lineSpacing?.value {
paragraphStyle.lineSpacing = value
}
if let value = paragraphSpacing?.value {
paragraphStyle.paragraphSpacing = value
}
if let value = headIndent?.value {
paragraphStyle.firstLineHeadIndent = value
}
if let value = alignment {
paragraphStyle.alignment = value.alignment!
} else {
paragraphStyle.alignment = .left
}
if let value = lineBreakMode {
paragraphStyle.lineBreakMode = value
} else {
paragraphStyle.lineBreakMode = .byTruncatingTail
}
return paragraphStyle
}
}
| mit | 9546100d276ebbd21fd1a816307c3a2d | 21.054945 | 65 | 0.529646 | 6.33123 | false | false | false | false |
actframework/FrameworkBenchmarks | frameworks/Swift/swift-nio/Sources/swift-nio-tfb-default/main.swift | 2 | 4681 |
import Foundation
import NIO
import NIOHTTP1
struct JSONTestResponse: Encodable {
let message = "Hello, World!"
}
enum Constants {
static let httpVersion = HTTPVersion(major: 1, minor: 1)
static let serverName = "SwiftNIO"
static let plainTextResponse: StaticString = "Hello, World!"
static let plainTextResponseLength = plainTextResponse.count
static let plainTextResponseLengthString = String(plainTextResponseLength)
static let jsonResponseLength = try! JSONEncoder().encode(JSONTestResponse()).count
static let jsonResponseLengthString = String(jsonResponseLength)
}
private final class HTTPHandler: ChannelInboundHandler {
public typealias InboundIn = HTTPServerRequestPart
public typealias OutboundOut = HTTPServerResponsePart
let dateFormatter = RFC1123DateFormatter()
let jsonEncoder = JSONEncoder()
var plaintextBuffer: ByteBuffer!
var jsonBuffer: ByteBuffer!
init() {
let allocator = ByteBufferAllocator()
plaintextBuffer = allocator.buffer(capacity: Constants.plainTextResponseLength)
plaintextBuffer.write(staticString: Constants.plainTextResponse)
jsonBuffer = allocator.buffer(capacity: Constants.jsonResponseLength)
}
func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
let reqPart = self.unwrapInboundIn(data)
switch reqPart {
case .head(let request):
switch request.uri {
case "/plaintext":
processPlaintext(ctx: ctx)
case "/json":
processJSON(ctx: ctx)
default:
_ = ctx.close()
}
case .body:
break
case .end:
_ = ctx.write(self.wrapOutboundOut(.end(nil)))
}
}
func channelReadComplete(ctx: ChannelHandlerContext) {
ctx.flush()
ctx.fireChannelReadComplete()
}
private func processPlaintext(ctx: ChannelHandlerContext) {
let responseHead = plainTextResponseHead(contentLength: Constants.plainTextResponseLengthString)
ctx.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
ctx.write(self.wrapOutboundOut(.body(.byteBuffer(plaintextBuffer))), promise: nil)
}
private func processJSON(ctx: ChannelHandlerContext) {
let responseHead = jsonResponseHead(contentLength: Constants.jsonResponseLengthString)
ctx.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
let responseData = try! jsonEncoder.encode(JSONTestResponse())
jsonBuffer.clear()
jsonBuffer.write(bytes: responseData)
ctx.write(self.wrapOutboundOut(.body(.byteBuffer(jsonBuffer))), promise: nil)
}
private func jsonResponseHead(contentLength: String) -> HTTPResponseHead {
return responseHead(contentType: "application/json", contentLength: contentLength)
}
private func plainTextResponseHead(contentLength: String) -> HTTPResponseHead {
return responseHead(contentType: "text/plain", contentLength: contentLength)
}
private func responseHead(contentType: String, contentLength: String) -> HTTPResponseHead {
var headers = HTTPHeaders()
headers.replaceOrAdd(name: "content-type", value: contentType)
headers.replaceOrAdd(name: "content-length", value: contentLength)
headers.replaceOrAdd(name: "server", value: Constants.serverName)
headers.replaceOrAdd(name: "date", value: dateFormatter.getDate())
return HTTPResponseHead(version: Constants.httpVersion,
status: .ok,
headers: headers)
}
}
let group = MultiThreadedEventLoopGroup(numThreads: System.coreCount)
let bootstrap = ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.backlog, value: 8192)
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_TCP), TCP_NODELAY), value: 1)
.childChannelInitializer { channel in
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).then {
channel.pipeline.add(handler: HTTPHandler())
}
}
.childChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.childChannelOption(ChannelOptions.maxMessagesPerRead, value: 16)
.childChannelOption(ChannelOptions.recvAllocator, value: AdaptiveRecvByteBufferAllocator())
defer {
try! group.syncShutdownGracefully()
}
let channel = try! bootstrap.bind(host: "0.0.0.0", port: 8080).wait()
try! channel.closeFuture.wait()
| bsd-3-clause | c02810601f1607019607c4d8d1466524 | 36.150794 | 104 | 0.7022 | 5.155286 | false | false | false | false |
Legoless/iOS-Course | 2015-1/Lesson8/Gamebox/Gamebox/ViewController.swift | 2 | 2151 | //
// ViewController.swift
// Gamebox
//
// Created by Dal Rupnik on 21/10/15.
// Copyright © 2015 Unified Sense. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, ImageViewControllerDelegate {
let manager = GameManager.shared
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var priorityTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
resultLabel.text = "Click to add game!"
nameTextField.delegate = self
priorityTextField.delegate = self
if let gameName = NSUserDefaults.standardUserDefaults().objectForKey("GameName") as? String {
nameTextField.text = gameName
}
}
func textFieldDidEndEditing(textField: UITextField) {
print("ENDED EDITING")
if (textField == self.nameTextField)
{
print ("NAME ENDED")
}
}
@IBAction func addGameButtonTap(sender: UIButton) {
if let name = nameTextField.text, priority = UInt(priorityTextField.text!) where name.characters.count > 0 {
let game = Game(name: name, priority: priority)
manager.games.append(game)
resultLabel.text = "Added! There are \(manager.games.count) games in database!"
resultLabel.textColor = UIColor.blackColor()
GameManager.shared.save()
}
else {
resultLabel.text = "Verify your data!"
resultLabel.textColor = UIColor.redColor()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ImageSegue" {
let viewController = segue.destinationViewController as! ImageViewController
viewController.delegate = self
}
}
func imageViewControllerDidFinish(imageViewController: ImageViewController) {
imageViewController.dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | f6205ab32a51f4ba84fb476509377944 | 28.861111 | 116 | 0.625116 | 5.456853 | false | false | false | false |
mitchellporter/ios-animations | Animation/TabBar/TabBarExampleAnimatedTransitioning.swift | 2 | 2475 | import UIKit
/*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
This licensed material is licensed under the Apache 2.0 license. http://www.apache.org/licenses/LICENSE-2.0.
*/
class TabBarExampleAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
var isPresenting = false
let fromIndex: Int
let toIndex: Int
let animMultiplier: Double = 1.0
init(fromIndex: Int, toIndex: Int) {
self.fromIndex = fromIndex
self.toIndex = toIndex
super.init()
}
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return 0.4
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let to = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! as UIViewController
let from = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! as UIViewController
let container = transitionContext.containerView()
let duration = transitionDuration(transitionContext)
container.addSubview(to.view)
var direction = toIndex > fromIndex ? CGFloat(-1) : CGFloat(1)
if let toPeople = to as? TabBarPeopleViewController {
to.view.transform = CGAffineTransformMakeTranslation(0, to.view.bounds.height)
} else if let fromPeople = from as? TabBarPeopleViewController {
to.view.alpha = 1.0
container.addSubview(from.view)
} else {
from.view.alpha = 1.0
to.view.alpha = 0.0
}
UIView.animateWithDuration(animMultiplier * transitionDuration(transitionContext), delay: animMultiplier * 0.0, options: nil, animations: { () -> Void in
to.view.alpha = 1.0
to.view.transform = CGAffineTransformIdentity
if let fromPeople = from as? TabBarPeopleViewController {
fromPeople.view.transform = CGAffineTransformMakeTranslation(0, from.view.bounds.height)
}
}) { finished in
to.view.transform = CGAffineTransformIdentity
from.view.transform = CGAffineTransformIdentity
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
}
| apache-2.0 | bd75e20f8de3fe8c97fd08817fe6364d | 35.382353 | 161 | 0.657235 | 5.753488 | false | false | false | false |
zapdroid/RXWeather | Pods/Nimble/Sources/Nimble/Adapters/NMBObjCMatcher.swift | 1 | 3358 | import Foundation
#if _runtime(_ObjC)
public typealias MatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage) -> Bool
public typealias FullMatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage, _ shouldNotMatch: Bool) -> Bool
public class NMBObjCMatcher: NSObject, NMBMatcher {
let _match: MatcherBlock
let _doesNotMatch: MatcherBlock
let canMatchNil: Bool
public init(canMatchNil: Bool, matcher: @escaping MatcherBlock, notMatcher: @escaping MatcherBlock) {
self.canMatchNil = canMatchNil
self._match = matcher
self._doesNotMatch = notMatcher
}
public convenience init(matcher: @escaping MatcherBlock) {
self.init(canMatchNil: true, matcher: matcher)
}
public convenience init(canMatchNil: Bool, matcher: @escaping MatcherBlock) {
self.init(canMatchNil: canMatchNil, matcher: matcher, notMatcher: ({ actualExpression, failureMessage in
!matcher(actualExpression, failureMessage)
}))
}
public convenience init(matcher: @escaping FullMatcherBlock) {
self.init(canMatchNil: true, matcher: matcher)
}
public convenience init(canMatchNil: Bool, matcher: @escaping FullMatcherBlock) {
self.init(canMatchNil: canMatchNil, matcher: ({ actualExpression, failureMessage in
matcher(actualExpression, failureMessage, false)
}), notMatcher: ({ actualExpression, failureMessage in
matcher(actualExpression, failureMessage, true)
}))
}
private func canMatch(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
do {
if !canMatchNil {
if try actualExpression.evaluate() == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
return false
}
}
} catch let error {
failureMessage.actualValue = "an unexpected error thrown: \(error)"
return false
}
return true
}
public func matches(_ actualBlock: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let expr = Expression(expression: actualBlock, location: location)
let result = _match(
expr,
failureMessage)
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
return result
} else {
return false
}
}
public func doesNotMatch(_ actualBlock: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let expr = Expression(expression: actualBlock, location: location)
let result = _doesNotMatch(
expr,
failureMessage)
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
return result
} else {
return false
}
}
}
#endif
| mit | 0b0771ca30a1d101392627cee4981866 | 40.45679 | 148 | 0.598273 | 6.039568 | false | false | false | false |
practicalswift/swift | stdlib/public/core/StringUTF8View.swift | 1 | 16574 | //===--- StringUTF8.swift - A UTF8 view of String -------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to
// allow performance optimizations of linear traversals.
extension String {
/// A view of a string's contents as a collection of UTF-8 code units.
///
/// You can access a string's view of UTF-8 code units by using its `utf8`
/// property. A string's UTF-8 view encodes the string's Unicode scalar
/// values as 8-bit integers.
///
/// let flowers = "Flowers 💐"
/// for v in flowers.utf8 {
/// print(v)
/// }
/// // 70
/// // 108
/// // 111
/// // 119
/// // 101
/// // 114
/// // 115
/// // 32
/// // 240
/// // 159
/// // 146
/// // 144
///
/// A string's Unicode scalar values can be up to 21 bits in length. To
/// represent those scalar values using 8-bit integers, more than one UTF-8
/// code unit is often required.
///
/// let flowermoji = "💐"
/// for v in flowermoji.unicodeScalars {
/// print(v, v.value)
/// }
/// // 💐 128144
///
/// for v in flowermoji.utf8 {
/// print(v)
/// }
/// // 240
/// // 159
/// // 146
/// // 144
///
/// In the encoded representation of a Unicode scalar value, each UTF-8 code
/// unit after the first is called a *continuation byte*.
///
/// UTF8View Elements Match Encoded C Strings
/// =========================================
///
/// Swift streamlines interoperation with C string APIs by letting you pass a
/// `String` instance to a function as an `Int8` or `UInt8` pointer. When you
/// call a C function using a `String`, Swift automatically creates a buffer
/// of UTF-8 code units and passes a pointer to that buffer. The code units
/// of that buffer match the code units in the string's `utf8` view.
///
/// The following example uses the C `strncmp` function to compare the
/// beginning of two Swift strings. The `strncmp` function takes two
/// `const char*` pointers and an integer specifying the number of characters
/// to compare. Because the strings are identical up to the 14th character,
/// comparing only those characters results in a return value of `0`.
///
/// let s1 = "They call me 'Bell'"
/// let s2 = "They call me 'Stacey'"
///
/// print(strncmp(s1, s2, 14))
/// // Prints "0"
/// print(String(s1.utf8.prefix(14)))
/// // Prints "They call me '"
///
/// Extending the compared character count to 15 includes the differing
/// characters, so a nonzero result is returned.
///
/// print(strncmp(s1, s2, 15))
/// // Prints "-17"
/// print(String(s1.utf8.prefix(15)))
/// // Prints "They call me 'B"
@_fixed_layout
public struct UTF8View {
@usableFromInline
internal var _guts: _StringGuts
@inlinable @inline(__always)
internal init(_ guts: _StringGuts) {
self._guts = guts
_invariantCheck()
}
}
}
extension String.UTF8View {
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
// TODO: Ensure index alignment
}
#endif // INTERNAL_CHECKS_ENABLED
}
extension String.UTF8View: BidirectionalCollection {
public typealias Index = String.Index
public typealias Element = UTF8.CodeUnit
/// The position of the first code unit if the UTF-8 view is
/// nonempty.
///
/// If the UTF-8 view is empty, `startIndex` is equal to `endIndex`.
@inlinable
public var startIndex: Index {
@inline(__always) get { return _guts.startIndex }
}
/// The "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// In an empty UTF-8 view, `endIndex` is equal to `startIndex`.
@inlinable
public var endIndex: Index {
@inline(__always) get { return _guts.endIndex }
}
/// Returns the next consecutive position after `i`.
///
/// - Precondition: The next position is representable.
@inlinable @inline(__always)
public func index(after i: Index) -> Index {
if _fastPath(_guts.isFastUTF8) {
return i.nextEncoded
}
return _foreignIndex(after: i)
}
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
precondition(!i.isZeroPosition)
if _fastPath(_guts.isFastUTF8) {
return i.priorEncoded
}
return _foreignIndex(before: i)
}
@inlinable @inline(__always)
public func index(_ i: Index, offsetBy n: Int) -> Index {
if _fastPath(_guts.isFastUTF8) {
_precondition(n + i._encodedOffset <= _guts.count)
return i.encoded(offsetBy: n)
}
return _foreignIndex(i, offsetBy: n)
}
@inlinable @inline(__always)
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
if _fastPath(_guts.isFastUTF8) {
// Check the limit: ignore limit if it precedes `i` (in the correct
// direction), otherwise must not be beyond limit (in the correct
// direction).
let iOffset = i._encodedOffset
let result = iOffset + n
let limitOffset = limit._encodedOffset
if n >= 0 {
guard limitOffset < iOffset || result <= limitOffset else { return nil }
} else {
guard limitOffset > iOffset || result >= limitOffset else { return nil }
}
return Index(_encodedOffset: result)
}
return _foreignIndex(i, offsetBy: n, limitedBy: limit)
}
@inlinable @inline(__always)
public func distance(from i: Index, to j: Index) -> Int {
if _fastPath(_guts.isFastUTF8) {
return j._encodedOffset &- i._encodedOffset
}
return _foreignDistance(from: i, to: j)
}
/// Accesses the code unit at the given position.
///
/// The following example uses the subscript to print the value of a
/// string's first UTF-8 code unit.
///
/// let greeting = "Hello, friend!"
/// let i = greeting.utf8.startIndex
/// print("First character's UTF-8 code unit: \(greeting.utf8[i])")
/// // Prints "First character's UTF-8 code unit: 72"
///
/// - Parameter position: A valid index of the view. `position`
/// must be less than the view's end index.
@inlinable
public subscript(i: Index) -> UTF8.CodeUnit {
@inline(__always) get {
String(_guts)._boundsCheck(i)
if _fastPath(_guts.isFastUTF8) {
return _guts.withFastUTF8 { utf8 in utf8[_unchecked: i._encodedOffset] }
}
return _foreignSubscript(position: i)
}
}
}
extension String.UTF8View: CustomStringConvertible {
@inlinable
public var description: String {
@inline(__always) get { return String(String(_guts)) }
}
}
extension String.UTF8View: CustomDebugStringConvertible {
public var debugDescription: String {
return "UTF8View(\(self.description.debugDescription))"
}
}
extension String {
/// A UTF-8 encoding of `self`.
@inlinable
public var utf8: UTF8View {
@inline(__always) get { return UTF8View(self._guts) }
set { self = String(newValue._guts) }
}
/// A contiguously stored null-terminated UTF-8 representation of the string.
///
/// To access the underlying memory, invoke `withUnsafeBufferPointer` on the
/// array.
///
/// let s = "Hello!"
/// let bytes = s.utf8CString
/// print(bytes)
/// // Prints "[72, 101, 108, 108, 111, 33, 0]"
///
/// bytes.withUnsafeBufferPointer { ptr in
/// print(strlen(ptr.baseAddress!))
/// }
/// // Prints "6"
public var utf8CString: ContiguousArray<CChar> {
if _fastPath(_guts.isFastUTF8) {
var result = _guts.withFastCChar { ContiguousArray($0) }
result.append(0)
return result
}
return _slowUTF8CString()
}
@usableFromInline @inline(never) // slow-path
internal func _slowUTF8CString() -> ContiguousArray<CChar> {
var result = ContiguousArray<CChar>()
result.reserveCapacity(self._guts.count + 1)
for c in self.utf8 {
result.append(CChar(bitPattern: c))
}
result.append(0)
return result
}
/// Creates a string corresponding to the given sequence of UTF-8 code units.
@available(swift, introduced: 4.0, message:
"Please use failable String.init?(_:UTF8View) when in Swift 3.2 mode")
@inlinable @inline(__always)
public init(_ utf8: UTF8View) {
self = String(utf8._guts)
}
}
extension String.UTF8View {
@inlinable
public var count: Int {
@inline(__always) get {
if _fastPath(_guts.isFastUTF8) {
return _guts.count
}
return _foreignCount()
}
}
}
// Index conversions
extension String.UTF8View.Index {
/// Creates an index in the given UTF-8 view that corresponds exactly to the
/// specified `UTF16View` position.
///
/// The following example finds the position of a space in a string's `utf16`
/// view and then converts that position to an index in the string's
/// `utf8` view.
///
/// let cafe = "Café 🍵"
///
/// let utf16Index = cafe.utf16.firstIndex(of: 32)!
/// let utf8Index = String.UTF8View.Index(utf16Index, within: cafe.utf8)!
///
/// print(Array(cafe.utf8[..<utf8Index]))
/// // Prints "[67, 97, 102, 195, 169]"
///
/// If the position passed in `utf16Index` doesn't have an exact
/// corresponding position in `utf8`, the result of the initializer is
/// `nil`. For example, because UTF-8 and UTF-16 represent high Unicode code
/// points differently, an attempt to convert the position of the trailing
/// surrogate of a UTF-16 surrogate pair fails.
///
/// The next example attempts to convert the indices of the two UTF-16 code
/// points that represent the teacup emoji (`"🍵"`). The index of the lead
/// surrogate is successfully converted to a position in `utf8`, but the
/// index of the trailing surrogate is not.
///
/// let emojiHigh = cafe.utf16.index(after: utf16Index)
/// print(String.UTF8View.Index(emojiHigh, within: cafe.utf8))
/// // Prints "Optional(String.Index(...))"
///
/// let emojiLow = cafe.utf16.index(after: emojiHigh)
/// print(String.UTF8View.Index(emojiLow, within: cafe.utf8))
/// // Prints "nil"
///
/// - Parameters:
/// - sourcePosition: A position in a `String` or one of its views.
/// - target: The `UTF8View` in which to find the new position.
@inlinable
public init?(_ idx: String.Index, within target: String.UTF8View) {
if _slowPath(target._guts.isForeign) {
guard idx._foreignIsWithin(target) else { return nil }
} else {
// All indices, except sub-scalar UTF-16 indices pointing at trailing
// surrogates, are valid.
guard idx.transcodedOffset == 0 else { return nil }
}
self = idx
}
}
// Reflection
extension String.UTF8View : CustomReflectable {
/// Returns a mirror that reflects the UTF-8 view of a string.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self)
}
}
//===--- Slicing Support --------------------------------------------------===//
/// In Swift 3.2, in the absence of type context,
///
/// someString.utf8[someString.utf8.startIndex..<someString.utf8.endIndex]
///
/// was deduced to be of type `String.UTF8View`. Provide a more-specific
/// Swift-3-only `subscript` overload that continues to produce
/// `String.UTF8View`.
extension String.UTF8View {
public typealias SubSequence = Substring.UTF8View
@inlinable
@available(swift, introduced: 4)
public subscript(r: Range<Index>) -> String.UTF8View.SubSequence {
return Substring.UTF8View(self, _bounds: r)
}
}
extension String.UTF8View {
/// Copies `self` into the supplied buffer.
///
/// - Precondition: The memory in `self` is uninitialized. The buffer must
/// contain sufficient uninitialized memory to accommodate
/// `source.underestimatedCount`.
///
/// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]`
/// are initialized.
@inlinable @inline(__always)
public func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Iterator.Element>
) -> (Iterator, UnsafeMutableBufferPointer<Iterator.Element>.Index) {
guard buffer.baseAddress != nil else {
_preconditionFailure(
"Attempt to copy string contents into nil buffer pointer")
}
guard let written = _guts.copyUTF8(into: buffer) else {
_preconditionFailure(
"Insufficient space allocated to copy string contents")
}
let it = String().utf8.makeIterator()
return (it, buffer.index(buffer.startIndex, offsetBy: written))
}
}
// Foreign string support
extension String.UTF8View {
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(after i: Index) -> Index {
_internalInvariant(_guts.isForeign)
let (scalar, scalarLen) = _guts.foreignErrorCorrectedScalar(
startingAt: i.strippingTranscoding)
let utf8Len = _numUTF8CodeUnits(scalar)
if utf8Len == 1 {
_internalInvariant(i.transcodedOffset == 0)
return i.nextEncoded
}
// Check if we're still transcoding sub-scalar
if i.transcodedOffset < utf8Len - 1 {
return i.nextTranscoded
}
// Skip to the next scalar
return i.encoded(offsetBy: scalarLen)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(before i: Index) -> Index {
_internalInvariant(_guts.isForeign)
if i.transcodedOffset != 0 {
_internalInvariant((1...3) ~= i.transcodedOffset)
return i.priorTranscoded
}
let (scalar, scalarLen) = _guts.foreignErrorCorrectedScalar(
endingAt: i)
let utf8Len = _numUTF8CodeUnits(scalar)
return i.encoded(offsetBy: -scalarLen).transcoded(withOffset: utf8Len &- 1)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignSubscript(position i: Index) -> UTF8.CodeUnit {
_internalInvariant(_guts.isForeign)
let scalar = _guts.foreignErrorCorrectedScalar(
startingAt: _guts.scalarAlign(i)).0
let encoded = Unicode.UTF8.encode(scalar)._unsafelyUnwrappedUnchecked
_internalInvariant(i.transcodedOffset < 1+encoded.count)
return encoded[
encoded.index(encoded.startIndex, offsetBy: i.transcodedOffset)]
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(_ i: Index, offsetBy n: Int) -> Index {
_internalInvariant(_guts.isForeign)
return _index(i, offsetBy: n)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
_internalInvariant(_guts.isForeign)
return _index(i, offsetBy: n, limitedBy: limit)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignDistance(from i: Index, to j: Index) -> Int {
_internalInvariant(_guts.isForeign)
return _distance(from: i, to: j)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignCount() -> Int {
_internalInvariant(_guts.isForeign)
return _distance(from: startIndex, to: endIndex)
}
}
extension String.Index {
@usableFromInline @inline(never) // opaque slow-path
@_effects(releasenone)
internal func _foreignIsWithin(_ target: String.UTF8View) -> Bool {
_internalInvariant(target._guts.isForeign)
// Currently, foreign means UTF-16.
// If we're transcoding, we're already a UTF8 view index.
if self.transcodedOffset != 0 { return true }
// Otherwise, we must be scalar-aligned, i.e. not pointing at a trailing
// surrogate.
return target._guts.isOnUnicodeScalarBoundary(self)
}
}
extension String.UTF8View {
@inlinable
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
guard _guts.isFastUTF8 else { return nil }
return try _guts.withFastUTF8(body)
}
}
| apache-2.0 | e54ad4492bd0d07b7fa7706f6f62bfac | 30.965251 | 80 | 0.643073 | 3.995656 | false | false | false | false |
ashfurrow/eidolon | Kiosk/Help/HelpViewController.swift | 2 | 7825 | import UIKit
import ORStackView
import Artsy_UILabels
import Artsy_UIButtons
import Action
import RxSwift
import RxCocoa
class HelpViewController: UIViewController {
var positionConstraints: [NSLayoutConstraint]?
var dismissTapGestureRecognizer: UITapGestureRecognizer?
fileprivate let stackView = ORTagBasedAutoStackView()
fileprivate var buyersPremiumButton: UIButton!
fileprivate let sideMargin: Float = 90.0
fileprivate let topMargin: Float = 45.0
fileprivate let headerMargin: Float = 25.0
fileprivate let inbetweenMargin: Float = 10.0
var showBuyersPremiumCommand = { () -> CocoaAction in
appDelegate().showBuyersPremiumCommand()
}
var registerToBidCommand = { (enabled: Observable<Bool>) -> CocoaAction in
appDelegate().registerToBidCommand(enabled: enabled)
}
var requestBidderDetailsCommand = { (enabled: Observable<Bool>) -> CocoaAction in
appDelegate().requestBidderDetailsCommand(enabled: enabled)
}
var showPrivacyPolicyCommand = { () -> CocoaAction in
appDelegate().showPrivacyPolicyCommand()
}
var showConditionsOfSaleCommand = { () -> CocoaAction in
appDelegate().showConditionsOfSaleCommand()
}
lazy var hasBuyersPremium: Observable<Bool> = {
return appDelegate()
.appViewController
.sale
.value
.rx.observe(String.self, "buyersPremium")
.map { $0.hasValue }
}()
class var width: Float {
get {
return 415.0
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Configure view
view.backgroundColor = .white
addSubviews()
}
}
private extension HelpViewController {
enum SubviewTag: Int {
case assistanceLabel = 0
case stuckLabel, stuckExplainLabel
case bidLabel, bidExplainLabel
case registerButton
case bidderDetailsLabel, bidderDetailsExplainLabel, bidderDetailsButton
case conditionsOfSaleButton, buyersPremiumButton, privacyPolicyButton
}
func addSubviews() {
// Configure subviews
let assistanceLabel = ARSerifLabel()
assistanceLabel.font = assistanceLabel.font.withSize(35)
assistanceLabel.text = "Assistance"
assistanceLabel.tag = SubviewTag.assistanceLabel.rawValue
let stuckLabel = titleLabel(tag: .stuckLabel, title: "Stuck in the process?")
let stuckExplainLabel = wrappingSerifLabel(tag: .stuckExplainLabel, text: "Find the nearest Artsy representative and they will assist you.")
let bidLabel = titleLabel(tag: .bidLabel, title: "How do I place a bid?")
let bidExplainLabel = wrappingSerifLabel(tag: .bidExplainLabel, text: "Enter the amount you would like to bid. You will confirm this bid in the next step. Enter your mobile number or bidder number and PIN that you received when you registered.")
bidExplainLabel.makeSubstringsBold(["mobile number", "bidder number", "PIN"])
var registerButton = blackButton(tag: .registerButton, title: "Register")
registerButton.rx.action = registerToBidCommand(connectedToInternetOrStubbing())
let bidderDetailsLabel = titleLabel(tag: .bidderDetailsLabel, title: "What Are Bidder Details?")
let bidderDetailsExplainLabel = wrappingSerifLabel(tag: .bidderDetailsExplainLabel, text: "The bidder number is how you can identify yourself to bid and see your place in bid history. The PIN is a four digit number that authenticates your bid.")
bidderDetailsExplainLabel.makeSubstringsBold(["bidder number", "PIN"])
var sendDetailsButton = blackButton(tag: .bidderDetailsButton, title: "Send me my details")
sendDetailsButton.rx.action = requestBidderDetailsCommand(connectedToInternetOrStubbing())
var conditionsButton = serifButton(tag: .conditionsOfSaleButton, title: "Conditions of Sale")
conditionsButton.rx.action = showConditionsOfSaleCommand()
buyersPremiumButton = serifButton(tag: .buyersPremiumButton, title: "Buyers Premium")
buyersPremiumButton.rx.action = showBuyersPremiumCommand()
var privacyButton = serifButton(tag: .privacyPolicyButton, title: "Privacy Policy")
privacyButton.rx.action = showPrivacyPolicyCommand()
// Add subviews
view.addSubview(stackView)
stackView.alignTop("0", leading: "0", bottom: nil, trailing: "0", to: view)
stackView.addSubview(assistanceLabel, withTopMargin: "\(topMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(stuckLabel, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(stuckExplainLabel, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(bidLabel, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(bidExplainLabel, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(registerButton, withTopMargin: "20", sideMargin: "\(sideMargin)")
stackView.addSubview(bidderDetailsLabel, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(bidderDetailsExplainLabel, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(sendDetailsButton, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(conditionsButton, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(privacyButton, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(self.sideMargin)")
hasBuyersPremium
.subscribe(onNext: { [weak self] hasBuyersPremium in
if hasBuyersPremium {
self?.stackView.addSubview(self!.buyersPremiumButton, withTopMargin: "\(self!.inbetweenMargin)", sideMargin: "\(self!.sideMargin)")
} else {
self?.stackView.removeSubview(self!.buyersPremiumButton)
}
})
.disposed(by: rx.disposeBag)
}
func blackButton(tag: SubviewTag, title: String) -> ARBlackFlatButton {
let button = ARBlackFlatButton()
button.setTitle(title, for: .normal)
button.tag = tag.rawValue
return button
}
func serifButton(tag: SubviewTag, title: String) -> ARUnderlineButton {
let button = ARUnderlineButton()
button.setTitle(title, for: .normal)
button.setTitleColor(.artsyGrayBold(), for: .normal)
button.titleLabel?.font = UIFont.serifFont(withSize: 18)
button.contentHorizontalAlignment = .left
button.tag = tag.rawValue
return button
}
func wrappingSerifLabel(tag: SubviewTag, text: String) -> UILabel {
let label = ARSerifLabel()
label.font = label.font.withSize(18)
label.lineBreakMode = .byWordWrapping
label.preferredMaxLayoutWidth = CGFloat(HelpViewController.width - sideMargin)
label.tag = tag.rawValue
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4
label.attributedText = NSAttributedString(string: text, attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle])
return label
}
func titleLabel(tag: SubviewTag, title: String) -> ARSerifLabel {
let label = ARSerifLabel()
label.font = label.font.withSize(24)
label.text = title
label.tag = tag.rawValue
return label
}
}
| mit | f3ec3b4abaf1731bcbf94148d399e9fc | 41.994505 | 253 | 0.669393 | 5.491228 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureKYC/Sources/FeatureKYCUI/KYCBaseViewController.swift | 1 | 3998 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import FeatureKYCDomain
import Localization
import PlatformKit
import PlatformUIKit
import SafariServices
import ToolKit
class KYCBaseViewController: UIViewController, KYCRouterDelegate, KYCOnboardingNavigationControllerDelegate {
private let webViewService: WebViewServiceAPI = resolve()
var router: KYCRouter!
var pageType: KYCPageType = .welcome
class func make(with coordinator: KYCRouter) -> KYCBaseViewController {
assertionFailure("Should be implemented by subclasses")
return KYCBaseViewController()
}
func apply(model: KYCPageModel) {
Logger.shared.debug("Should be overriden to do something with KYCPageModel.")
}
override func viewDidLoad() {
super.viewDidLoad()
// TICKET: IOS-1236 - Refactor KYCBaseViewController NavigationBarItem Titles
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
setupBarButtonItem()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setupBarButtonItem()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
router.delegate = self
router.handle(event: .pageWillAppear(pageType))
}
override func viewWillDisappear(_ animated: Bool) {
router.delegate = nil
super.viewWillDisappear(animated)
}
// MARK: Private Functions
fileprivate func setupBarButtonItem() {
guard let navController = navigationController as? KYCOnboardingNavigationController else { return }
let appearance = UINavigationBarAppearance()
appearance.backgroundColor = .white
navController.navigationBar.standardAppearance = appearance
navController.navigationBar.compactAppearance = appearance
navController.navigationBar.scrollEdgeAppearance = appearance
navController.onboardingDelegate = self
navController.setupBarButtonItem()
}
fileprivate func presentNeedSomeHelpAlert() {
let confirm = AlertAction(style: .confirm(LocalizationConstants.KYC.readNow))
let cancel = AlertAction(style: .default(LocalizationConstants.KYC.contactSupport))
let model = AlertModel(
headline: LocalizationConstants.KYC.needSomeHelp,
body: LocalizationConstants.KYC.helpGuides,
actions: [confirm, cancel]
)
let alert = AlertView.make(with: model) { [weak self] action in
guard let this = self else { return }
switch action.style {
case .confirm:
let url = "https://blockchain.zendesk.com/hc/en-us/categories/360001135512-Identity-Verification"
this.webViewService.openSafari(url: url, from: this)
case .default:
let url = "https://blockchain.zendesk.com/hc/en-us/requests/new?ticket_form_id=360000186571"
this.webViewService.openSafari(url: url, from: this)
case .dismiss:
break
}
}
alert.show()
}
func navControllerCTAType() -> NavigationCTA {
guard let navController = navigationController as? KYCOnboardingNavigationController else { return .none }
return navController.viewControllers.count == 1 ? .dismiss : .help
}
func navControllerRightBarButtonTapped(_ navController: KYCOnboardingNavigationController) {
switch navControllerCTAType() {
case .none:
break
case .dismiss:
onNavControllerRightBarButtonWillDismiss()
router.stop()
case .help:
presentNeedSomeHelpAlert()
case .skip:
onNavControllerRightBarButtonSkip()
}
}
// MARK: - Optionally override
func onNavControllerRightBarButtonWillDismiss() {}
func onNavControllerRightBarButtonSkip() {}
}
| lgpl-3.0 | 28bbc43fc104a222d81297fcc59f64f7 | 35.336364 | 114 | 0.678759 | 5.343583 | false | false | false | false |
daisukenagata/BLEView | BLEView/Classes/BLNotification.swift | 1 | 1868 | //
// BLNotification.swift
// Pods
//
// Created by 永田大祐 on 2017/02/12.
//
//
import UIKit
import CoreLocation
extension BLBeacon {
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion)
{
if(beacons.count > 0){
for i in 0 ..< beacons.count {
let beacon = beacons[i]
let rssi = beacon.rssi;
var proximity = ""
switch (beacon.proximity) {
case CLProximity.unknown :
print("Proximity: Unknown");
proximity = "Unknown"
break
case CLProximity.far:
print("Proximity: Far");
proximity = "Far"
break
case CLProximity.near:
print("Proximity: Near");
proximity = "Near"
break
case CLProximity.immediate:
print("Proximity: Immediate");
proximity = "Immediate"
break
@unknown default: break
}
BlModel.sharedBLEBeacon.blLocationManager = blLocationManager
BlModel.sharedBLEBeacon.statusStr = (rssi * -1 ).description
BlModel.sharedBLEBeacon.proximity = proximity
if BlModel.sharedBLEBeacon.statusStr != ""{
BlModel.sharedBLETableView.update()
}
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "beaconReceive"), object: self )
}
}
}
}
| mit | 0c8a8ef91c19e6f04c21a3386e582cff | 29.491803 | 118 | 0.45 | 6.118421 | false | false | false | false |
mirego/taylor-ios | TaylorTests/Types/StringTexts.swift | 1 | 4008 | // Copyright (c) 2016, Mirego
// 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 the Mirego 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 XCTest
import Taylor
class StringTests: XCTestCase {
func testRegExp()
{
let emailRegExp = "^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,63}$"
XCTAssertTrue("genius@mirego.com".matches(emailRegExp))
XCTAssertFalse("genius@mirego".matches(emailRegExp))
XCTAssertFalse("genius@mirego".matches(""))
XCTAssertFalse("".matches(""))
XCTAssertFalse("".matches(emailRegExp))
// Case sensitive
XCTAssertTrue("genius".matches("GENIUS", caseSensitive: false) )
XCTAssertFalse("genius".matches("GENIUS", caseSensitive: true))
}
func testIsEmailAddress()
{
// General
XCTAssertTrue("genius@mirego.com".isEmailAddress())
XCTAssertTrue("GENIUS@MIREGO.COM".isEmailAddress())
XCTAssertTrue("genius@mirego.newtldwithlongname".isEmailAddress())
XCTAssertFalse("genius_!mirego1q2312@mirego".isEmailAddress())
XCTAssertFalse("@mirego".isEmailAddress())
// Missing parts
XCTAssertFalse("@mirego.com".isEmailAddress())
XCTAssertFalse("genius.mirego.com".isEmailAddress())
XCTAssertFalse("genius@mirego".isEmailAddress())
XCTAssertFalse("genius@.com".isEmailAddress())
// With Spaces
XCTAssertTrue("genius mirego@mirego.com".isEmailAddress())
XCTAssertFalse("genius mirego@mirego domain.com".isEmailAddress())
}
func testTrim() {
let trimmedString = "This is a string"
let stringWithSpaces = "\t \(trimmedString) \t "
var string = String(stringWithSpaces)
XCTAssertEqual(string.trimmed, trimmedString)
// Should not mutate the string
XCTAssertEqual(string, stringWithSpaces)
// Should mutate the string
string.trim()
XCTAssertEqual(string, trimmedString)
// Test empty string
XCTAssertEqual("".trimmed, "")
}
func testCapitalizeFirstLetter() {
let capitalizedString = "Capitalize first letter only"
var string = "capitalize first letter only"
XCTAssertEqual(string.capitalizedFirstLetter, capitalizedString)
// Should not mutate the string
XCTAssertEqual(string, "capitalize first letter only")
// Should mutate the string
string.capitalizeFirstLetter()
XCTAssertEqual(string, capitalizedString)
// Test empty string
XCTAssertEqual("".capitalizedFirstLetter, "")
}
}
| bsd-3-clause | a89451f2e65345de9096f473e0657feb | 39.08 | 79 | 0.697854 | 5.086294 | false | true | false | false |
silence0201/Swift-Study | SwiftLearn/MySwift13_subscripts_operator_overloading.playground/Contents.swift | 1 | 6654 | //: Playground - noun: a place where people can play
import UIKit
/**
Swift_subscripts_operator_overloading
*/
var arr = [0,1,2,3]
arr[1]
var dict = ["北京":"Beijing", "纽约":"New York", "巴黎":"Paris"]
dict["北京"]
struct Vector3{
var x:Double = 0.0
var y:Double = 0.0
var z:Double = 0.0
subscript(index:Int) -> Double?{
get{
switch index{
case 0: return x
case 1: return y
case 2: return z
default: return nil
}
}
/// 默认新值是newValue, 其类型与get的返回类型相同
set{
guard let newValue = newValue else{ return }
switch index{
case 0: x = newValue
case 1: y = newValue
case 2: z = newValue
default: return
}
}
}
subscript(axis:String) -> Double?{
get{
switch axis{
case "x","X": return x
case "y","Y": return y
case "z","Z": return z
default: return nil
}
}
set{
guard let newValue = newValue else{ return }
switch axis{
case "x","X": x = newValue
case "y","Y": y = newValue
case "z","Z": z = newValue
default: return
}
}
}
//返回向量的模
func lenght() -> Double{
return sqrt(x * x + y * y + z * z)
}
}
var v = Vector3(x: 1.0, y: 2.0, z: 3.0)
v.x
let xxx = v[0] //xxx is Double?
let aaa = v[100] //aaa is nil
v["z"]
v["Y"]
v["Hello"]
v[0] = 100.0
v["Y"] = 30
v
///Swift支持有任意多个参数的下标.
struct Matrix{
var data:[[Double]]
let r:Int
let c:Int
init(row:Int, col:Int){
self.r = row
self.c = col
data = [[Double]]()
for _ in 0..<r{
let aRow = Array(repeating: 0.0, count: col)
data.append(aRow)
}
}
//m[1,1]
subscript(x: Int, y: Int) -> Double{
get{
assert( x >= 0 && x < r && y >= 0 && y < c , "Index Out of Range")
return data[x][y]
}
set{ //内置函数 assert
assert( x >= 0 && x < r && y >= 0 && y < c , "Index Out of Range")
data[x][y] = newValue
}
}
// 如果想使用 m[1][1]
subscript(row: Int) -> [Double]{
get{
assert( row >= 0 && row < r , "Index Out of Range")
return data[row]
}
set(vector){ //newValue应该是get的返回值类型
assert( vector.count == c , "Column Number does NOT match")
data[row] = vector
}
}
}
var m = Matrix(row: 2, col: 2)
//m[2,2] //EXC_BAD_INSTRUCTION
m[1,1]
// 如果想使用 m[1][1]
m[1][1]
m[1]
m[0] = [1.5,4.5]
m[0][0]
m[0][1]
// 更多关于assert,留在错误处理进行讲解
// 对于下标的使用
// 实现魔方
// 实现数据结构,如链表
// 实现数据Table,等等等等
//运算符重载, 运算符本质就是函数. *** = 等号是不能被重载的, 是由系统所保留的, 因为它在低层是内存管理相关的.
//重载的运算符函数要定义在结构外面.
func + (left: Vector3, right: Vector3) -> Vector3{
return Vector3(x: left.x + right.x, y: left.y + right.y, z: left.z + right.z)
}
var va = Vector3(x: 1.0, y: 2.0, z: 3.0)
let vb = Vector3(x: 3.0, y: 4.0, z: 5.0)
va + vb
func - (left: Vector3, right: Vector3) -> Vector3{
return Vector3(x: left.x - right.x, y: left.y - right.y, z: left.z - right.z)
}
va - vb
//内积
func * (left: Vector3, right: Vector3) -> Double{
return left.x * right.x + left.y * right.y + left.z * right.z
}
va * vb
func * (left: Vector3, a: Double) -> Vector3{
return Vector3(x: left.x * a, y: left.y * a, z: left.z * a)
}
va * -1.0
func * (a: Double, right: Vector3) -> Vector3{
return right * a
}
-1.0 * va
//left必须inout, 返回值就不需要了.
func +=( left: inout Vector3, right: Vector3){
left = left + right
}
va += vb
//-号加了prefix, 只能用在前面.
prefix func - (vector: Vector3) -> Vector3{
return Vector3(x: -vector.x, y: -vector.y, z: -vector.z)
}
-va
//比较运算符的重载
func == (left: Vector3, right: Vector3) -> Bool{
return left.x == right.x && left.y == right.y && left.z == right.z
}
va == vb
func != (left: Vector3, right: Vector3) -> Bool{
return !(left == right)
}
va != vb
func < (left: Vector3, right: Vector3) -> Bool{
if left.x != right.x{ return left.x < right.x}
if left.y != right.y{ return left.y < right.y}
if left.z != right.z{ return left.z < right.z}
return false
}
va < vb
func <= (left: Vector3, right: Vector3) -> Bool{
return left < right || left == right
}
func > (left: Vector3, right: Vector3) -> Bool{
return !(left <= right)
}
func >= (left: Vector3, right: Vector3) -> Bool{
return !(left < right)
}
let a = [2, 3, 1, 5]
a.sorted(by: >)
//自定义的运算符重载
// Custom operators can begin with one of the ASCII characters
// ASCII characters /, =, -, +, !, *, %, <, >, &, |, ^, ~, or with one of the Unicode characters
//自定义单目运算符
postfix operator +++ //声明+++将会是一个单目运算符
postfix func +++ ( vector: inout Vector3) -> Vector3 {
vector += Vector3(x: 1.0, y: 1.0, z: 1.0)
return vector
}
va+++
//前置的+++操作
prefix operator +++
prefix func +++( vector: inout Vector3) -> Vector3{
let ret = vector
vector += Vector3(x: 1.0, y: 1.0, z: 1.0)
return ret
}
+++va
va
//双目运算符
//associativity 结合性, 左结合
//precedence 优先级[0~255] 默认是140, 140是与加法平行的优先级,
//infix operator ^{associativity left precedence 140} //swift2
infix operator ^: AAA
precedencegroup AAA {
associativity: left
higherThan: AdditionPrecedence
lowerThan: MultiplicationPrecedence
}
func ^ (left: Vector3, right: Vector3) -> Double{
return acos( (left * right) / (left.lenght() * right.lenght()) )
}
va ^ vb
//优先级设置参考Swift官方文档 乘法优先级是150
//infix operator **{associativity right precedence 155} //swift2
infix operator **: BBB
precedencegroup BBB{
associativity: left
higherThan: AdditionPrecedence
lowerThan: MultiplicationPrecedence
}
func **(x: Double, p:Double) -> Double{
return pow(x, p)
}
2**3
2 ** 3 ** 2 //因为associativity结合性是右结合, 所以先计算3**2=9, 再计算2**9=512
1+2 ** 3 ** 2
5*2 ** 3 ** 2
| mit | b414e655567ff8c74aac445599d31501 | 20.202797 | 96 | 0.529024 | 2.976927 | false | false | false | false |
segura2010/exodobb-for-iOS | exodobbSiriIntent/IntentHandler.swift | 1 | 9152 | //
// IntentHandler.swift
// exodobbSiriIntent
//
// Created by Alberto on 10/9/16.
// Copyright © 2016 Alberto. All rights reserved.
//
import Intents
// As an example, this class is set up to handle Message intents.
// You will want to replace this or add other intents as appropriate.
// The intents you wish to handle must be declared in the extension's Info.plist.
// You can test your example integration by saying things to Siri like:
// "Send a message using <myApp>"
// "<myApp> John saying hello"
// "Search for messages in <myApp>"
class IntentHandler: INExtension, INSendMessageIntentHandling, INSearchForMessagesIntentHandling, INSetMessageAttributeIntentHandling {
var message = ""
var thread = ""
var threadId = ""
override func handler(for intent: INIntent) -> Any {
// This is the default implementation. If you want different objects to handle different intents,
// you can override this and return the handler you want for that particular intent.
print("COOKIE: \(getCookie())")
return self
}
// MARK: - INSendMessageIntentHandling
// Implement resolution methods to provide additional information about your intent (optional).
func resolveRecipients(forSendMessage intent: INSendMessageIntent, with completion: @escaping ([INPersonResolutionResult]) -> Void) {
if let recipients = intent.recipients {
// If no recipients were provided we'll need to prompt for a value.
if recipients.count == 0 {
completion([INPersonResolutionResult.needsValue()])
return
}
var resolutionResults = [INPersonResolutionResult]()
print(recipients)
for recipient in recipients {
var matchingContacts = [INPerson]() // Implement your contact matching logic here to create an array of matching contacts
// Here we must search the topic
// Search endpoint https://exo.do/api/search/keyword?in=titles
print("\(recipient.spokenPhrase)")
print("IDENTIFIER: \(recipient.contactIdentifier)")
print("DIS: \(recipient.displayName)")
print("REC: \(recipient)")
NodeBBAPI.sharedInstance.searchTopicByTitle(recipient.spokenPhrase!, cookie: getCookie()){(error:NSError?, responseObject:[String:AnyObject]?) in
if(error != nil)
{
resolutionResults += [INPersonResolutionResult.unsupported()]
completion(resolutionResults)
return print("error")
}
var person = recipient
//print(responseObject)
if let posts = responseObject?["posts"] as? [[String:AnyObject]]
{
/* We should give the user the option to chose the topic, but now it creates an infinite loop in Siri..
for p in posts
{
let title = p["topic"]?["title"]
let tid = "\(p["topic"]?["tid"])"
//print("\(p["topic"]?["title"])")
var person = INPerson(handle: tid, displayName: title as! String?, contactIdentifier: tid)
matchingContacts.append(person)
}
*/
// So we use the first one
let title = posts[0]["topic"]?["title"]
let tid = "\(posts[0]["topic"]!["tid"]!)" as! String
print("Selected: \(title)")
person = INPerson(handle: tid, displayName: title as! String?, contactIdentifier: tid as! String)
matchingContacts.append(person)
}
switch matchingContacts.count {
case 2 ... Int.max:
// We need Siri's help to ask user to pick one from the matches.
resolutionResults += [INPersonResolutionResult.disambiguation(with: matchingContacts)]
case 1:
// We have exactly one matching contact
resolutionResults += [INPersonResolutionResult.success(with: person)]
case 0:
// We have no contacts matching the description provided
resolutionResults += [INPersonResolutionResult.unsupported()]
default:
break
}
completion(resolutionResults)
}
}
}
}
func resolveContent(forSendMessage intent: INSendMessageIntent, with completion: @escaping (INStringResolutionResult) -> Void) {
if let text = intent.content, !text.isEmpty {
message = text
completion(INStringResolutionResult.success(with: text))
} else {
completion(INStringResolutionResult.needsValue())
}
}
// Once resolution is completed, perform validation on the intent and provide confirmation (optional).
func confirm(sendMessage intent: INSendMessageIntent, completion: @escaping (INSendMessageIntentResponse) -> Void) {
// Verify user is authenticated and your app is ready to send a message.
NodeBBAPI.sharedInstance.initWSEvents()
let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendMessageIntent.self))
let response = INSendMessageIntentResponse(code: .ready, userActivity: userActivity)
completion(response)
}
// Handle the completed intent (required).
func handle(sendMessage intent: INSendMessageIntent, completion: @escaping (INSendMessageIntentResponse) -> Void) {
// Implement your application logic to send a message here.
message = intent.content!
let tid = intent.recipients![0].contactIdentifier!
//let tid = intent.recipients?[0].contactIdentifier
print("SENDING: \(message) to TID: \(tid)")
NodeBBAPI.sharedInstance.sendPost(message, tid:String(tid)!)
let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendMessageIntent.self))
let response = INSendMessageIntentResponse(code: .success, userActivity: userActivity)
completion(response)
}
// Implement handlers for each intent you wish to handle. As an example for messages, you may wish to also handle searchForMessages and setMessageAttributes.
// MARK: - INSearchForMessagesIntentHandling
func handle(searchForMessages intent: INSearchForMessagesIntent, completion: @escaping (INSearchForMessagesIntentResponse) -> Void) {
// Implement your application logic to find a message that matches the information in the intent.
let userActivity = NSUserActivity(activityType: NSStringFromClass(INSearchForMessagesIntent.self))
let response = INSearchForMessagesIntentResponse(code: .success, userActivity: userActivity)
// Initialize with found message's attributes
response.messages = [INMessage(
identifier: "identifier",
content: "I am so excited about SiriKit!",
dateSent: Date(),
sender: INPerson(personHandle: INPersonHandle(value: "sarah@example.com", type: .emailAddress), nameComponents: nil, displayName: "Sarah", image: nil, contactIdentifier: nil, customIdentifier: nil),
recipients: [INPerson(personHandle: INPersonHandle(value: "+1-415-555-5555", type: .phoneNumber), nameComponents: nil, displayName: "John", image: nil, contactIdentifier: nil, customIdentifier: nil)]
)]
completion(response)
}
// MARK: - INSetMessageAttributeIntentHandling
func handle(setMessageAttribute intent: INSetMessageAttributeIntent, completion: @escaping (INSetMessageAttributeIntentResponse) -> Void) {
// Implement your application logic to set the message attribute here.
let userActivity = NSUserActivity(activityType: NSStringFromClass(INSetMessageAttributeIntent.self))
let response = INSetMessageAttributeIntentResponse(code: .success, userActivity: userActivity)
completion(response)
}
func getCookie() -> String
{
let defaults = UserDefaults(suiteName: "group.exodobb")
if let cookie = defaults?.string(forKey: "cookie") {
print("getCookie() -> \(cookie)")
return cookie
}
else{
return ""
}
}
}
| gpl-2.0 | d7f82207c4d8b98817afacf4a313e50e | 44.755 | 212 | 0.586165 | 5.832377 | false | false | false | false |
eurofurence/ef-app_ios | Eurofurence/SwiftUI/Modules/Schedule/ScheduleCollectionView.swift | 1 | 7461 | import EurofurenceKit
import SwiftUI
struct ScheduleCollectionView: View {
@EnvironmentObject var model: EurofurenceModel
@ObservedObject var schedule: Schedule
@Environment(\.showScheduleFilterButton) private var showScheduleFilter
@State private var isPresentingFilter = false
@State private var selectedEvent: Event?
var body: some View {
ScheduleEventsList(schedule: schedule)
.searchable(text: $schedule.query.animation())
.toolbar {
ToolbarItem(placement: .status) {
statusView
}
ToolbarItem(placement: .bottomBar) {
if showScheduleFilter {
ScheduleFilterButton(isPresentingFilter: $isPresentingFilter, schedule: schedule)
}
}
}
}
@ViewBuilder
private var statusView: some View {
VStack {
Text(
"\(schedule.matchingEventsCount) matching events",
comment: "Format for presenting the number of matching events in a schedule"
)
.font(.caption)
if let localizedFilterDescription = schedule.localizedFilterDescription {
Text(verbatim: localizedFilterDescription)
.font(.caption2)
}
}
}
}
private struct ScheduleFilterButton: View {
@Binding var isPresentingFilter: Bool
var schedule: Schedule
var body: some View {
Button {
isPresentingFilter.toggle()
} label: {
Label {
Text("Filter")
} icon: {
if isPresentingFilter {
Image(systemName: "line.3.horizontal.decrease.circle.fill")
} else {
Image(systemName: "line.3.horizontal.decrease.circle")
}
}
}
.popover(isPresented: $isPresentingFilter) {
NavigationView {
ScheduleFilterView(schedule: schedule)
}
.sensiblePopoverFrame()
.filteringInterfaceDetents()
}
}
}
private struct ScheduleFilterView: View {
@ObservedObject var schedule: Schedule
@Environment(\.dismiss) private var dismiss
var body: some View {
Form {
Toggle(isOn: $schedule.favouritesOnly.animation()) {
Label {
Text("Favourites Only")
} icon: {
FavouriteIcon(filled: true)
}
}
if schedule.availableDays.isEmpty == false {
Section {
ScheduleDayPicker(schedule: schedule)
} header: {
Text("Day")
}
}
if schedule.availableTracks.isEmpty == false {
Section {
ScheduleTrackPicker(schedule: schedule)
} header: {
Text("Track")
}
}
if schedule.availableRooms.isEmpty == false {
Section {
ScheduleRoomPicker(schedule: schedule)
} header: {
Text("Room")
}
}
}
.listStyle(.insetGrouped)
.navigationTitle("Filters")
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button {
dismiss()
} label: {
Text("Done")
}
}
}
}
}
private struct ScheduleDayPicker: View {
@ObservedObject var schedule: Schedule
var body: some View {
SelectableRow(tag: nil, selection: $schedule.selectedDay.animation()) {
Label {
Text("Entire Convention")
} icon: {
if schedule.selectedTrack == nil {
Image(systemName: "calendar.circle.fill")
} else {
Image(systemName: "calendar.circle")
}
}
}
ForEach(schedule.availableDays) { day in
SelectableRow(tag: day, selection: $schedule.selectedDay.animation()) {
DayLabel(day: day, isSelected: schedule.selectedDay == day)
}
}
}
}
private struct ScheduleTrackPicker: View {
@ObservedObject var schedule: Schedule
var body: some View {
SelectableRow(tag: nil, selection: $schedule.selectedTrack.animation()) {
Label {
Text("All Tracks")
} icon: {
if schedule.selectedTrack == nil {
Image(systemName: "square.stack.fill")
} else {
Image(systemName: "square.stack")
}
}
}
ForEach(schedule.availableTracks) { track in
SelectableRow(tag: track, selection: $schedule.selectedTrack.animation()) {
TrackLabel(track, isSelected: schedule.selectedTrack == track)
}
}
}
}
private struct ScheduleRoomPicker: View {
@ObservedObject var schedule: Schedule
var body: some View {
SelectableRow(tag: nil, selection: $schedule.selectedRoom.animation()) {
Text("Everywhere")
}
ForEach(schedule.availableRooms) { room in
SelectableRow(tag: room, selection: $schedule.selectedRoom.animation()) {
Text(room.shortName)
}
}
}
}
struct ScheduleCollectionView_Previews: PreviewProvider {
static var previews: some View {
EurofurenceModel.preview { model in
NavigationView {
ScheduleCollectionView(schedule: model.makeSchedule())
.navigationTitle("Preview")
}
.previewDisplayName("Unconfigured Schedule")
NavigationView {
let dayConfiguration = EurofurenceModel.ScheduleConfiguration(day: model.day(for: .conDayTwo))
ScheduleCollectionView(schedule: model.makeSchedule(configuration: dayConfiguration))
.navigationTitle("Preview")
}
.previewDisplayName("Day Specific Schedule")
NavigationView {
let trackConfiguration = EurofurenceModel.ScheduleConfiguration(track: model.track(for: .clubStage))
ScheduleCollectionView(schedule: model.makeSchedule(configuration: trackConfiguration))
.navigationTitle("Preview")
}
.previewDisplayName("Track Specific Schedule")
NavigationView {
let dayAndTrackConfiguration = EurofurenceModel.ScheduleConfiguration(
day: model.day(for: .conDayTwo),
track: model.track(for: .clubStage)
)
let scheduleController = model.makeSchedule(configuration: dayAndTrackConfiguration)
ScheduleCollectionView(schedule: scheduleController)
.navigationTitle("Preview")
}
.previewDisplayName("Day + Track Specific Schedule")
}
}
}
| mit | d529f4214f4feeaf9ea68f83e3be5b32 | 30.348739 | 116 | 0.518161 | 5.851765 | false | true | false | false |
danwatco/mega-liker | MegaLiker/SettingsViewController.swift | 1 | 2117 | //
// SettingsViewController.swift
// MegaLiker
//
// Created by Dan Watkinson on 27/11/2015.
// Copyright © 2015 Dan Watkinson. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
var clientID = "[INSTAGRAM_CLIENT_ID]"
var defaults = NSUserDefaults.standardUserDefaults()
@IBOutlet weak var statusLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
let accessCode = defaults.objectForKey("accessCode")
if(accessCode != nil){
statusLabel.text = "You are now signed in."
}
}
@IBAction func signInBtn(sender: UIButton) {
let userScope = "&scope=likes"
let instagramURL = "https://instagram.com/oauth/authorize/?client_id=" + clientID + "&redirect_uri=megaliker://callback&response_type=token" + userScope
UIApplication.sharedApplication().openURL(NSURL(string: instagramURL)!)
}
@IBAction func signOutBtn(sender: UIButton) {
defaults.removeObjectForKey("accessCode")
statusLabel.textColor = UIColor.redColor()
statusLabel.text = "You are now signed out."
let navController:CustomNavigationController = self.parentViewController as! CustomNavigationController
let viewController:ViewController = navController.viewControllers.first as! ViewController
viewController.userStatus = false
viewController.accessCode = nil
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 0d313230912efdd6ce04e547934067de | 32.587302 | 160 | 0.681474 | 5.038095 | false | false | false | false |
taketo1024/SwiftyAlgebra | Sources/SwmCore/Matrix/MatrixImpl.swift | 1 | 10729 | //
// MatrixImpl.swift
// Sample
//
// Created by Taketo Sano on 2019/10/04.
//
public protocol MatrixImpl: Equatable, CustomStringConvertible {
associatedtype BaseRing: Ring
typealias Initializer = (Int, Int, BaseRing) -> Void
init(size: MatrixSize, initializer: (Initializer) -> Void)
init<S: Sequence>(size: MatrixSize, grid: S) where S.Element == BaseRing
init<S: Sequence>(size: MatrixSize, entries: S) where S.Element == MatrixEntry<BaseRing>
static func zero(size: MatrixSize) -> Self
static func identity(size: MatrixSize) -> Self
static func unit(size: MatrixSize, at: (Int, Int)) -> Self
static func scalar(size: MatrixSize, value: BaseRing) -> Self
subscript(i: Int, j: Int) -> BaseRing { get set }
var size: (rows: Int, cols: Int) { get }
var isZero: Bool { get }
var isIdentity: Bool { get }
var isInvertible: Bool { get }
var inverse: Self? { get }
var transposed: Self { get }
var determinant: BaseRing { get }
var trace: BaseRing { get }
func rowVector(_ i: Int) -> Self
func colVector(_ j: Int) -> Self
func submatrix(rowRange: Range<Int>) -> Self
func submatrix(colRange: Range<Int>) -> Self
func submatrix(rowRange: Range<Int>, colRange: Range<Int>) -> Self
func concat(_ B: Self) -> Self
func stack(_ B: Self) -> Self
func permuteRows(by p: Permutation<anySize>) -> Self
func permuteCols(by q: Permutation<anySize>) -> Self
func permute(rowsBy p: Permutation<anySize>, colsBy q: Permutation<anySize>) -> Self
var nonZeroEntries: AnySequence<MatrixEntry<BaseRing>> { get }
func mapNonZeroEntries(_ f: (Int, Int, BaseRing) -> BaseRing) -> Self
func serialize() -> [BaseRing]
static func ==(a: Self, b: Self) -> Bool
static func +(a: Self, b: Self) -> Self
static prefix func -(a: Self) -> Self
static func -(a: Self, b: Self) -> Self
static func *(r: BaseRing, a: Self) -> Self
static func *(a: Self, r: BaseRing) -> Self
static func *(a: Self, b: Self) -> Self
static func ⊕(a: Self, b: Self) -> Self
static func ⊗(a: Self, b: Self) -> Self
}
// MEMO: default implementations are provided,
// but conforming types should override them for performance.
extension MatrixImpl {
public init<S: Sequence>(size: MatrixSize, grid: S) where S.Element == BaseRing {
let m = size.cols
self.init(size: size, entries: grid.enumerated().lazy.compactMap{ (idx, a) in
if !a.isZero {
let (i, j) = (idx / m, idx % m)
return (i, j, a)
} else {
return nil
}
})
}
public init<S: Sequence>(size: MatrixSize, entries: S) where S.Element == MatrixEntry<BaseRing> {
self.init(size: size) { setEntry in
entries.forEach { (i, j, a) in setEntry(i, j, a) }
}
}
public static func zero(size: MatrixSize) -> Self {
.init(size: size) { _ in () }
}
public static func identity(size: MatrixSize) -> Self {
scalar(size: size, value: .identity)
}
public static func unit(size: MatrixSize, at: (Int, Int)) -> Self {
.init(size: size) { setEntry in
setEntry(at.0, at.1, .identity)
}
}
public static func scalar(size: MatrixSize, value: BaseRing) -> Self {
.init(size: size) { setEntry in
let r = min(size.0, size.1)
for i in 0 ..< r {
setEntry(i, i, value)
}
}
}
@inlinable
public subscript(rowRange: Range<Int>, colRange: Range<Int>) -> Self {
self.submatrix(rowRange: rowRange, colRange: colRange)
}
public var isSquare: Bool {
size.rows == size.cols
}
public var isIdentity: Bool {
isSquare && nonZeroEntries.allSatisfy { (i, j, a) in i == j && a.isIdentity }
}
public var isInvertible: Bool {
isSquare && determinant.isInvertible
}
public var inverse: Self? {
if isSquare, let dInv = determinant.inverse {
return .init(size: size) { setEntry in
((0 ..< size.rows) * (0 ..< size.cols)).forEach { (i, j) in
let a = dInv * cofactor(j, i)
setEntry(i, j, a)
}
}
} else {
return nil
}
}
public var transposed: Self {
.init(size: (size.cols, size.rows)) { setEntry in
nonZeroEntries.forEach { (i, j, a) in setEntry(j, i, a) }
}
}
public var trace: BaseRing {
assert(isSquare)
return (0 ..< size.rows).sum { i in
self[i, i]
}
}
public var determinant: BaseRing {
assert(isSquare)
if size.rows == 0 {
return .identity
} else {
return nonZeroEntries
.filter{ (i, j, a) in i == 0 }
.sum { (_, j, a) in a * cofactor(0, j) }
}
}
private func cofactor(_ i0: Int, _ j0: Int) -> BaseRing {
let ε = (-BaseRing.identity).pow(i0 + j0)
let minor = Self(size: (size.rows - 1, size.cols - 1)) { setEntry in
nonZeroEntries.forEach { (i, j, a) in
if i == i0 || j == j0 { return }
let i1 = i < i0 ? i : i - 1
let j1 = j < j0 ? j : j - 1
setEntry(i1, j1, a)
}
}
return ε * minor.determinant
}
@inlinable
public func rowVector(_ i: Int) -> Self {
submatrix(rowRange: i ..< i + 1, colRange: 0 ..< size.cols)
}
@inlinable
public func colVector(_ j: Int) -> Self {
submatrix(rowRange: 0 ..< size.rows, colRange: j ..< j + 1)
}
@inlinable
public func submatrix(rowRange: Range<Int>) -> Self {
submatrix(rowRange: rowRange, colRange: 0 ..< size.cols)
}
@inlinable
public func submatrix(colRange: Range<Int>) -> Self {
submatrix(rowRange: 0 ..< size.rows, colRange: colRange)
}
public func submatrix(rowRange: Range<Int>, colRange: Range<Int>) -> Self {
let size = (rowRange.upperBound - rowRange.lowerBound, colRange.upperBound - colRange.lowerBound)
return .init(size: size ) { setEntry in
nonZeroEntries.forEach { (i, j, a) in
if rowRange.contains(i) && colRange.contains(j) {
setEntry(i - rowRange.lowerBound, j - colRange.lowerBound, a)
}
}
}
}
public func concat(_ B: Self) -> Self {
assert(size.rows == B.size.rows)
let A = self
return .init(size: (A.size.rows, A.size.cols + B.size.cols)) { setEntry in
A.nonZeroEntries.forEach { (i, j, a) in setEntry(i, j, a) }
B.nonZeroEntries.forEach { (i, j, a) in setEntry(i, j + A.size.cols, a) }
}
}
public func stack(_ B: Self) -> Self {
assert(size.cols == B.size.cols)
let A = self
return .init(size: (A.size.rows + B.size.rows, A.size.cols)) { setEntry in
A.nonZeroEntries.forEach { (i, j, a) in setEntry(i, j, a) }
B.nonZeroEntries.forEach { (i, j, a) in setEntry(i + A.size.rows, j, a) }
}
}
@inlinable
public func permuteRows(by p: Permutation<anySize>) -> Self {
permute(rowsBy: p, colsBy: .identity(length: size.cols))
}
@inlinable
public func permuteCols(by q: Permutation<anySize>) -> Self {
permute(rowsBy: .identity(length: size.rows), colsBy: q)
}
public func permute(rowsBy p: Permutation<anySize>, colsBy q: Permutation<anySize>) -> Self {
.init(size: size) { setEntry in
nonZeroEntries.forEach{ (i, j, a) in
setEntry(p[i], q[j], a)
}
}
}
@inlinable
public static prefix func - (a: Self) -> Self {
a.mapNonZeroEntries{ (_, _, a) in -a }
}
@inlinable
public static func -(a: Self, b: Self) -> Self {
assert(a.size == b.size)
return a + (-b)
}
@inlinable
public static func * (r: BaseRing, a: Self) -> Self {
a.mapNonZeroEntries{ (_, _, a) in r * a }
}
@inlinable
public static func * (a: Self, r: BaseRing) -> Self {
a.mapNonZeroEntries{ (_, _, a) in a * r }
}
public static func ⊕ (A: Self, B: Self) -> Self {
.init(size: (A.size.rows + B.size.rows, A.size.cols + B.size.cols)) { setEntry in
A.nonZeroEntries.forEach { (i, j, a) in setEntry(i, j, a) }
B.nonZeroEntries.forEach { (i, j, a) in setEntry(i + A.size.rows, j + A.size.cols, a) }
}
}
public static func ⊗ (A: Self, B: Self) -> Self {
.init(size: (A.size.rows * B.size.rows, A.size.cols * B.size.cols)) { setEntry in
A.nonZeroEntries.forEach { (i, j, a) in
B.nonZeroEntries.forEach { (k, l, b) in
let p = i * B.size.rows + k
let q = j * B.size.cols + l
let c = a * b
setEntry(p, q, c)
}
}
}
}
public func mapNonZeroEntries(_ f: (Int, Int, BaseRing) -> BaseRing) -> Self {
.init(size: size) { setEntry in
nonZeroEntries.forEach { (i, j, a) in
let b = f(i, j, a)
if !b.isZero {
setEntry(i, j, b)
}
}
}
}
public func serialize() -> [BaseRing] {
((0 ..< size.rows) * (0 ..< size.cols)).map{ (i, j) in
self[i, j]
}
}
public var description: String {
"[" + (0 ..< size.rows).map({ i in
(0 ..< size.cols).map({ j in
"\(self[i, j])"
}).joined(separator: ", ")
}).joined(separator: "; ") + "]"
}
public var detailDescription: String {
if size.rows == 0 || size.cols == 0 {
return "[\(size)]"
} else {
return "[\t" + (0 ..< size.rows).map({ i in
(0 ..< size.cols).map({ j in
"\(self[i, j])"
}).joined(separator: ",\t")
}).joined(separator: "\n\t") + "]"
}
}
}
public protocol SparseMatrixImpl: MatrixImpl {
var numberOfNonZeros: Int { get }
var density: Double { get }
}
extension SparseMatrixImpl {
public var isZero: Bool {
numberOfNonZeros == 0
}
public var density: Double {
let N = numberOfNonZeros
return N > 0 ? Double(N) / Double(size.rows * size.cols) : 0
}
}
| cc0-1.0 | 6ffdac6b559e36eb1633c24e253e2ab5 | 30.997015 | 105 | 0.520758 | 3.763694 | false | false | false | false |
maail/MMImageLoader | MMImageLoader/ImageDetailsViewController.swift | 1 | 3454 | //
// ImageDetailsViewController.swift
// MMImageLoader
//
// Created by Mohamed Maail on 5/29/16.
// Copyright © 2016 Mohamed Maail. All rights reserved.
//
import UIKit
class ImageDetailsViewController: UIViewController {
@IBOutlet weak var PictureImageView: UIImageView!
@IBOutlet weak var AuthorLabel: UILabel!
@IBOutlet weak var ProfileImageView: UIImageView!
@IBOutlet weak var AuthorURLLabel: UILabel!
var imageDetails : UnsplashModel!
var imageLoader = MMImageLoader()
var activityIndicator = UIActivityIndicatorView()
override func viewDidLoad() {
super.viewDidLoad()
self.setDefault()
self.setStyle()
self.setData()
}
func setDefault(){
self.title = "Image Details"
//add activity indicator on load
activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50);
activityIndicator.center.x = self.view.center.x
activityIndicator.center.y = self.PictureImageView.center.y - 65
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge
self.PictureImageView.addSubview(activityIndicator)
}
func setStyle(){
self.view.backgroundColor = UIColor(red: 0.797, green: 0.797, blue: 0.797, alpha: 1)
self.ProfileImageView.layer.cornerRadius = self.ProfileImageView.frame.size.width / 2
self.PictureImageView.contentMode = .center
self.PictureImageView.layer.masksToBounds = true
self.navigationController?.navigationBar.tintColor = UIColor.gray
}
func setData(){
self.AuthorLabel.text = imageDetails.Author
self.AuthorURLLabel.text = imageDetails.AuthorURL
//show low res image first
self.activityIndicator.startAnimating()
let lowResImageURL = API.Resize(Width: 200, Height: 0, ImageID: imageDetails.ID)
imageLoader.requestImage(lowResImageURL) { (Status, Image) in
hideStatusBarActivity()
if Status{
self.PictureImageView.contentMode = .scaleAspectFill
self.PictureImageView.image = Image
}
}
//download and set image
showStatusBarActivity()
let resizeImageURL = API.Resize(Width: 1700, Height: 1200, ImageID: imageDetails.ID)
imageLoader.requestImage(resizeImageURL) { (Status, Image) in
hideStatusBarActivity()
self.activityIndicator.stopAnimating()
self.activityIndicator.isHidden = true
if Status{
self.PictureImageView.alpha = 0
UIView.animate(withDuration: 0.5, delay: 0.12, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.PictureImageView.contentMode = .scaleAspectFill
self.PictureImageView.image = Image
self.PictureImageView.alpha = 1
}, completion: nil)
}
}
}
override func viewWillDisappear(_ animated: Bool) {
self.PictureImageView.image = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 885b63474d2b4123782b2ed94f3b2607 | 35.347368 | 121 | 0.61309 | 5.420722 | false | false | false | false |
rnystrom/GitHawk | Classes/Login/LoginSplashViewController.swift | 1 | 5755 | //
// LoginSplashViewController.swift
// Freetime
//
// Created by Ryan Nystrom on 7/8/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import SafariServices
import GitHubAPI
import GitHubSession
private let loginURL = URLBuilder.github()
.add(paths: ["login", "oauth", "authorize"])
.add(item: "client_id", value: Secrets.GitHub.clientId)
.add(item: "scope", value: "user+repo+notifications")
.url!
private let callbackURLScheme = "freetime://"
protocol LoginSplashViewControllerDelegate: class {
func finishLogin(token: String, authMethod: GitHubUserSession.AuthMethod, username: String)
}
final class LoginSplashViewController: UIViewController {
enum State {
case idle
case fetchingToken
}
private var client: Client!
@IBOutlet weak var splashView: SplashView!
@IBOutlet weak var signInButton: UIButton!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
private weak var delegate: LoginSplashViewControllerDelegate?
@available(iOS 11.0, *)
private var authSession: SFAuthenticationSession? {
get {
return _authSession as? SFAuthenticationSession
}
set {
_authSession = newValue
}
}
private var _authSession: Any?
var state: State = .idle {
didSet {
let hideSpinner: Bool
switch state {
case .idle: hideSpinner = true
case .fetchingToken: hideSpinner = false
}
signInButton.isEnabled = hideSpinner
activityIndicator.isHidden = hideSpinner
let title = hideSpinner
? NSLocalizedString("Sign in with GitHub", comment: "")
: NSLocalizedString("Signing in...", comment: "")
signInButton.setTitle(title, for: .normal)
}
}
override func viewDidLoad() {
super.viewDidLoad()
state = .idle
signInButton.layer.cornerRadius = Styles.Sizes.cardCornerRadius
signInButton.addTouchEffect()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setupSplashView()
}
// MARK: Public API
static func make(client: Client, delegate: LoginSplashViewControllerDelegate) -> LoginSplashViewController? {
let controller = UIStoryboard(
name: "OauthLogin",
bundle: Bundle(for: AppDelegate.self))
.instantiateInitialViewController() as? LoginSplashViewController
controller?.client = client
controller?.delegate = delegate
controller?.modalPresentationStyle = .formSheet
return controller
}
// MARK: Private API
@IBAction func onSignInButton(_ sender: Any) {
self.authSession = SFAuthenticationSession(url: loginURL, callbackURLScheme: callbackURLScheme, completionHandler: { [weak self] (callbackUrl, error) in
guard error == nil, let callbackUrl = callbackUrl else {
switch error! {
case SFAuthenticationError.canceledLogin: break
default: self?.handleError()
}
return
}
guard let items = URLComponents(url: callbackUrl, resolvingAgainstBaseURL: false)?.queryItems,
let index = items.index(where: { $0.name == "code" }),
let code = items[index].value
else { return }
self?.state = .fetchingToken
self?.client.requestAccessToken(code: code) { [weak self] result in
switch result {
case .error:
self?.handleError()
case .success(let user):
self?.delegate?.finishLogin(token: user.token, authMethod: .oauth, username: user.username)
}
}
})
self.authSession?.start()
}
@IBAction func onPersonalAccessTokenButton(_ sender: Any) {
let alert = UIAlertController.configured(
title: NSLocalizedString("Personal Access Token", comment: ""),
message: NSLocalizedString("Sign in with a Personal Access Token with both repo and user scopes.", comment: ""),
preferredStyle: .alert
)
alert.addTextField { (textField) in
textField.placeholder = NSLocalizedString("Personal Access Token", comment: "")
}
alert.addActions([
AlertAction.cancel(),
AlertAction.login({ [weak alert, weak self] _ in
alert?.actions.forEach { $0.isEnabled = false }
self?.state = .fetchingToken
let token = alert?.textFields?.first?.text ?? ""
self?.client.send(V3VerifyPersonalAccessTokenRequest(token: token)) { result in
switch result {
case .failure:
self?.handleError()
case .success(let user):
self?.delegate?.finishLogin(token: token, authMethod: .pat, username: user.data.login)
}
}
})
])
present(alert, animated: trueUnlessReduceMotionEnabled)
}
private func handleError() {
state = .idle
let alert = UIAlertController.configured(
title: NSLocalizedString("Error", comment: ""),
message: NSLocalizedString("There was an error signing in to GitHub. Please try again.", comment: ""),
preferredStyle: .alert
)
alert.addAction(AlertAction.ok())
present(alert, animated: trueUnlessReduceMotionEnabled)
}
private func setupSplashView() {
splashView.configureView()
}
}
| mit | ac479578b126e812bdb859f1481d4159 | 32.260116 | 160 | 0.600973 | 5.347584 | false | false | false | false |
KyoheiG3/RxSwift | RxExample/RxExample/Examples/TableViewWithEditingCommands/User.swift | 14 | 744 | //
// User.swift
// RxExample
//
// Created by Krunoslav Zaher on 12/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
struct User: Equatable, CustomDebugStringConvertible {
var firstName: String
var lastName: String
var imageURL: String
init(firstName: String, lastName: String, imageURL: String) {
self.firstName = firstName
self.lastName = lastName
self.imageURL = imageURL
}
}
extension User {
var debugDescription: String {
return firstName + " " + lastName
}
}
func ==(lhs: User, rhs:User) -> Bool {
return lhs.firstName == rhs.firstName &&
lhs.lastName == rhs.lastName &&
lhs.imageURL == rhs.imageURL
} | mit | 4cb99abe4e10060d4eb4e60f72ee8196 | 20.882353 | 65 | 0.637954 | 4.245714 | false | false | false | false |
otoshimono/mamorio-reception | ReceptionKit/Models/Contacts.swift | 1 | 3745 | //
// Contacts.swift
// ReceptionKit
//
// Created by Andy Cho on 2015-04-23.
// Copyright (c) 2015 Andy Cho. All rights reserved.
//
import Foundation
import AddressBook
class ContactPhone {
var type: String
var number: String
init(type: String, number: String) {
self.type = type
self.number = number
}
func isWorkPhone() -> Bool {
return self.type == "_$!<Work>!$_"
}
func isMobilePhone() -> Bool {
return self.type == "_$!<Mobile>!$_"
}
}
class Contact {
var name: String
var phones: [ContactPhone]
var picture: UIImage?
init(name: String, phones: [ContactPhone], picture: UIImage?) {
self.name = name
self.phones = phones
self.picture = picture
}
// Check to see if the user has granted the address book permission, ask for permission if not
// Returns true if authorized, false if not
static func isAuthorized() -> Bool {
// Get the authorization if needed
let authStatus = ABAddressBookGetAuthorizationStatus()
if authStatus == .denied || authStatus == .restricted {
Logger.error("No permission to access the contacts")
} else if authStatus == .notDetermined {
ABAddressBookRequestAccessWithCompletion(nil) { (granted: Bool, error: CFError?) in
Logger.debug("Successfully got permission for the contacts")
}
}
// Need to refetch the status if it was updated
return ABAddressBookGetAuthorizationStatus() == ABAuthorizationStatus.authorized
}
// Search for all contacts that match a name
static func search(_ name: String) -> [Contact] {
guard isAuthorized() else {
return []
}
let addressBook: ABAddressBook = ABAddressBookCreateWithOptions(nil, nil).takeUnretainedValue()
let query = name as CFString
let people = ABAddressBookCopyPeopleWithName(addressBook, query).takeRetainedValue() as Array
var contacts = [Contact]()
for person: ABRecord in people {
let contactName: String = ABRecordCopyCompositeName(person).takeRetainedValue() as String
let contactPhoneNumbers = getPhoneNumbers(person, property: kABPersonPhoneProperty)
var contactPicture: UIImage?
if let contactPictureDataOptional = ABPersonCopyImageData(person) {
let contactPictureData = contactPictureDataOptional.takeRetainedValue() as Data
contactPicture = UIImage(data: contactPictureData)
}
contacts.append(Contact(name: contactName, phones: contactPhoneNumbers, picture: contactPicture))
}
return contacts
}
//
// Private functions
//
// Get a property from a ABPerson, returns an array of Strings that matches the value
private static func getPhoneNumbers(_ person: ABRecord, property: ABPropertyID) -> [ContactPhone] {
let personProperty = ABRecordCopyValue(person, property).takeRetainedValue()
guard let personPropertyValues = ABMultiValueCopyArrayOfAllValues(personProperty) else {
return []
}
var propertyValues = [ContactPhone]()
let properties = personPropertyValues.takeUnretainedValue() as NSArray
for (index, property) in properties.enumerated() {
let propertyLabel = ABMultiValueCopyLabelAtIndex(personProperty, index).takeRetainedValue() as String
if let propertyValue = property as? String {
let phone = ContactPhone(type: propertyLabel, number: propertyValue)
propertyValues.append(phone)
}
}
return propertyValues
}
}
| mit | ef9ab20bcf7a3d955ed02955131db2ac | 31.284483 | 113 | 0.645928 | 5.165517 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio | uoregon-cis-399/examples/W3Example_W17/W3Example/Source/Controller/SecondViewController.swift | 1 | 2808 | //
// SecondViewController.swift
// W3Example
//
// Created by Charles Augustine on 1/27/17.
// Copyright © 2017 Charles. All rights reserved.
//
import UIKit
class SecondViewController : UIViewController {
// MARK: IBAction
@IBAction private func buttonPressed(sender: AnyObject) {
// Only show the third view controller if the system time seconds are even
// and show an alert otherwise.
if Int(Date.timeIntervalSinceReferenceDate) % 2 == 1 {
let alertController = UIAlertController(title: "Unavailable", message: "This button only works on even seconds.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
present(alertController, animated: true)
}
else {
performSegue(withIdentifier: "ThirdViewControllerSegue", sender: sender)
}
}
// MARK: IBAction (Unwind Segue)
@IBAction private func done(sender: UIStoryboardSegue) {
// This method is a special IBAction used as a destination of an unwind segue.
// This is not how you should dismiss your modally presented view controller in
// assignment3. In assignment3 you should put the commented out line of code
// shown below in your delegate method implementation in MainViewController.
// dismiss(animated: true)
}
// MARK: View Management
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// The sender parameter provided to this method is what was passed to performSegue,
// or it is the control that triggered the segue if it was not manually triggered
if segue.identifier == "ThirdViewControllerSegue" {
// Here we can configure the view controller(s) that are about to be presented.
// This is an appropriate place to set any properties relevant for the function
// of the view controllers. A common thing to set here is the delegate of the
// view controller being presented to self.
// Note that the segue parameter has a destination property that allow us to get
// the view controller about to be presented. The properties are of type
// UIViewController so casting is necessary to access a more specific type's
// properties.
let navigationController = segue.destination as! UINavigationController
let thirdViewController = navigationController.topViewController as! ThirdViewController
// Now that we have a reference to the view controller, set its fancyBackgroundColor
// property to a color determined based on the system clock.
let color: UIColor
let timeValue = Int(Date.timeIntervalSinceReferenceDate) % 4
switch timeValue {
case 0:
color = UIColor.lightGray
case 1:
color = UIColor.cyan
default:
color = UIColor.red
}
thirdViewController.fancyBackgroundColor = color
}
else {
super.prepare(for: segue, sender: sender)
}
}
}
| gpl-3.0 | 59496389ca1d0fb3bdfb0922718da381 | 37.452055 | 140 | 0.741361 | 4.351938 | false | false | false | false |
ktakayama/SimpleRSSReader | Pods/RealmResultsController/Source/RealmResultsController.swift | 1 | 13365 | //
// RealmResultsController.swift
// redbooth-ios-sdk
//
// Created by Isaac Roldan on 4/8/15.
// Copyright © 2015 Redbooth Inc.
//
import Foundation
import UIKit
import RealmSwift
enum RRCError: ErrorType {
case InvalidKeyPath
case EmptySortDescriptors
}
public enum RealmResultsChangeType: String {
case Insert
case Delete
case Update
case Move
}
public protocol RealmResultsControllerDelegate: class {
/**
Notifies the receiver that the realm results controller is about to start processing of one or more changes due to an add, remove, move, or update.
:param: controller The realm results controller that sent the message.
*/
func willChangeResults(controller: AnyObject)
/**
Notifies the receiver that a fetched object has been changed due to an add, remove, move, or update.
:param: controller The realm results controller that sent the message.
:param: object The object in controller’s fetched results that changed.
:param: oldIndexPath The index path of the changed object (this value is the same as newIndexPath for insertions).
:param: newIndexPath The destination path for the object for insertions or moves (this value is the same as oldIndexPath for a deletion).
:param: changeType The type of change. For valid values see RealmResultsChangeType.
*/
func didChangeObject<U>(controller: AnyObject, object: U, oldIndexPath: NSIndexPath, newIndexPath: NSIndexPath, changeType: RealmResultsChangeType)
/**
Notifies the receiver of the addition or removal of a section.
:param: controller The realm results controller that sent the message.
:param: section The section that changed.
:param: index The index of the changed section.
:param: changeType The type of change (insert or delete).
*/
func didChangeSection<U>(controller: AnyObject, section: RealmSection<U>, index: Int, changeType: RealmResultsChangeType)
/**
Notifies the receiver that the realm results controller has completed processing of one or more changes due to an add, remove, move, or update.
:param: controller The realm results controller that sent the message.
*/
func didChangeResults(controller: AnyObject)
}
public class RealmResultsController<T: Object, U> : RealmResultsCacheDelegate {
public weak var delegate: RealmResultsControllerDelegate?
var _test: Bool = false
var populating: Bool = false
var observerAdded: Bool = false
var cache: RealmResultsCache<T>!
private(set) public var request: RealmRequest<T>
private(set) public var filter: (T -> Bool)?
var mapper: T -> U
var sectionKeyPath: String? = ""
var queueManager: RealmQueueManager = RealmQueueManager()
var temporaryAdded: [T] = []
var temporaryUpdated: [T] = []
var temporaryDeleted: [T] = []
/**
All results separated by the sectionKeyPath in RealmSection<U>
Warning: This is computed variable that maps all the avaliable sections using the mapper. Could be an expensive operation
Warning2: The RealmSections contained in the array do not contain objects, only its keyPath
*/
public var sections: [RealmSection<U>] {
return cache.sections.map(realmSectionMapper)
}
/// Number of sections in the RealmResultsController
public var numberOfSections: Int {
return cache.sections.count
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
observerAdded = false
}
//MARK: Initializers
/**
Create a RealmResultsController with a Request, a SectionKeypath to group the results and a mapper.
This init NEEDS a mapper, and all the Realm Models (T) will be transformed using the mapper
to objects of type (U). Done this way to avoid using Realm objects that are not thread safe.
And to decouple the Model layer of the View Layer.
If you want the RRC to return Realm objects that are thread safe, you should use the init
that doesn't require a mapper.
NOTE: If sectionKeyPath is used, it must be equal to the property used in the first SortDescriptor
of the RealmRequest. If not, RRC will throw an error.
NOTE2: Realm does not support sorting by KeyPaths, so you must only use properties of the model
you want to fetch and not KeyPath to any relationship
NOTE3: The RealmRequest needs at least one SortDescriptor
- param: request Request to fetch objects
- param: sectionKeyPath KeyPath to group the results by sections
- param: mapper Mapper to map the results.
- returns: Self
*/
public init(request: RealmRequest<T>, sectionKeyPath: String? ,mapper: T -> U, filter: (T -> Bool)? = nil) throws {
self.request = request
self.mapper = mapper
self.sectionKeyPath = sectionKeyPath
self.cache = RealmResultsCache<T>(request: request, sectionKeyPath: sectionKeyPath)
self.filter = filter
if sortDescriptorsAreEmpty(request.sortDescriptors) {
throw RRCError.EmptySortDescriptors
}
if !keyPathIsValid(sectionKeyPath, sorts: request.sortDescriptors) {
throw RRCError.InvalidKeyPath
}
self.cache?.delegate = self
}
/**
This INIT does not require a mapper, instead will use an empty mapper.
If you plan to use this INIT, you should create the RRC specifiyng T = U
Ex: let RRC = RealmResultsController<TaskModel, TaskModel>....
All objects sent to the delegate of the RRC will be of the model type but
they will be "mirrors", i.e. they don't belong to any Realm DB.
NOTE: If sectionKeyPath is used, it must be equal to the property used in the first SortDescriptor
of the RealmRequest. If not, RRC will throw an error
NOTE2: The RealmRequest needs at least one SortDescriptor
- param: request Request to fetch objects
- param: sectionKeyPath keyPath to group the results of the request
- returns: self
*/
public convenience init(request: RealmRequest<T>, sectionKeyPath: String?) throws {
try self.init(request: request, sectionKeyPath: sectionKeyPath, mapper: {$0 as! U})
}
internal convenience init(forTESTRequest request: RealmRequest<T>, sectionKeyPath: String?, mapper: (T)->(U)) throws {
try self.init(request: request, sectionKeyPath: sectionKeyPath, mapper: mapper)
self._test = true
}
/**
Update the filter currently used in the RRC by a new one.
This func resets completetly the RRC, so:
- It will force the RRC to clean all its cache and refetch all the objects.
- You MUST do a reloadData() in your UITableView after calling this method.
- Not refreshing the table could cause a crash because the indexes changed.
:param: newFilter A Filter closure applied to T: Object
*/
public func updateFilter(newFilter: T -> Bool) {
filter = newFilter
performFetch()
}
//MARK: Fetch
/**
Fetches the initial data for the RealmResultsController
Atention: Must be called after the initialization and should be called only once
*/
public func performFetch() {
populating = true
var objects = self.request.execute().toArray().map{ $0.getMirror() }
if let filter = filter {
objects = objects.filter(filter)
}
self.cache.reset(objects)
populating = false
if !observerAdded { self.addNotificationObservers() }
}
//MARK: Helpers
/**
Returns the number of objects at a given section index
- param: sectionIndex Int
- returns: the objects count at the sectionIndex
*/
public func numberOfObjectsAt(sectionIndex: Int) -> Int {
if cache.sections.count == 0 { return 0 }
return cache.sections[sectionIndex].objects.count
}
/**
Returns the mapped object at a given NSIndexPath
- param: indexPath IndexPath for the desired object
- returns: the object as U (mapped)
*/
public func objectAt(indexPath: NSIndexPath) -> U {
let object = cache.sections[indexPath.section].objects[indexPath.row] as! T
return self.mapper(object)
}
private func sortDescriptorsAreEmpty(sorts: [SortDescriptor]) -> Bool {
return sorts.first == nil
}
// At this point, we are sure sorts.first always has a SortDescriptor
private func keyPathIsValid(keyPath: String?, sorts: [SortDescriptor]) -> Bool {
if keyPath == nil { return true }
return keyPath == sorts.first!.property
}
private func realmSectionMapper<S>(section: Section<S>) -> RealmSection<U> {
return RealmSection<U>(objects: nil, keyPath: section.keyPath)
}
//MARK: Cache delegate
func didInsert<T: Object>(object: T, indexPath: NSIndexPath) {
Threading.executeOnMainThread {
self.delegate?.didChangeObject(self, object: object, oldIndexPath: indexPath, newIndexPath: indexPath, changeType: .Insert)
}
}
func didUpdate<T: Object>(object: T, oldIndexPath: NSIndexPath, newIndexPath: NSIndexPath, changeType: RealmResultsChangeType) {
Threading.executeOnMainThread {
self.delegate?.didChangeObject(self, object: object, oldIndexPath: oldIndexPath, newIndexPath: newIndexPath, changeType: changeType)
}
}
func didDelete<T: Object>(object: T, indexPath: NSIndexPath) {
Threading.executeOnMainThread {
self.delegate?.didChangeObject(self, object: object, oldIndexPath: indexPath, newIndexPath: indexPath, changeType: .Delete)
}
}
func didInsertSection<T : Object>(section: Section<T>, index: Int) {
if populating { return }
Threading.executeOnMainThread {
self.delegate?.didChangeSection(self, section: self.realmSectionMapper(section), index: index, changeType: .Insert)
}
}
func didDeleteSection<T : Object>(section: Section<T>, index: Int) {
Threading.executeOnMainThread {
self.delegate?.didChangeSection(self, section: self.realmSectionMapper(section), index: index, changeType: .Delete)
}
}
//MARK: Realm Notifications
private func addNotificationObservers() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveRealmChanges:", name: "realmChanges", object: nil)
observerAdded = true
}
@objc func didReceiveRealmChanges(notification: NSNotification) {
guard case let notificationObject as [String : [RealmChange]] = notification.object
where notificationObject.keys.first == request.realm.path,
let objects = notificationObject[self.request.realm.path] else { return }
queueManager.addOperation {
self.refetchObjects(objects)
self.finishWriteTransaction()
}
}
private func refetchObjects(objects: [RealmChange]) {
for object in objects {
guard String(object.type) == String(T.self), let mirrorObject = object.mirror as? T else { continue }
if object.action == RealmAction.Delete {
temporaryDeleted.append(mirrorObject)
continue
}
var passesFilter = true
var passesPredicate = true
Threading.executeOnMainThread(true) {
passesPredicate = self.request.predicate.evaluateWithObject(mirrorObject)
if let filter = self.filter {
passesFilter = filter(mirrorObject)
}
}
if object.action == RealmAction.Create && passesPredicate && passesFilter {
temporaryAdded.append(mirrorObject)
}
else if object.action == RealmAction.Update {
if passesFilter && passesPredicate {
temporaryUpdated.append(mirrorObject)
}
else {
temporaryDeleted.append(mirrorObject)
}
}
}
}
func pendingChanges() -> Bool{
return temporaryAdded.count > 0 ||
temporaryDeleted.count > 0 ||
temporaryUpdated.count > 0
}
private func finishWriteTransaction() {
if !pendingChanges() { return }
Threading.executeOnMainThread(true) {
self.delegate?.willChangeResults(self)
}
var objectsToMove: [T] = []
var objectsToUpdate: [T] = []
for object in temporaryUpdated {
cache.updateType(object) == .Move ? objectsToMove.append(object) : objectsToUpdate.append(object)
}
temporaryDeleted.appendContentsOf(objectsToMove)
temporaryAdded.appendContentsOf(objectsToMove)
cache.update(objectsToUpdate)
cache.delete(temporaryDeleted)
cache.insert(temporaryAdded)
temporaryAdded.removeAll()
temporaryDeleted.removeAll()
temporaryUpdated.removeAll()
Threading.executeOnMainThread(true) {
self.delegate?.didChangeResults(self)
}
}
}
| mit | d95573901a4fcb8a0cd6dba198f691e6 | 37.068376 | 151 | 0.660904 | 5.004494 | false | false | false | false |
gewill/Feeyue | Feeyue/Main/Weibo/Views/StatusFooterView.swift | 1 | 6383 | //
// StatusFooterView.swift
// Feeyue
//
// Created by Will on 3/1/16.
// Copyright © 2016 gewill.org. All rights reserved.
//
import UIKit
protocol StatusFooterViewDelegate {
func numberOfCommentCount(_ footerView: StatusFooterView) -> Int
func numberOfRetweetCount(_ footerView: StatusFooterView) -> Int
func footerView(_ footerView: StatusFooterView, didClickRetweenButton: UIButton)
func footerView(_ footerView: StatusFooterView, didClickCommentsButton: UIButton)
}
class StatusFooterView: UITableViewHeaderFooterView {
var delegate: StatusFooterViewDelegate?
var retweetCount = 0
var commentsCount = 0
var retweetButton = UIButton(type: .system)
var commentsButton = UIButton(type: .system)
var buttonUnderline = UIView()
var toRetweetbuttonUnderlineLeadingConstraint: NSLayoutConstraint!
var toRetweetbuttonUnderlineTrailingConstraint: NSLayoutConstraint!
var toCommentsbuttonUnderlineLeadingConstraint: NSLayoutConstraint!
var toCommentsbuttonUnderlineTrailingConstraint: NSLayoutConstraint!
fileprivate let commonGargin: CGFloat = 8
override func draw(_ rect: CGRect) {
self.contentView.backgroundColor = UIColor.white
retweetButton.titleLabel!.font = UIFont.boldSystemFont(ofSize: 14)
commentsButton.titleLabel!.font = UIFont.boldSystemFont(ofSize: 14)
retweetButton.contentHorizontalAlignment = .left
commentsButton.contentHorizontalAlignment = .left
buttonUnderline.backgroundColor = SystemTintColor
let separator = UIView()
separator.backgroundColor = SeparatorColor
self.contentView.addSubview(separator)
self.contentView.addSubview(retweetButton)
self.contentView.addSubview(commentsButton)
self.contentView.addSubview(buttonUnderline)
retweetButton.translatesAutoresizingMaskIntoConstraints = false
commentsButton.translatesAutoresizingMaskIntoConstraints = false
buttonUnderline.translatesAutoresizingMaskIntoConstraints = false
separator.translatesAutoresizingMaskIntoConstraints = false
toCommentsbuttonUnderlineLeadingConstraint = NSLayoutConstraint(item: buttonUnderline, attribute: .leading, relatedBy: .equal, toItem: commentsButton, attribute: .leading, multiplier: 1, constant: 0)
toCommentsbuttonUnderlineTrailingConstraint = NSLayoutConstraint(item: buttonUnderline, attribute: .trailing, relatedBy: .equal, toItem: commentsButton, attribute: .trailing, multiplier: 1, constant: 0)
toRetweetbuttonUnderlineLeadingConstraint = NSLayoutConstraint(item: buttonUnderline, attribute: .leading, relatedBy: .equal, toItem: retweetButton, attribute: .leading, multiplier: 1, constant: 0)
toRetweetbuttonUnderlineTrailingConstraint = NSLayoutConstraint(item: buttonUnderline, attribute: .trailing, relatedBy: .equal, toItem: retweetButton, attribute: .trailing, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([
retweetButton.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: commonGargin),
retweetButton.trailingAnchor.constraint(equalTo: commentsButton.leadingAnchor, constant: -commonGargin),
retweetButton.centerYAnchor.constraint(equalTo: self.centerYAnchor),
commentsButton.centerYAnchor.constraint(equalTo: self.centerYAnchor),
buttonUnderline.heightAnchor.constraint(equalToConstant: 3),
buttonUnderline.bottomAnchor.constraint(equalTo: self.bottomAnchor),
separator.bottomAnchor.constraint(equalTo: self.bottomAnchor),
separator.leadingAnchor.constraint(equalTo: self.leadingAnchor),
separator.trailingAnchor.constraint(equalTo: self.trailingAnchor),
separator.heightAnchor.constraint(equalToConstant: 1)
])
self.underlineAlignToCommentsButton()
// self.ChangeRetweetCountAndCommentCount()
retweetButton.addTarget(self, action: #selector(StatusFooterView.retweetButtonClick), for: .touchDown)
commentsButton.addTarget(self, action: #selector(StatusFooterView.commentsButtonClick), for: .touchDown)
}
override func layoutSubviews() {
super.layoutSubviews()
self.ChangeRetweetCountAndCommentCount()
}
// MARK: - response methods
@objc func retweetButtonClick() {
self.underlineAlignToRetweenButton()
delegate?.footerView(self, didClickRetweenButton: retweetButton)
}
@objc func commentsButtonClick() {
self.underlineAlignToCommentsButton()
delegate?.footerView(self, didClickCommentsButton: commentsButton)
}
// MARK: - private methods
func ChangeRetweetCountAndCommentCount() {
if let count = delegate?.numberOfRetweetCount(self) {
retweetCount = count
}
if let count = delegate?.numberOfCommentCount(self) {
commentsCount = count
}
retweetButton.setTitle("Retweet: \(retweetCount)", for: UIControl.State())
commentsButton.setTitle("Comment: \(commentsCount)", for: UIControl.State())
}
fileprivate func underlineAlignToRetweenButton() {
self.retweetButton.setTitleColor(SystemTintColor, for: UIControl.State())
self.commentsButton.setTitleColor(HalfSystemTintColor, for: UIControl.State())
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.toRetweetbuttonUnderlineLeadingConstraint.isActive = true
self.toRetweetbuttonUnderlineTrailingConstraint.isActive = true
self.toCommentsbuttonUnderlineLeadingConstraint.isActive = false
self.toCommentsbuttonUnderlineTrailingConstraint.isActive = false
})
}
fileprivate func underlineAlignToCommentsButton() {
self.commentsButton.setTitleColor(SystemTintColor, for: UIControl.State())
self.retweetButton.setTitleColor(HalfSystemTintColor, for: UIControl.State())
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.toRetweetbuttonUnderlineLeadingConstraint.isActive = false
self.toRetweetbuttonUnderlineTrailingConstraint.isActive = false
self.toCommentsbuttonUnderlineLeadingConstraint.isActive = true
self.toCommentsbuttonUnderlineTrailingConstraint.isActive = true
})
}
}
| mit | a6c3b0b15798a1bcf6c94d3955e23775 | 39.649682 | 210 | 0.736446 | 5.759928 | false | false | false | false |
dmitryelj/SDR-Frequency-Plotter-OSX | FrequencyPlotter/ViewControllerSettings.swift | 1 | 1564 | //
// ViewControllerSettings.swift
// SpectrumGraph
//
// Created by Dmitrii Eliuseev on 21/03/16.
// Copyright © 2016 Dmitrii Eliuseev. All rights reserved.
// dmitryelj@gmail.com
import Cocoa
class ViewControllerSettings: NSViewController {
@IBOutlet weak var labelGain1: NSTextField!
@IBOutlet weak var sliderGain1: NSSlider!
@IBOutlet weak var labelGain2: NSTextField!
@IBOutlet weak var sliderGain2: NSSlider!
var titleGain1:String = ""
var valueGain1:CGFloat = 0
var valueGain1Low:CGFloat = 0
var valueGain1High:CGFloat = 100
var titleGain2:String = ""
var valueGain2:CGFloat = 0
var valueGain2Low:CGFloat = 0
var valueGain2High:CGFloat = 100
var onDidChangedGain1: ((CGFloat) -> Void)?
var onDidChangedGain2: ((CGFloat) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
labelGain1.stringValue = titleGain1
sliderGain1.minValue = Double(valueGain1Low)
sliderGain1.maxValue = Double(valueGain1High)
sliderGain1.floatValue = Float(valueGain1)
labelGain2.stringValue = titleGain2
sliderGain2.minValue = Double(valueGain2Low)
sliderGain2.maxValue = Double(valueGain2High)
sliderGain2.floatValue = Float(valueGain2)
}
@IBAction func onSliderGain1ValueChanged(sender: AnyObject) {
let val = CGFloat(sliderGain1.floatValue)
if let ch = onDidChangedGain1 {
ch(val)
}
}
@IBAction func onSliderGain2ValueChanged(sender: AnyObject) {
let val = CGFloat(sliderGain2.floatValue)
if let ch = onDidChangedGain2 {
ch(val)
}
}
}
| gpl-3.0 | ca0dcc03f924bcb234e87af5ec7da5c8 | 27.944444 | 63 | 0.722329 | 3.849754 | false | false | false | false |
tardieu/swift | test/Generics/same_type_constraints.swift | 2 | 7196 | // RUN: %target-typecheck-verify-swift
protocol Fooable {
associatedtype Foo
var foo: Foo { get }
}
protocol Barrable {
associatedtype Bar: Fooable
var bar: Bar { get }
}
struct X {}
struct Y: Fooable {
typealias Foo = X
var foo: X { return X() }
}
struct Z: Barrable {
typealias Bar = Y
var bar: Y { return Y() }
}
protocol TestSameTypeRequirement {
func foo<F1: Fooable>(_ f: F1) where F1.Foo == X
}
struct SatisfySameTypeRequirement : TestSameTypeRequirement {
func foo<F2: Fooable>(_ f: F2) where F2.Foo == X {}
}
protocol TestSameTypeAssocTypeRequirement {
associatedtype Assoc
func foo<F1: Fooable>(_ f: F1) where F1.Foo == Assoc
}
struct SatisfySameTypeAssocTypeRequirement : TestSameTypeAssocTypeRequirement {
typealias Assoc = X
func foo<F2: Fooable>(_ f: F2) where F2.Foo == X {}
}
struct SatisfySameTypeAssocTypeRequirementDependent<T>
: TestSameTypeAssocTypeRequirement
{
typealias Assoc = T
func foo<F3: Fooable>(_ f: F3) where F3.Foo == T {}
}
// Pulled in from old standard library to keep the following test
// (LazySequenceOf) valid.
public struct GeneratorOf<T> : IteratorProtocol, Sequence {
/// Construct an instance whose `next()` method calls `nextElement`.
public init(_ nextElement: @escaping () -> T?) {
self._next = nextElement
}
/// Construct an instance whose `next()` method pulls its results
/// from `base`.
public init<I : IteratorProtocol>(_ base: I) where I.Element == T {
var base = base
self._next = { base.next() }
}
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`.
public mutating func next() -> T? {
return _next()
}
/// `GeneratorOf<T>` is also a `Sequence`, so it `generate`\ s
/// a copy of itself
public func makeIterator() -> GeneratorOf {
return self
}
let _next: () -> T?
}
// rdar://problem/19009056
public struct LazySequenceOf<S : Sequence, A> : Sequence where S.Iterator.Element == A {
public func makeIterator() -> GeneratorOf<A> {
return GeneratorOf<A>({ return nil })
}
public subscript(i : A) -> A { return i }
}
public func iterate<A>(_ f : @escaping (A) -> A) -> (_ x : A) -> LazySequenceOf<Iterate<A>, A>? {
return { x in nil }
}
public final class Iterate<A> : Sequence {
typealias IteratorProtocol = IterateGenerator<A>
public func makeIterator() -> IterateGenerator<A> {
return IterateGenerator<A>()
}
}
public final class IterateGenerator<A> : IteratorProtocol {
public func next() -> A? {
return nil
}
}
// rdar://problem/18475138
public protocol Observable : class {
associatedtype Output
func addObserver(_ obj : @escaping (Output) -> Void)
}
public protocol Bindable : class {
associatedtype Input
func foo()
}
class SideEffect<In> : Bindable {
typealias Input = In
func foo() { }
}
struct Composed<Left: Bindable, Right: Observable> where Left.Input == Right.Output {}
infix operator <- : AssignmentPrecedence
func <- <
Right : Observable
>(lhs: @escaping (Right.Output) -> Void, rhs: Right) -> Composed<SideEffect<Right>, Right>?
{
return nil
}
// rdar://problem/17855378
struct Pair<T, U> {
typealias Type_ = (T, U)
}
protocol Seq {
associatedtype Element
func zip<OtherSeq: Seq, ResultSeq: Seq> (_ otherSeq: OtherSeq) -> ResultSeq
where ResultSeq.Element == Pair<Element, OtherSeq.Element>.Type_
}
// rdar://problem/18435371
extension Dictionary {
func multiSubscript<S : Sequence>(_ seq: S) -> [Value?] where S.Iterator.Element == Key {
var result = [Value?]()
for seqElt in seq {
result.append(self[seqElt])
}
return result
}
}
// rdar://problem/19245317
protocol P {
associatedtype T: P // expected-error{{type may not reference itself as a requirement}}
}
struct S<A: P> {
init<Q: P>(_ q: Q) where Q.T == A {}
}
// rdar://problem/19371678
protocol Food { }
class Grass : Food { }
protocol Animal {
associatedtype EdibleFood:Food
func eat(_ f:EdibleFood)
}
class Cow : Animal {
func eat(_ f: Grass) { }
}
struct SpecificAnimal<F:Food> : Animal {
typealias EdibleFood=F
let _eat:(_ f:F) -> ()
init<A:Animal>(_ selfie:A) where A.EdibleFood == F {
_eat = { selfie.eat($0) }
}
func eat(_ f:F) {
_eat(f)
}
}
// rdar://problem/18803556
struct Something<T> {
var items: [T] = []
}
extension Something {
init<S : Sequence>(_ s: S) where S.Iterator.Element == T {
for item in s {
items.append(item)
}
}
}
// rdar://problem/18120419
func TTGenWrap<T, I : IteratorProtocol>(_ iterator: I) where I.Element == (T,T)
{
var iterator = iterator
_ = iterator.next()
}
func IntIntGenWrap<I : IteratorProtocol>(_ iterator: I) where I.Element == (Int,Int)
{
var iterator = iterator
_ = iterator.next()
}
func GGWrap<I1 : IteratorProtocol, I2 : IteratorProtocol>(_ i1: I1, _ i2: I2) where I1.Element == I2.Element
{
var i1 = i1
var i2 = i2
_ = i1.next()
_ = i2.next()
}
func testSameTypeTuple(_ a: Array<(Int,Int)>, s: ArraySlice<(Int,Int)>) {
GGWrap(a.makeIterator(), s.makeIterator())
TTGenWrap(a.makeIterator())
IntIntGenWrap(s.makeIterator())
}
// rdar://problem/20256475
protocol FooProtocol {
associatedtype Element
func getElement() -> Element
}
protocol Bar {
associatedtype Foo : FooProtocol
func getFoo() -> Foo
mutating func extend<C : FooProtocol>(_ elements: C)
where C.Element == Foo.Element
}
// rdar://problem/21620908
protocol P1 { }
protocol P2Base { }
protocol P2 : P2Base {
associatedtype Q : P1
func getQ() -> Q
}
struct XP1<T : P2Base> : P1 {
func wibble() { }
}
func sameTypeParameterizedConcrete<C : P2>(_ c: C) where C.Q == XP1<C> {
c.getQ().wibble()
}
// rdar://problem/21621421
protocol P3 {
associatedtype AssocP3 : P1
}
protocol P4 {
associatedtype AssocP4 : P3
}
struct X1 : P1 { }
struct X3 : P3 {
typealias AssocP3 = X1
}
func foo<C : P4>(_ c: C) where C.AssocP4 == X3 {}
struct X4 : P4 {
typealias AssocP4 = X3
}
func testFoo(_ x3: X4) {
foo(x3)
}
// rdar://problem/21625478
struct X6<T> { }
protocol P6 { }
protocol P7 {
associatedtype AssocP7
}
protocol P8 {
associatedtype AssocP8 : P7
associatedtype AssocOther
}
func testP8<C : P8>(_ c: C) where C.AssocOther == X6<C.AssocP8.AssocP7> {}
// setGenericSignature() was getting called twice here
struct Ghost<T> {}
protocol Timewarp {
associatedtype Wormhole
}
struct Teleporter<A, B> where A : Timewarp, A.Wormhole == Ghost<B> {}
struct Beam {}
struct EventHorizon : Timewarp {
typealias Wormhole = Ghost<Beam>
}
func activate<T>(_ t: T) {}
activate(Teleporter<EventHorizon, Beam>())
// rdar://problem/29288428
class C {}
protocol P9 {
associatedtype A
}
struct X7<T: P9> where T.A : C { }
extension X7 where T.A == Int { } // expected-error {{'T.A' requires that 'Int' inherit from 'C'}}
struct X8<T: C> { }
extension X8 where T == Int { } // expected-error {{'T' requires that 'Int' inherit from 'C'}}
| apache-2.0 | 5988f080e1a8cbc6c1a95c969f881520 | 20.54491 | 108 | 0.647304 | 3.345421 | false | false | false | false |
hejunbinlan/Carlos | Tests/CacheRequestTests.swift | 2 | 13478 | import Foundation
import Quick
import Nimble
import Carlos
class CacheRequestTests: QuickSpec {
override func spec() {
describe("CacheRequest") {
var request: CacheRequest<String>!
var successSentinels: [String?]!
var failureSentinels: [NSError?]!
context("when initialized with the empty initializer") {
beforeEach {
request = CacheRequest<String>()
successSentinels = [nil, nil, nil]
failureSentinels = [nil, nil, nil]
}
context("when calling onSuccess") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onSuccess({ result in
successSentinels[idx] = result
})
}
}
it("should not immediately call the closures") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
context("when calling succeed") {
let value = "success value"
beforeEach {
request.succeed(value)
}
it("should call the closures") {
expect(successSentinels).to(allPass({ $0! == value }))
}
context("when calling onSuccess again") {
var subsequentSuccessSentinel: String?
beforeEach {
request.onSuccess({ result in
subsequentSuccessSentinel = result
})
}
it("should immediately call the closures") {
expect(subsequentSuccessSentinel).to(equal(value))
}
}
}
context("when calling fail") {
beforeEach {
request.fail(nil)
}
it("should not call any success closure") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
}
}
context("when calling onFailure") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onFailure({ error in
failureSentinels[idx] = error
})
}
}
it("should not immediately call the closures") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(failureSentinels.count))
}
context("when calling fail") {
let errorCode = -1100
beforeEach {
request.fail(NSError(domain: "test", code: errorCode, userInfo: nil))
}
it("should call the closures") {
expect(failureSentinels).to(allPass({ $0!?.code == errorCode }))
}
context("when calling onFailure again") {
var subsequentFailureSentinel: NSError?
beforeEach {
request.onFailure({ error in
subsequentFailureSentinel = error
})
}
it("should immediately call the closures") {
expect(subsequentFailureSentinel?.code).to(equal(errorCode))
}
}
}
context("when calling succeed") {
beforeEach {
request.succeed("test")
}
it("should not call any closure") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(failureSentinels.count))
}
}
}
context("when calling onCompletion") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onCompletion({ value, error in
failureSentinels[idx] = error
successSentinels[idx] = value
})
}
}
it("should not immediately call the closures passing an error") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(failureSentinels.count))
}
it("should not immediately call the closures passing a value") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
context("when calling fail") {
let errorCode = -1100
beforeEach {
request.fail(NSError(domain: "test", code: errorCode, userInfo: nil))
}
it("should call the closures passing an error") {
expect(failureSentinels).to(allPass({ $0!?.code == errorCode }))
}
it("should not call the closures passing a value") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
context("when calling onCompletion again") {
var subsequentFailureSentinel: NSError?
var subsequentSuccessSentinel: String?
beforeEach {
request.onCompletion({ value, error in
subsequentSuccessSentinel = value
subsequentFailureSentinel = error
})
}
it("should immediately call the closure passing an error") {
expect(subsequentFailureSentinel?.code).to(equal(errorCode))
}
it("should not immediately call the closure passing a value") {
expect(subsequentSuccessSentinel).to(beNil())
}
}
}
context("when calling succeed") {
let value = "success value"
beforeEach {
request.succeed(value)
}
it("should call the closures passing a value") {
expect(successSentinels).to(allPass({ $0! == value }))
}
it("should not call the closures passing an error") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(failureSentinels.count))
}
context("when calling onCompletion again") {
var subsequentSuccessSentinel: String?
var subsequentFailureSentinel: NSError?
beforeEach {
request.onCompletion({ result, error in
subsequentSuccessSentinel = result
subsequentFailureSentinel = error
})
}
it("should immediately call the closure passing a value") {
expect(subsequentSuccessSentinel).to(equal(value))
}
it("should not immediately call the closure passing an error") {
expect(subsequentFailureSentinel).to(beNil())
}
}
}
}
}
context("when initialized with a value") {
let value = "this is a sync success value"
beforeEach {
request = CacheRequest(value: value)
successSentinels = [nil, nil, nil]
failureSentinels = [nil, nil, nil]
}
context("when calling onSuccess") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onSuccess({ result in
successSentinels[idx] = result
})
}
}
it("should immediately call the closures") {
expect(successSentinels.filter({ $0 != nil }).count).to(equal(successSentinels.count))
}
it("should pass the right value") {
expect(successSentinels).to(allPass({ $0! == value }))
}
}
context("when calling onFailure") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onFailure({ error in
failureSentinels[idx] = error
})
}
}
it("should not call the closures") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(failureSentinels.count))
}
}
context("when calling onCompletion") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onCompletion({ value, error in
successSentinels[idx] = value
failureSentinels[idx] = error
})
}
}
it("should not call the closures passing an error") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(failureSentinels.count))
}
it("should call the closures passing a value") {
expect(successSentinels).to(allPass({ $0! == value }))
}
}
}
context("when initialized with an error") {
context("when the error is not nil") {
let error = NSError(domain: "Test", code: 10, userInfo: nil)
beforeEach {
request = CacheRequest<String>(error: error)
successSentinels = [nil, nil, nil]
failureSentinels = [nil, nil, nil]
}
context("when calling onSuccess") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onSuccess({ result in
successSentinels[idx] = result
})
}
}
it("should not call the closures") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
}
context("when calling onFailure") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onFailure({ error in
failureSentinels[idx] = error
})
}
}
it("should immediately call the closures") {
expect(failureSentinels.filter({ $0 != nil }).count).to(equal(failureSentinels.count))
}
it("should pass the right error") {
expect(failureSentinels).to(allPass({ $0!!.code == error.code }))
}
}
context("when calling onCompletion") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onCompletion({ value, error in
successSentinels[idx] = value
failureSentinels[idx] = error
})
}
}
it("should immediately call the closures") {
expect(failureSentinels.filter({ $0 != nil }).count).to(equal(failureSentinels.count))
}
it("should pass the right error") {
expect(failureSentinels).to(allPass({ $0!!.code == error.code }))
}
it("should not pass a value") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
}
}
context("when the error is nil") {
var failureSentinels: [Bool?]!
beforeEach {
request = CacheRequest<String>(error: nil)
successSentinels = [nil, nil, nil]
failureSentinels = [nil, nil, nil]
}
context("when calling onSuccess") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onSuccess({ result in
successSentinels[idx] = result
})
}
}
it("should not call the closures") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
}
context("when calling onFailure") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onFailure({ error in
failureSentinels[idx] = true
})
}
}
it("should immediately call the closures") {
expect(failureSentinels.filter({ $0 != nil }).count).to(equal(failureSentinels.count))
}
}
context("when calling onCompletion") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onCompletion({ value, error in
failureSentinels[idx] = true
successSentinels[idx] = value
})
}
}
it("should immediately call the closures") {
expect(failureSentinels.filter({ $0 != nil }).count).to(equal(failureSentinels.count))
}
it("should not pass a value") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
}
}
}
}
}
} | mit | 3730aa428a387e7114c86e7fe0981734 | 32.529851 | 100 | 0.475441 | 5.97694 | false | false | false | false |
twtstudio/WePeiYang-iOS | WePeiYang/Bicycle/Model/NotificationList.swift | 1 | 1889 | //
// NotificationList.swift
// WePeiYang
//
// Created by JinHongxu on 16/8/10.
// Copyright © 2016年 Qin Yubo. All rights reserved.
//
import Foundation
class NotificationList: NSObject {
var list: Array<NotificationItem> = []
var newestTimeStamp: Int = 0
var didGetNewNotification: Bool = false
static let sharedInstance = NotificationList()
private override init() {}
func getList(doSomething: () -> ()) {
list.removeAll()
let manager = AFHTTPSessionManager()
manager.GET(BicycleAPIs.notificationURL, parameters: nil, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) in
let dic = responseObject as? NSDictionary
//log.obj(dic!)/
guard dic?.objectForKey("errno") as? NSNumber == 0 else {
MsgDisplay.showErrorMsg(dic?.objectForKey("errmsg") as? String)
return
}
guard let foo = dic?.objectForKey("data") as? NSArray else {
MsgDisplay.showErrorMsg("获取信息失败")
return
}
if foo.count > 0 {
let fooTimeStamp = Int(foo[0].objectForKey("timestamp") as! String)!
if fooTimeStamp > self.newestTimeStamp {
self.didGetNewNotification = true
self.newestTimeStamp = fooTimeStamp
}
}
for dict in foo {
self.list.append(NotificationItem(dict: dict as! NSDictionary))
}
doSomething()
}, failure: { (task: NSURLSessionDataTask?, error: NSError) in
MsgDisplay.showErrorMsg("网络错误,请稍后再试")
print("error: \(error)")
})
}
} | mit | 3ad679b274ff92c5099cb2db655068bb | 29.916667 | 136 | 0.532362 | 5.327586 | false | false | false | false |
bvic23/VinceRP | VinceRPTests/Common/Util/WeakReferenceTests.swift | 1 | 2136 | //
// Created by Viktor Belenyesi on 20/04/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
@testable import VinceRP
import Quick
import Nimble
let v = NSObject()
class WeakReferenceSpec: QuickSpec {
override func spec() {
context("value") {
it("does not hold it's value") {
// when
let wr = WeakReference(NSObject())
// then
expect(wr.value).to(beNil())
}
it("keeps it's value if it got hold outside") {
// when
let wr = WeakReference(v)
// then
expect(wr.value) == v
}
}
describe("hash") {
it("'s hash is not 0 if reference is valid") {
// when
let wr = WeakReference(v)
// then
expect(wr.hashValue) != 0
}
it("'s hash is 0 if reference is gone") {
// when
let wr = WeakReference(NSObject())
// then
expect(wr.hashValue) == 0
}
}
describe("equality") {
it("holds equality for same instances") {
// when
let w1 = WeakReference(v)
let w2 = WeakReference(v)
// then
expect(w1) == w2
}
it("holds equality for nil reference") {
// when
let w1 = WeakReference(NSObject())
let w2 = WeakReference(NSObject())
// then
expect(w1) == w2
expect(w1.hashValue) == 0
}
it("holds equality the same hasValue") {
// when
let w1 = WeakReference(Foo())
let w2 = WeakReference(Foo())
// then
expect(w1) == w2
}
}
}
}
| mit | 101015fa887ccc98f8e3d9c98c76a827 | 22.472527 | 60 | 0.383895 | 5.407595 | false | false | false | false |
tinrobots/Mechanica | Sources/StandardLibrary/String+Utils.swift | 1 | 15851 | extension String {
/// Creates a string containing the given 'StaticString'.
///
/// - Parameter staticString: The 'StaticString' to convert to a string.
public init(staticString: StaticString) {
self = staticString.withUTF8Buffer {
String(decoding: $0, as: UTF8.self)
}
}
/// **Mechanica**
///
/// Returns a `new` string containing the first character of the `String`.
public var first: String {
let first = self[..<index(after: startIndex)]
return String(first)
}
/// **Mechanica**
///
/// Checks if all of the characters in a string are all the same.
public var isHomogeneous: Bool {
for char in dropFirst() where char != first {
return false
}
return true
}
/// **Mechanica**
///
/// Returns true if all the characters are lowercased.
public var isLowercase: Bool {
return self == lowercased()
}
/// **Mechanica**
///
/// Returns true, if all characters are uppercased. Otherwise, false.
public var isUppercase: Bool {
return self == uppercased()
}
/// **Mechanica**
///
/// Returns a `new` string containing the last character of the `String`.
public var last: String {
let last = self[index(before: endIndex)...]
return String(last)
}
/// **Mechanica**
///
/// Returns the length of the `String`.
public var length: Int {
return count
}
/// **Mechanica**
///
/// Returns a `new` String with the center-padded version of `self` if it's shorter than `length` using a `token`. Padding characters are truncated if they can't be evenly divided by length.
///
/// Example 1:
///
/// let string = "Hello World"
/// string.padding(length: 15) -> " Hello World "
///
/// Example 2:
///
/// let string = "Hello World"
/// string.padding(length: 15, withToken: "*") -> "**Hello World**"
///
/// - Parameters:
/// - length: The final length of your string. If the provided length is less than or equal to the original string, the original string is returned.
/// - token: The string used to pad the String (defaults to a white space).
/// - Returns: The padded copy of the string.
/// - Note: If the the sum-total of characters added is odd, the left side of the string will have one less instance of the token.
public func padding(length: Int, with token: String = " ") -> String {
guard count < length else { return self }
let padLength = length - count
let halfPadLength = Double(padLength) / 2
let roundedStartingPadLength = Int(halfPadLength.rounded(.toNearestOrAwayFromZero))
return paddingStart(length: length - roundedStartingPadLength, with: token).paddingEnd(length: length, with: token)
}
/// **Mechanica**
///
/// Pads `self on the left and right sides if it's shorter than `length` using a `token`. Padding characters are truncated if they can't be evenly divided by length.
///
/// Example 1:
///
/// let string = "Hello World"
/// string.pad(length: 15) -> " Hello World "
///
/// Example 2:
///
/// let string = "Hello World"
/// string.pad(length: 15, withToken: "*") -> "**Hello World**"
///
/// - Parameters:
/// - length: The final length of your string. If the provided length is less than or equal to the original string, the original string is returned.
/// If the the sum-total of characters added is odd, the left side of the string will have one less instance of the token.
/// - token: The string used to pad the String (defaults to a white space).
/// - Note: If the the sum-total of characters added is odd, the left side of the string will have one less instance of the token.
public mutating func pad(length: Int, with token: String = " ") {
self = padding(length: length, with: token)
}
/// **Mechanica**
///
/// Returns a `new` String with the left-padded version of `self` if it's shorter than `length` using a `token`. Padding characters are truncated if they can't be evenly divided by length.
///
/// Example 1:
///
/// let string = "Hello World"
/// string.paddingStart(length: 15) -> " Hello World"
///
/// Example 2:
///
/// let string = "Hello World"
/// string.paddingStart(length: 15, withToken: "*") -> "****Hello World"
///
/// - Parameters:
/// - length: The final length of your string.
/// - token: The string used to pad the String (defaults to a white space).
/// - Returns: The left-padded copy of the string.
public func paddingStart(length: Int, with token: String = " ") -> String {
guard count < length else { return self }
let padLength = length - count
if padLength < token.count {
return token[token.startIndex..<token.index(token.startIndex, offsetBy: padLength)] + self
} else {
var padding = token
while padding.count < padLength {
padding.append(token)
}
return padding[padding.startIndex..<padding.index(padding.startIndex, offsetBy: padLength)] + self
}
}
/// **Mechanica**
///
/// Pads `self` on the left side if it's shorter than `length` using a `token`. Padding characters are truncated if they exceed length.
///
/// Example 1:
///
/// let string = "Hello World"
/// string.padStart(length: 15) -> " Hello World"
///
/// Example 2:
///
/// let string = "Hello World"
/// string.padStart(length: 15, withToken: "*") -> "****Hello World"
///
/// - Parameters:
/// - length: The final length of your string.
/// - token: The string used to pad the String (defaults to a white space).
public mutating func padStart(length: Int, with token: String = " ") {
self = paddingStart(length: length, with: token)
}
/// **Mechanica**
///
/// Returns a `new` String with the right-padded version of `self` if it's shorter than `length` using a `token`. Padding characters are truncated if they can't be evenly divided by length.
///
/// Example 1:
///
/// let string = "Hello World"
/// string.paddingEnd(length: 15) -> "Hello World "
///
/// Example 2:
///
/// let string = "Hello World"
/// string.paddingEnd(length: 15, withToken: "*", ) -> "Hello World****"
///
/// - Parameters:
/// - length: The final length of your string.
/// - token: The string used to pad the String (defaults to a white space).
/// - Returns: The right-padded copy of the string.
public func paddingEnd(length: Int, with token: String = " ") -> String {
guard count < length else { return self }
let padLength = length - count
if padLength < token.count {
return self + token[token.startIndex..<token.index(token.startIndex, offsetBy: padLength)]
} else {
var padding = token
while padding.count < padLength {
padding.append(token)
}
return self + padding[padding.startIndex..<padding.index(padding.startIndex, offsetBy: padLength)]
}
}
/// **Mechanica**
///
/// Pads `self` on the right side if it's shorter than `length` using a `token`. Padding characters are truncated if they exceed length.
///
/// Example 1:
///
/// let string = "Hello World"
/// string.padEnd(length: 15) -> "Hello World "
///
/// Example 2:
///
/// let string = "Hello World"
/// string.padEnd(length: 15, withToken: "*", ) -> "Hello World****"
///
/// - Parameters:
/// - length: The final length of your string.
/// - token: The string used to pad the String (defaults to a white space).
public mutating func padEnd(length: Int, with token: String = " ") {
self = paddingEnd(length: length, with: token)
}
/// **Mechanica**
///
/// Returns a substring, up to maxLength in length, containing the initial elements of the `String`.
///
/// - Warning: If maxLength exceeds self.count, the result contains all the elements of self.
/// - parameter maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero.
///
public func prefix(maxLength: Int) -> String {
return String(prefix(maxLength))
}
/// **Mechanica**
///
/// Returns a new `String` containing the characters of the String from the one at a given position to the end.
///
/// Example:
///
/// "hello".droppingPrefix(upToPosition: 1) -> "ello"
/// "hello".droppingPrefix(upToPosition: 1) -> ""
///
/// - parameter upToPosition: position (included) up to which remove the prefix.
public func droppingPrefix(upToPosition: Int = 1) -> String {
guard upToPosition >= 0 && upToPosition <= length else { return "" }
return String(dropFirst(upToPosition))
}
/// **Mechanica**
///
/// Returns a new `String` removing the spcified prefix (if the string has it).
///
/// Example:
///
/// "hello".droppingPrefix("hel") -> "lo"
///
/// - parameter prefix: prefix to be removed.
public func droppingPrefix(_ prefix: String) -> String {
guard hasPrefix(prefix) else { return self }
return droppingPrefix(upToPosition: prefix.length)
}
/// **Mechanica**
///
/// Returns a new `String` containing the characters of the String up to, but not including, the one at a given position.
/// - parameter fromPosition: position (included) from which remove the suffix
///
/// Example:
///
/// "hello".droppingSuffix(fromPosition: 1) -> "hell"
/// "hello".droppingSuffix(fromPosition: 10) -> ""
///
public func droppingSuffix(fromPosition: Int = 1) -> String {
guard fromPosition >= 0 && fromPosition <= length else { return "" }
return String(dropLast(fromPosition))
}
/// **Mechanica**
///
/// Returns a new `String` removing the spcified suffix (if the string has it).
///
/// Example:
///
/// "hello".droppingSuffix("0") -> "hell"
///
/// - parameter prefix: prefix to be removed.
public func droppingSuffix(_ suffix: String) -> String {
guard hasSuffix(suffix) else { return self }
return droppingSuffix(fromPosition: suffix.length)
}
/// **Mechanica**
///
/// Reverse `self`.
public mutating func reverse() {
self = String(reversed())
}
/// **Mechanica**
///
/// Returns a slice, up to maxLength in length, containing the final elements of `String`.
///
/// - Warning: If maxLength exceeds `String` character count, the result contains all the elements of `String`.
/// - parameter maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero.
public func suffix(maxLength: Int) -> String {
return String(suffix(maxLength))
}
/// **Mechanica**
///
/// Truncates the `String` to the given length (number of characters) and appends optional trailing string if longer.
/// The default trailing is the ellipsis (…).
/// - parameter length: number of characters after which the `String` is truncated
/// - parameter trailing: optional trailing string
///
public func truncate(at length: Int, withTrailing trailing: String? = "…") -> String {
var truncated = self.prefix(maxLength: length)
if 0..<self.length ~= length {
if let trailing = trailing {
truncated.append(trailing)
}
}
return truncated
}
// MARK: - Subscript Methods
/// **Mechanica**
///
/// Gets the character at the specified index as String.
///
/// - parameter index: index Position of the character to get
///
/// - Returns: Character as String or nil if the index is out of bounds
///
/// Example:
///
/// let myString = "Hello world"
/// myString[0] -> "H"
/// myString[3] -> "l"
/// myString[10] -> "d"
/// myString[11] -> nil
/// myString[-1] -> nil
///
public subscript (index: Int) -> Character? {
guard 0..<count ~= index else { return nil }
return Array(self)[index]
}
/// **Mechanica**
///
/// Returns a substring for the given range.
///
/// - Parameter range: a `CountableRange` range.
///
/// Example:
///
/// let myString = "Hello world"
/// myString[0..<0] -> ""
/// myString[0..<1] -> "Hello worl"
/// myString[0..<10] -> "Hello world"
/// myString[0..<11] -> nil
/// myString[11..<14] -> nil
/// myString[-1..<11] -> nil
///
public subscript (range: CountableRange<Int>) -> Substring? {
guard 0...count ~= range.lowerBound else { return nil }
guard 0...count ~= range.upperBound else { return nil }
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(startIndex, offsetBy: range.upperBound)
return self[start..<end]
}
/// **Mechanica**
///
/// Returns a substring for the given range.
/// - Parameter range: a `CountableClosedRange` range.
///
/// Example:
///
/// let myString = "Hello world"
/// myString[0...0]
/// myString[0...1]
/// myString[0...10]
/// myString[0...11]
/// myString[11...14]
/// myString[-1...11]
///
public subscript (range: CountableClosedRange<Int>) -> Substring? {
guard 0..<count ~= range.lowerBound else { return nil }
guard 0..<count ~= range.upperBound else { return nil }
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(startIndex, offsetBy: range.upperBound)
return self[start...end]
}
/// **Mechanica**
///
/// Returns a substring for the given range.
/// - Parameter range: a `PartialRangeUpTo` range.
///
/// Example:
///
/// let myString = "Hello world"
/// myString[0...0] -> "H"
/// myString[0...1] -> "He"
/// myString[0...10] -> "Hello world"
/// myString[0...11] -> nil
/// myString[11...14] -> nil
/// myString[-1...11] -> nil
///
public subscript (range: PartialRangeUpTo<Int>) -> Substring? {
guard 0...count ~= range.upperBound else { return nil }
let end = index(startIndex, offsetBy: range.upperBound)
return self[..<end]
}
/// **Mechanica**
///
/// - Parameter range: a `PartialRangeThrough` range.
/// Example:
///
/// let myString = "Hello world"
/// myString[..<0] -> ""
/// myString[..<1] -> "H"
/// myString[..<10] -> "Hello worl"
/// myString[..<11] -> "Hello world"
/// myString[..<14] -> nil
/// myString[..<(-1)] -> nil
///
public subscript(range: PartialRangeThrough<Int>) -> Substring? {
guard 0..<count ~= range.upperBound else { return nil }
let end = index(startIndex, offsetBy: range.upperBound)
return self[...end]
}
/// **Mechanica**
///
/// Returns a substring for the given range.
/// - Parameter range: a `CountablePartialRangeFrom` range.
/// Example:
///
/// let myString = "Hello world"
/// myString[0...] -> "Hello world"
/// myString[1...] -> "ello world"
/// myString[10...] -> "d"
/// myString[11...] -> nil
/// myString[14...] -> nil
/// myString[(-1)...] -> nil
///
public subscript (range: CountablePartialRangeFrom<Int>) -> Substring? {
guard 0..<count ~= range.lowerBound else { return nil }
let start = index(startIndex, offsetBy: range.lowerBound)
return self[start...]
}
// MARK: - Operators
/// **Mechanica**
///
/// Returns a substring for the given range.
/// Creates a `new` string representing the given string repeated the specified number of times.
public static func * (lhs: String, rhs: Int) -> String {
return String(repeating: lhs, count: rhs)
}
/// **Mechanica**
///
/// Returns a substring for the given range.
/// Creates a `new` string representing the given string repeated the specified number of times.
public static func * (lhs: Int, rhs: String) -> String {
return String(repeating: rhs, count: lhs)
}
}
| mit | 1562cd3254f7be7fceb64cbbb7fa473a | 31.674227 | 194 | 0.609579 | 4.005814 | false | false | false | false |
semiroot/SwiftyConstraints | Tests/SC203BottomTests.swift | 1 | 4849 | //
// SC201Top.swift
// SwiftyConstraints
//
// Created by Hansmartin Geiser on 15/04/17.
// Copyright © 2017 Hansmartin Geiser. All rights reserved.
//
import XCTest
import Foundation
@testable import SwiftyConstraints
class SC203BottomTests: SCTest {
var subview1 = SCView()
var subview2 = SCView()
var superview: SCView?
var swiftyConstraints: SwiftyConstraints?
override func setUp() {
super.setUp()
superview = SCView()
swiftyConstraints = SwiftyConstraints(superview!)
}
override func tearDown() {
super.tearDown()
swiftyConstraints = nil
superview = nil
}
func test00Bottom() {
guard let swiftyConstraints = swiftyConstraints, let superview = superview else { XCTFail("Test setup failure"); return }
swiftyConstraints.attach(subview1)
swiftyConstraints.bottom()
guard let constraint1 = SCTAssertConstraintCreated(swiftyConstraints, .bottom) else { return }
SCTAssertConstraintMatching(constraint1, produceConstraint(subview1, superview, .bottom, .bottom, .equal, 1, 0))
swiftyConstraints.removeBottom()
SCTAssertConstraintRemoved(swiftyConstraints, constraint1, .bottom)
swiftyConstraints.bottom(33.5)
guard let constraint2 = SCTAssertConstraintCreated(swiftyConstraints, .bottom) else { return }
SCTAssertConstraintMatching(constraint2, produceConstraint(subview1, superview, .bottom, .bottom, .equal, 1, -33.5))
swiftyConstraints.removeBottom()
SCTAssertConstraintRemoved(swiftyConstraints, constraint2, .bottom)
}
func test01Above() {
guard let swiftyConstraints = swiftyConstraints, let superview = superview else { XCTFail("Test setup failure"); return }
swiftyConstraints
.attach(subview1)
.attach(subview2)
swiftyConstraints.above(subview1)
guard let constraint1 = SCTAssertConstraintCreated(swiftyConstraints, .bottom) else { return }
SCTAssertConstraintMatching(constraint1, produceConstraint(subview2, subview1, .bottom, .top, .equal, 1, 0))
swiftyConstraints.removeBottom()
SCTAssertConstraintRemoved(swiftyConstraints, constraint1, .bottom)
swiftyConstraints.above(subview1, 15.5)
guard let constraint2 = SCTAssertConstraintCreated(swiftyConstraints, .bottom) else { return }
SCTAssertConstraintMatching(constraint2, produceConstraint(subview2, subview1, .bottom, .top, .equal, 1, -15.5))
swiftyConstraints.removeBottom()
SCTAssertConstraintRemoved(swiftyConstraints, constraint2, .bottom)
// invalid reference
let view = SCView()
swiftyConstraints.above(view)
XCTAssertTrue(
superview.constraints.count == 0,
"Constraint should not have been created for inexistent reference"
)
XCTAssertEqual(
swiftyConstraints.previousErrors.last,
SCError.emptyReferenceView,
"Empty reference view did not cause error"
)
}
func test02Stacking() {
guard let swiftyConstraints = swiftyConstraints, let superview = superview else { XCTFail("Test setup failure"); return }
swiftyConstraints.attach(subview1).stackBottom()
XCTAssertTrue(
(try? swiftyConstraints.getCurrentContainer()) === swiftyConstraints.previousBottom,
"Stacking container did not get set"
)
swiftyConstraints.attach(subview2)
swiftyConstraints.bottom()
guard let constraint1 = SCTAssertConstraintCreated(swiftyConstraints, .bottom) else { return }
SCTAssertConstraintMatching(constraint1, produceConstraint(subview2, subview1, .bottom, .top, .equal, 1, 0))
swiftyConstraints.removeBottom()
SCTAssertConstraintRemoved(swiftyConstraints, constraint1, .bottom)
swiftyConstraints.bottom(15.5)
guard let constraint2 = SCTAssertConstraintCreated(swiftyConstraints, .bottom) else { return }
SCTAssertConstraintMatching(constraint2, produceConstraint(subview2, subview1, .bottom, .top, .equal, 1, -15.5))
swiftyConstraints.removeBottom()
SCTAssertConstraintRemoved(swiftyConstraints, constraint2, .bottom)
swiftyConstraints.resetStackBottom()
XCTAssertNil(
swiftyConstraints.previousBottom,
"Stacking container did not get reset"
)
swiftyConstraints.bottom()
guard let constraint3 = SCTAssertConstraintCreated(swiftyConstraints, .bottom) else { return }
SCTAssertConstraintMatching(constraint3, produceConstraint(subview2, superview, .bottom, .bottom, .equal, 1, 0))
swiftyConstraints.removeBottom()
SCTAssertConstraintRemoved(swiftyConstraints, constraint3, .bottom)
swiftyConstraints.removeBottom()
XCTAssertEqual(
swiftyConstraints.previousErrors.last,
SCError.emptyRemoveConstraint,
"Removing empty constraint did not cause error"
)
}
}
| mit | 359da0befdff7c97eac45b144a7a3def | 32.902098 | 125 | 0.726485 | 5.286805 | false | true | false | false |
jkereako/MassStateKeno | Sources/Views/DrawingTableViewController.swift | 1 | 2324 | //
// DrawingTableViewController.swift
// MassLotteryKeno
//
// Created by Jeff Kereakoglow on 5/19/19.
// Copyright © 2019 Alexis Digital. All rights reserved.
//
import UIKit
protocol DrawingTableViewControllerDelegate: class {
func didPullToRefresh(tableViewController: DrawingTableViewController, refreshControl: UIRefreshControl)
}
final class DrawingTableViewController: UITableViewController {
weak var delegate: DrawingTableViewControllerDelegate?
var viewModel: DrawingTableViewModel? {
didSet {
title = viewModel?.title
tableView?.refreshControl?.endRefreshing()
tableView.dataSource = viewModel
tableView.delegate = viewModel
tableView.reloadData()
}
}
init() {
super.init(style: .grouped)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(
nibName: cellReuseIdentifier, bundle: Bundle(for: DrawingTableViewCell.self)
)
refreshControl = UIRefreshControl()
refreshControl?.addTarget(
viewModel,
action: #selector(refreshAction),
for: .valueChanged
)
tableView.register(nib, forCellReuseIdentifier: cellReuseIdentifier)
tableView.backgroundColor = UIColor(named: "DarkBlue")
tableView.separatorStyle = .none
}
}
// MARK: - DrawingTableViewModelDataSource
extension DrawingTableViewController: DrawingTableViewModelDataSource {
var cellReuseIdentifier: String {
return "DrawingTableViewCell"
}
func configure(_ cell: UITableViewCell, with drawingViewModel: DrawingViewModel) -> UITableViewCell {
guard let drawingTableViewCell = cell as? DrawingTableViewCell else {
assertionFailure("Expected a DrawingTableViewCell")
return UITableViewCell()
}
drawingTableViewCell.viewModel = drawingViewModel
return drawingTableViewCell
}
}
// MARK: - Target-actions
extension DrawingTableViewController {
@objc func refreshAction(sender: Any) {
delegate?.didPullToRefresh(
tableViewController: self, refreshControl: tableView.refreshControl!
)
}
}
| mit | 00ef46a5ed3863a26191cb4c01f7b9f4 | 26.654762 | 108 | 0.678003 | 5.735802 | false | false | false | false |
onmyway133/Github.swift | GithubSwiftTests/Classes/FormatterSpec.swift | 1 | 1751 | //
// FormatterSpec.swift
// GithubSwift
//
// Created by Khoa Pham on 03/04/16.
// Copyright © 2016 Fantageek. All rights reserved.
//
import Foundation
import GithubSwift
import Quick
import Nimble
import Mockingjay
import RxSwift
import Sugar
class FormatterSpec: QuickSpec {
override func spec() {
describe("formatter") {
var calendar: NSCalendar!
beforeEach {
calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
calendar.locale = NSLocale(localeIdentifier: "en_US_POSIX")
calendar.timeZone = NSTimeZone(abbreviation: "UTC")!
}
it("should parse an ISO 8601 string into a date and back") {
let string = "2011-01-26T19:06:43Z"
let components = NSDateComponents().then {
$0.day = 26;
$0.month = 1;
$0.year = 2011;
$0.hour = 19;
$0.minute = 6;
$0.second = 43;
}
let date = Formatter.date(string: string)
expect(date).toNot(beNil())
expect(date).to(equal(calendar.dateFromComponents(components)))
expect(Formatter.string(date: date!)).to(equal(string))
}
it("shouldn't use ISO week-numbering year") {
let string = "2012-01-01T00:00:00Z"
let components = NSDateComponents().then {
$0.day = 1;
$0.month = 1;
$0.year = 2012;
$0.hour = 0;
$0.minute = 0;
$0.second = 0;
}
let date = Formatter.date(string: string)
expect(date).toNot(beNil())
expect(date).to(equal(calendar.dateFromComponents(components)))
expect(Formatter.string(date: date!)).to(equal(string))
}
}
}
}
| mit | 7f08cc137bd12ba32b20da51696de9a8 | 25.923077 | 72 | 0.572 | 4.060325 | false | false | false | false |
y-hryk/Architectures-iOS | ArchitecturesDemo/AppDelegate.swift | 1 | 2693 | //
// AppDelegate.swift
// ArchitecturesDemo
//
// Created by h.yamaguchi on 2016/12/28.
// Copyright © 2016年 h.yamaguchi. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.backgroundColor = UIColor.black
UINavigationBar.appearance().barTintColor = UIColor.baseColor()
UIApplication.shared.setStatusBarStyle(.lightContent, animated: false)
let vc = SwitchVC.mainController()
let navi = UINavigationController(rootViewController: vc)
self.window?.rootViewController = navi
self.window?.makeKeyAndVisible()
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 invalidate graphics rendering callbacks. 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 active 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:.
}
}
| mit | 3d9707411ed20c68de47ff26336c692c | 44.59322 | 285 | 0.733457 | 5.711253 | false | false | false | false |
genadyo/Lyft | Lyft/Classes/LyftOAuth.swift | 1 | 2669 | //
// LyftOAuth.swift
// SFParties
//
// Created by Genady Okrain on 5/11/16.
// Copyright © 2016 Okrain. All rights reserved.
//
import Foundation
public extension Lyft {
// Initialize clientId & clientSecret
static func set(clientId: String, clientSecret: String, sandbox: Bool? = nil) {
sharedInstance.clientId = clientId
sharedInstance.clientSecret = clientSecret
sharedInstance.sandbox = sandbox ?? false
}
// 3-Legged flow for accessing user-specific endpoints
static func userLogin(scope: String, state: String = "", completionHandler: ((_ success: Bool, _ error: NSError?) -> ())?) {
guard let clientId = sharedInstance.clientId, let _ = sharedInstance.clientSecret else { return }
let string = "\(lyftAPIOAuthURL)/authorize?client_id=\(clientId)&response_type=code&scope=\(scope)&state=\(state)"
sharedInstance.completionHandler = completionHandler
if let url = URL(string: string.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!) {
UIApplication.shared.openURL(url)
}
}
// Client Credentials (2-legged) flow for public endpoints
static func publicLogin(_ completionHandler: ((_ success: Bool, _ error: NSError?) -> ())?) {
guard let _ = sharedInstance.clientId, let _ = sharedInstance.clientSecret else { return }
sharedInstance.completionHandler = completionHandler
fetchAccessToken(nil)
}
// Refreshing the access token
static func refreshToken(_ completionHandler: ((_ success: Bool, _ error: NSError?) -> ())?) {
guard let _ = sharedInstance.clientId, let _ = sharedInstance.clientSecret else { return }
sharedInstance.completionHandler = completionHandler
fetchAccessToken(nil, refresh: true)
}
// Revoking the access token
static func revokeToken(_ completionHandler: ((_ success: Bool, _ error: NSError?) -> ())?) {
guard let _ = sharedInstance.clientId, let _ = sharedInstance.clientSecret else { return }
sharedInstance.completionHandler = completionHandler
fetchAccessToken(nil, refresh: false, revoke: true)
}
// func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool
static func openURL(_ url: URL) -> Bool {
guard let _ = sharedInstance.clientId, let _ = sharedInstance.clientSecret else { return false }
guard let code = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.filter({ $0.name == "code" }).first?.value else { return false }
fetchAccessToken(code)
return true
}
}
| mit | 6b9c7c0d02abc2d86d028bacb2b825ae | 38.235294 | 158 | 0.673538 | 4.922509 | false | false | false | false |
andrebocchini/SwiftChattyOSX | Pods/SwiftChatty/SwiftChatty/Requests/Notifications/DetachAccountRequest.swift | 1 | 629 | //
// DetachAccountRequest.swift
// SwiftChatty
//
// Created by Andre Bocchini on 1/28/16.
// Copyright © 2016 Andre Bocchini. All rights reserved.
//
import Alamofire
/// - SeeAlso: http://winchatty.com/v2/readme#_Toc421451708
public struct DetachAccountRequest: Request {
public let endpoint: ApiEndpoint = .DetachAccount
public let httpMethod: Alamofire.Method = .POST
public let account: Account
public var parameters: [String : AnyObject] = [:]
public init(withClientId clientId: String, account: Account) {
self.account = account
self.parameters["clientId"] = clientId
}
}
| mit | 3747d7a5d9ccd6c9b8c0808711a4e0c2 | 26.304348 | 66 | 0.699045 | 4.214765 | false | false | false | false |
nathan-hekman/Chill | Chill/Chill WatchKit Extension/InterfaceController.swift | 1 | 17218 | //
// InterfaceController.swift
// Chill WatchKit Extension
//
// Created by Nathan Hekman on 12/7/15.
// Copyright © 2015 NTH. All rights reserved.
//
import Foundation
import HealthKit
import WatchKit
import WatchConnectivity
class InterfaceController: WKInterfaceController {
@IBOutlet var resultGroup: WKInterfaceGroup!
@IBOutlet var chillResultLabel: WKInterfaceLabel!
@IBOutlet private weak var label: WKInterfaceLabel!
@IBOutlet private weak var heart: WKInterfaceImage!
@IBOutlet private weak var startStopButton : WKInterfaceButton!
@IBOutlet var pleaseWaitLabel: WKInterfaceLabel!
//State of the app - is the workout activated
var workoutActive = false
// define the activity type and location
var workoutSession : HKWorkoutSession?
let heartRateUnit = HKUnit(fromString: "count/min")
var anchor = HKQueryAnchor(fromValue: Int(HKAnchoredObjectQueryNoAnchor))
var hasShownAlert = false
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
tellPhoneWatchIsAwake()
//setupTargetLabel()
}
override func willActivate() {
super.willActivate()
setupWCSession()
setupHeartRateData()
tellPhoneWatchIsAwake()
//setupTargetLabel()
}
override func willDisappear() {
}
override func didAppear() {
tellPhoneWatchIsAwake()
//setupHeartRateData()
//showPopup()
//setupTargetLabel()
}
func setupHeartRateData() {
guard HKHealthStore.isHealthDataAvailable() == true else {
self.displayNotAllowed()
return
}
if let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) {
let dataTypes = Set(arrayLiteral: quantityType)
let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
if let healthStore = HealthKitManager.sharedInstance.healthStore {
let status = healthStore.authorizationStatusForType(quantityType!)
switch status {
case .SharingAuthorized:
Utils.updateUserDefaultsHasRespondedToHealthKit(1) //update has responded now at this point
dispatch_async(dispatch_get_main_queue()) {
self.startStopButton.setEnabled(true)
self.pleaseWaitLabel.setText("Measuring...")
self.pleaseWaitLabel.setHidden(true)
//self.chillResultLabel.setText("---")
}
case .SharingDenied:
Utils.updateUserDefaultsHasRespondedToHealthKit(0) //update has responded now at this point
dispatch_async(dispatch_get_main_queue()) {
self.startStopButton.setEnabled(false)
self.pleaseWaitLabel.setText("Open Health app to accept access")
self.pleaseWaitLabel.setHidden(false)
if (self.hasShownAlert == false) {
self.tryToShowPopup("\"Chill\" needs permission to access heart rate data and save heart rate data to the Health app in order to check your heart rate and Chill status. Check the Health app to accept. See the iPhone app for privacy information.")
} else { //if true, then set to false so it shows next time
self.hasShownAlert = false
}
}
//}
case .NotDetermined:
dispatch_async(dispatch_get_main_queue()) {
self.startStopButton.setEnabled(false)
//self.chillResultLabel.setText("Open on iPhone or Health app to accept access")
self.pleaseWaitLabel.setText("Open Health app to accept access")
self.pleaseWaitLabel.setHidden(false)
}
if (self.hasShownAlert == false) {
healthStore.requestAuthorizationToShareTypes(dataTypes, readTypes: dataTypes) { (success, error) -> Void in
if success == false {
self.displayNotAllowed()
Utils.updateUserDefaultsHasRespondedToHealthKit(0)
}
else if success == true {
self.setupHeartRateData()
Utils.updateUserDefaultsHasRespondedToHealthKit(1) //update has responded now at this point
}
}
}
else { //if true, then set to false so it shows next time
self.hasShownAlert = false
}
}
}
} else {
self.displayNotAllowed()
return
}
}
func tryToShowPopup(text: String!){
//if (Utils.retrieveHasRespondedToHealthKitFromUserDefaults() == nil) { //show alert if hasn't seen before or failed
let h0 = {
print("OK tapped")
//finish the current workout
// self.stopLoadingAnimation()
// self.resetScreen()
}
let action1 = WKAlertAction(title: "Got it", style: .Default, handler:h0)
dispatch_async(dispatch_get_main_queue()) {
self.presentAlertControllerWithTitle("Health Access", message: text, preferredStyle: .Alert, actions: [action1])
self.hasShownAlert = true
}
//}
}
func setupWCSession() {
WatchSessionManager.sharedInstance.startSession()
WatchSessionManager.sharedInstance.interfaceController = self //save copy of self in session manager
}
func displayNotAllowed() {
dispatch_async(dispatch_get_main_queue()) {
self.label.setText("use actual device")
}
}
func workoutDidStart(date : NSDate) {
dispatch_async(dispatch_get_main_queue()) {
if let query = self.createHeartRateStreamingQuery(date) {
if let healthStore = HealthKitManager.sharedInstance.healthStore {
healthStore.executeQuery(query)
}
} else {
self.label.setText("cannot start")
}
}
}
func workoutDidEnd(date : NSDate) {
dispatch_async(dispatch_get_main_queue()) {
if let query = self.createHeartRateStreamingQuery(date) {
if let healthStore = HealthKitManager.sharedInstance.healthStore {
healthStore.stopQuery(query)
self.stopLoadingAnimation()
self.stopWorkout()
self.resetScreen()
}
} else {
self.label.setText("cannot stop")
}
}
}
// MARK: - Actions
@IBAction func startBtnTapped() {
dispatch_async(dispatch_get_main_queue()) {
self.setupHeartRateData()
if (self.workoutActive) {
//finish the current workout
self.stopLoadingAnimation()
self.stopWorkout()
self.resetScreen()
} else {
//start a new workout
dispatch_async(dispatch_get_main_queue()) {
//self.setupTargetLabel()
self.startLoadingAnimation()
self.workoutActive = true
self.startStopButton.setTitle("Cancel")
self.label.setText("--")
self.chillResultLabel.setText("---")
self.startWorkout()
}
}
}
}
func startLoadingAnimation() {
// 1
let duration = 1.0
// 2
resultGroup.setBackgroundImageNamed("Loader")
// 3
dispatch_async(dispatch_get_main_queue()) {
self.pleaseWaitLabel.setText("Measuring...")
self.pleaseWaitLabel.setHidden(false)
self.chillResultLabel.setHidden(true)
self.resultGroup.startAnimatingWithImagesInRange(NSRange(location: 0, length: 97), duration: duration, repeatCount: 0)
}
}
func stopLoadingAnimation() {
//stop loading animation
dispatch_async(dispatch_get_main_queue()) {
self.pleaseWaitLabel.setText("Measuring...")
self.pleaseWaitLabel.setHidden(true)
self.chillResultLabel.setHidden(false)
self.resultGroup.setBackgroundImage(nil)
self.resultGroup.stopAnimating()
}
}
func tellPhoneWatchIsAwake() {
//if let _ = WatchSessionManager.sharedInstance.validReachableSession {
let messageToSend = ["Awake":"I'm awake, iPhone!"]
WatchSessionManager.sharedInstance.sendMessage(messageToSend, replyHandler: { replyMessage in
//handle and present the message on screen
if let value = replyMessage["Awake"] as? String {
print("Message received back from iPhone: \(value)")
}
else {
print("No message received back from iPhone!")
}
}, errorHandler: {error in
// catch any errors here
print(error)
})
//}
}
func stopWorkout() {
if let workout = self.workoutSession {
if let healthStore = HealthKitManager.sharedInstance.healthStore {
healthStore.endWorkoutSession(workout)
}
self.workoutSession = nil
}
}
func startWorkout() {
self.workoutSession = HKWorkoutSession(activityType: HKWorkoutActivityType.CrossTraining, locationType: HKWorkoutSessionLocationType.Indoor)
self.workoutSession?.delegate = self
if let healthStore = HealthKitManager.sharedInstance.healthStore {
healthStore.startWorkoutSession(self.workoutSession!)
}
}
func createHeartRateStreamingQuery(workoutStartDate: NSDate) -> HKQuery? {
// adding predicate will not work
// let predicate = HKQuery.predicateForSamplesWithStartDate(workoutStartDate, endDate: nil, options: HKQueryOptions.None)
guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return nil }
let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: nil, anchor: anchor, limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in
guard let newAnchor = newAnchor else {
return
}
self.anchor = newAnchor
self.updateHeartRate(sampleObjects)
}
heartRateQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) -> Void in
if (self.workoutActive == true) { //check if stop button has been pressed
self.anchor = newAnchor! //these two lines will continue measuring if uncommented
self.updateHeartRate(samples)
}
else {
}
}
return heartRateQuery
}
func sendHeartRateValueToPhone(heartRate: String!, isChill: String!) { //heart rate as a string, is chill boolean as "T" or "F" string for true or false
WatchSessionManager.sharedInstance.lastHeartRateString = heartRate
let messageToSend = ["HR":"\(isChill):\(heartRate)"]
//if let _ = WatchSessionManager.sharedInstance.validReachableSession {
do {
try WatchSessionManager.sharedInstance.updateApplicationContext(messageToSend)
}
catch {
print("couldn't update application context!!")
}
//}
}
func updateHeartRate(samples: [HKSample]?) {
guard let heartRateSamples = samples as? [HKQuantitySample] else {return}
guard let sample = heartRateSamples.first else{return}
let value = sample.quantity.doubleValueForUnit(self.heartRateUnit)
let heartRateInt = UInt16(value)
let heartRateString = String(heartRateInt)
let chill = userIsChill(heartRateInt)
if (self.workoutActive == true) {
//finish the current workout after 1 measurement
self.workoutActive = false
self.stopLoadingAnimation()
//show result on UI
dispatch_async(dispatch_get_main_queue()) {
//vibrate watch too
WKInterfaceDevice().playHaptic(.Notification)
self.animateHeart()
self.label.setText(heartRateString)
if (chill == true) { //user is chill
self.chillResultLabel.setText("You're Chill.")
self.chillResultLabel.setVerticalAlignment(WKInterfaceObjectVerticalAlignment.Center)
self.chillResultLabel.setHorizontalAlignment(WKInterfaceObjectHorizontalAlignment.Center)
//send latest HR value to phone
self.sendHeartRateValueToPhone(heartRateString, isChill:"T")
}
else { //user is not chill
self.chillResultLabel.setText("You should Chill.")
self.chillResultLabel.setVerticalAlignment(WKInterfaceObjectVerticalAlignment.Center)
self.chillResultLabel.setHorizontalAlignment(WKInterfaceObjectHorizontalAlignment.Center)
//send latest HR value to phone
self.sendHeartRateValueToPhone(heartRateString, isChill:"F")
}
self.stopWorkout()
self.resetScreen()
//var _ = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "resetScreen", userInfo: nil, repeats: false)
}
}
}
func resetScreen() {
dispatch_async(dispatch_get_main_queue()) {
self.workoutActive = false
self.startStopButton.setTitle("Measure")
// self.label.setText("--")
// self.chillResultLabel.setText("---")
}
}
func userIsChill(heartRate: UInt16!) -> Bool! {
//user is not "Chill" if heartrate is above 76 bpm. According to: http://www.webmd.com/heart-disease/features/5-heart-rate-myths-debunked
//"Recent studies suggest a heart rate higher than 76 beats per minute when you're resting may be linked to a higher risk of heart attack."
let heartRateTarget = UInt16(WatchSessionManager.sharedInstance.targetHeartRateString)
if (heartRate > heartRateTarget) {
return false
}
else {
return true
}
}
func animateHeart() {
self.animateWithDuration(0.5) {
self.heart.setWidth(30)
self.heart.setHeight(30)
}
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * double_t(NSEC_PER_SEC)))
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_after(when, queue) {
dispatch_async(dispatch_get_main_queue(), {
self.animateWithDuration(0.5, animations: {
self.heart.setWidth(23)
self.heart.setHeight(23)
})
})
}
}
}
extension InterfaceController: HKWorkoutSessionDelegate {
func workoutSession(workoutSession: HKWorkoutSession, didChangeToState toState: HKWorkoutSessionState, fromState: HKWorkoutSessionState, date: NSDate) {
switch toState {
case .Running:
workoutDidStart(date)
case .Ended:
workoutDidEnd(date)
default:
//workoutDidEnd(date)
print("Unexpected state \(toState)")
}
}
func workoutSession(workoutSession: HKWorkoutSession, didFailWithError error: NSError) {
// Do nothing for now
NSLog("Workout error: \(error.userInfo)")
stopLoadingAnimation()
self.stopWorkout()
resetScreen()
}
}
extension InterfaceController: WCSessionDelegate {
} | mit | 4d0fe83366b6d5148a6cb513113cbb0d | 35.020921 | 274 | 0.559796 | 5.914462 | false | false | false | false |
michael-lehew/swift-corelibs-foundation | Foundation/NSURLSession/NSURLSessionTask.swift | 1 | 52949 | // Foundation/NSURLSession/NSURLSessionTask.swift - NSURLSession API
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
///
/// URLSession API code.
/// - SeeAlso: NSURLSession.swift
///
// -----------------------------------------------------------------------------
import CoreFoundation
import Dispatch
/// A cancelable object that refers to the lifetime
/// of processing a given request.
open class URLSessionTask : NSObject, NSCopying {
/// How many times the task has been suspended, 0 indicating a running task.
fileprivate var suspendCount = 1
fileprivate var easyHandle: _EasyHandle!
fileprivate var totalDownloaded = 0
fileprivate var session: URLSessionProtocol! //change to nil when task completes
fileprivate let body: _Body
fileprivate let tempFileURL: URL
/// The internal state that the task is in.
///
/// Setting this value will also add / remove the easy handle.
/// It is independt of the `state: URLSessionTask.State`. The
/// `internalState` tracks the state of transfers / waiting for callbacks.
/// The `state` tracks the overall state of the task (running vs.
/// completed).
/// - SeeAlso: URLSessionTask._InternalState
fileprivate var internalState = _InternalState.initial {
// We manage adding / removing the easy handle and pausing / unpausing
// here at a centralized place to make sure the internal state always
// matches up with the state of the easy handle being added and paused.
willSet {
if !internalState.isEasyHandlePaused && newValue.isEasyHandlePaused {
fatalError("Need to solve pausing receive.")
}
if internalState.isEasyHandleAddedToMultiHandle && !newValue.isEasyHandleAddedToMultiHandle {
session.remove(handle: easyHandle)
}
}
didSet {
if !oldValue.isEasyHandleAddedToMultiHandle && internalState.isEasyHandleAddedToMultiHandle {
session.add(handle: easyHandle)
}
if oldValue.isEasyHandlePaused && !internalState.isEasyHandlePaused {
fatalError("Need to solve pausing receive.")
}
if case .taskCompleted = internalState {
updateTaskState()
guard let s = session as? URLSession else { fatalError() }
s.workQueue.async {
s.taskRegistry.remove(self)
}
}
}
}
/// All operations must run on this queue.
fileprivate let workQueue: DispatchQueue
/// This queue is used to make public attributes thread safe. It's a
/// **concurrent** queue and must be used with a barries when writing. This
/// allows multiple concurrent readers or a single writer.
fileprivate let taskAttributesIsolation: DispatchQueue
public override init() {
// Darwin Foundation oddly allows calling this initializer, even though
// such a task is quite broken -- it doesn't have a session. And calling
// e.g. `taskIdentifier` will crash.
//
// We set up the bare minimum for init to work, but don't care too much
// about things crashing later.
session = _MissingURLSession()
taskIdentifier = 0
originalRequest = nil
body = .none
workQueue = DispatchQueue(label: "URLSessionTask.notused.0")
taskAttributesIsolation = DispatchQueue(label: "URLSessionTask.notused.1")
let fileName = NSTemporaryDirectory() + NSUUID().uuidString + ".tmp"
_ = FileManager.default.createFile(atPath: fileName, contents: nil)
self.tempFileURL = URL(fileURLWithPath: fileName)
super.init()
}
/// Create a data task. If there is a httpBody in the URLRequest, use that as a parameter
internal convenience init(session: URLSession, request: URLRequest, taskIdentifier: Int) {
if let bodyData = request.httpBody {
self.init(session: session, request: request, taskIdentifier: taskIdentifier, body: _Body.data(createDispatchData(bodyData)))
} else {
self.init(session: session, request: request, taskIdentifier: taskIdentifier, body: .none)
}
}
internal init(session: URLSession, request: URLRequest, taskIdentifier: Int, body: _Body) {
self.session = session
self.workQueue = session.workQueue
self.taskAttributesIsolation = session.taskAttributesIsolation
self.taskIdentifier = taskIdentifier
self.originalRequest = request
self.body = body
let fileName = NSTemporaryDirectory() + NSUUID().uuidString + ".tmp"
_ = FileManager.default.createFile(atPath: fileName, contents: nil)
self.tempFileURL = URL(fileURLWithPath: fileName)
super.init()
self.easyHandle = _EasyHandle(delegate: self)
}
deinit {
//TODO: Can we ensure this somewhere else? This might run on the wrong
// thread / queue.
//if internalState.isEasyHandleAddedToMultiHandle {
// session.removeHandle(easyHandle)
//}
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone?) -> Any {
NSUnimplemented()
}
/// An identifier for this task, assigned by and unique to the owning session
open let taskIdentifier: Int
/// May be nil if this is a stream task
/*@NSCopying*/ open let originalRequest: URLRequest?
/// May differ from originalRequest due to http server redirection
/*@NSCopying*/ open fileprivate(set) var currentRequest: URLRequest? {
get {
var r: URLRequest? = nil
taskAttributesIsolation.sync { r = self._currentRequest }
return r
}
//TODO: dispatch_barrier_async
set { taskAttributesIsolation.async { self._currentRequest = newValue } }
}
fileprivate var _currentRequest: URLRequest? = nil
/*@NSCopying*/ open fileprivate(set) var response: URLResponse? {
get {
var r: URLResponse? = nil
taskAttributesIsolation.sync { r = self._response }
return r
}
set { taskAttributesIsolation.async { self._response = newValue } }
}
fileprivate var _response: URLResponse? = nil
/* Byte count properties may be zero if no body is expected,
* or URLSessionTransferSizeUnknown if it is not possible
* to know how many bytes will be transferred.
*/
/// Number of body bytes already received
open fileprivate(set) var countOfBytesReceived: Int64 {
get {
var r: Int64 = 0
taskAttributesIsolation.sync { r = self._countOfBytesReceived }
return r
}
set { taskAttributesIsolation.async { self._countOfBytesReceived = newValue } }
}
fileprivate var _countOfBytesReceived: Int64 = 0
/// Number of body bytes already sent */
open fileprivate(set) var countOfBytesSent: Int64 {
get {
var r: Int64 = 0
taskAttributesIsolation.sync { r = self._countOfBytesSent }
return r
}
set { taskAttributesIsolation.async { self._countOfBytesSent = newValue } }
}
fileprivate var _countOfBytesSent: Int64 = 0
/// Number of body bytes we expect to send, derived from the Content-Length of the HTTP request */
open fileprivate(set) var countOfBytesExpectedToSend: Int64 = 0
/// Number of byte bytes we expect to receive, usually derived from the Content-Length header of an HTTP response. */
open fileprivate(set) var countOfBytesExpectedToReceive: Int64 = 0
/// The taskDescription property is available for the developer to
/// provide a descriptive label for the task.
open var taskDescription: String?
/* -cancel returns immediately, but marks a task as being canceled.
* The task will signal -URLSession:task:didCompleteWithError: with an
* error value of { NSURLErrorDomain, NSURLErrorCancelled }. In some
* cases, the task may signal other work before it acknowledges the
* cancelation. -cancel may be sent to a task that has been suspended.
*/
open func cancel() { NSUnimplemented() }
/*
* The current state of the task within the session.
*/
open var state: URLSessionTask.State {
get {
var r: URLSessionTask.State = .suspended
taskAttributesIsolation.sync { r = self._state }
return r
}
set { taskAttributesIsolation.async { self._state = newValue } }
}
fileprivate var _state: URLSessionTask.State = .suspended
/*
* The error, if any, delivered via -URLSession:task:didCompleteWithError:
* This property will be nil in the event that no error occured.
*/
/*@NSCopying*/ open var error: NSError? { NSUnimplemented() }
/// Suspend the task.
///
/// Suspending a task will prevent the URLSession from continuing to
/// load data. There may still be delegate calls made on behalf of
/// this task (for instance, to report data received while suspending)
/// but no further transmissions will be made on behalf of the task
/// until -resume is sent. The timeout timer associated with the task
/// will be disabled while a task is suspended. -suspend and -resume are
/// nestable.
open func suspend() {
// suspend / resume is implemented simply by adding / removing the task's
// easy handle fromt he session's multi-handle.
//
// This might result in slightly different behaviour than the Darwin Foundation
// implementation, but it'll be difficult to get complete parity anyhow.
// Too many things depend on timeout on the wire etc.
//
// TODO: It may be worth looking into starting over a task that gets
// resumed. The Darwin Foundation documentation states that that's what
// it does for anything but download tasks.
// We perform the increment and call to `updateTaskState()`
// synchronous, to make sure the `state` is updated when this method
// returns, but the actual suspend will be done asynchronous to avoid
// dead-locks.
workQueue.sync {
self.suspendCount += 1
guard self.suspendCount < Int.max else { fatalError("Task suspended too many times \(Int.max).") }
self.updateTaskState()
if self.suspendCount == 1 {
self.workQueue.async {
self.performSuspend()
}
}
}
}
/// Resume the task.
///
/// - SeeAlso: `suspend()`
open func resume() {
workQueue.sync {
self.suspendCount -= 1
guard 0 <= self.suspendCount else { fatalError("Resuming a task that's not suspended. Calls to resume() / suspend() need to be matched.") }
self.updateTaskState()
if self.suspendCount == 0 {
self.workQueue.async {
self.performResume()
}
}
}
}
/// The priority of the task.
///
/// Sets a scaling factor for the priority of the task. The scaling factor is a
/// value between 0.0 and 1.0 (inclusive), where 0.0 is considered the lowest
/// priority and 1.0 is considered the highest.
///
/// The priority is a hint and not a hard requirement of task performance. The
/// priority of a task may be changed using this API at any time, but not all
/// protocols support this; in these cases, the last priority that took effect
/// will be used.
///
/// If no priority is specified, the task will operate with the default priority
/// as defined by the constant URLSessionTaskPriorityDefault. Two additional
/// priority levels are provided: URLSessionTaskPriorityLow and
/// URLSessionTaskPriorityHigh, but use is not restricted to these.
open var priority: Float {
get {
var r: Float = 0
taskAttributesIsolation.sync { r = self._priority }
return r
}
set {
taskAttributesIsolation.async { self._priority = newValue }
}
}
fileprivate var _priority: Float = URLSessionTaskPriorityDefault
}
extension URLSessionTask {
public enum State : Int {
/// The task is currently being serviced by the session
case running
case suspended
/// The task has been told to cancel. The session will receive a URLSession:task:didCompleteWithError: message.
case canceling
/// The task has completed and the session will receive no more delegate notifications
case completed
}
}
fileprivate extension URLSessionTask {
/// The calls to `suspend` can be nested. This one is only called when the
/// task is not suspended and needs to go into suspended state.
func performSuspend() {
if case .transferInProgress(let transferState) = internalState {
internalState = .transferReady(transferState)
}
}
/// The calls to `resume` can be nested. This one is only called when the
/// task is suspended and needs to go out of suspended state.
func performResume() {
if case .initial = internalState {
guard let r = originalRequest else { fatalError("Task has no original request.") }
startNewTransfer(with: r)
}
if case .transferReady(let transferState) = internalState {
internalState = .transferInProgress(transferState)
}
}
}
internal extension URLSessionTask {
/// The is independent of the public `state: URLSessionTask.State`.
enum _InternalState {
/// Task has been created, but nothing has been done, yet
case initial
/// The easy handle has been fully configured. But it is not added to
/// the multi handle.
case transferReady(_TransferState)
/// The easy handle is currently added to the multi handle
case transferInProgress(_TransferState)
/// The transfer completed.
///
/// The easy handle has been removed from the multi handle. This does
/// not (necessarily mean the task completed. A task that gets
/// redirected will do multiple transfers.
case transferCompleted(response: HTTPURLResponse, bodyDataDrain: _TransferState._DataDrain)
/// The transfer failed.
///
/// Same as `.transferCompleted`, but without response / body data
case transferFailed
/// Waiting for the completion handler of the HTTP redirect callback.
///
/// When we tell the delegate that we're about to perform an HTTP
/// redirect, we need to wait for the delegate to let us know what
/// action to take.
case waitingForRedirectCompletionHandler(response: HTTPURLResponse, bodyDataDrain: _TransferState._DataDrain)
/// Waiting for the completion handler of the 'did receive response' callback.
///
/// When we tell the delegate that we received a response (i.e. when
/// we received a complete header), we need to wait for the delegate to
/// let us know what action to take. In this state the easy handle is
/// paused in order to suspend delegate callbacks.
case waitingForResponseCompletionHandler(_TransferState)
/// The task is completed
///
/// Contrast this with `.transferCompleted`.
case taskCompleted
}
}
fileprivate extension URLSessionTask._InternalState {
var isEasyHandleAddedToMultiHandle: Bool {
switch self {
case .initial: return false
case .transferReady: return false
case .transferInProgress: return true
case .transferCompleted: return false
case .transferFailed: return false
case .waitingForRedirectCompletionHandler: return false
case .waitingForResponseCompletionHandler: return true
case .taskCompleted: return false
}
}
var isEasyHandlePaused: Bool {
switch self {
case .initial: return false
case .transferReady: return false
case .transferInProgress: return false
case .transferCompleted: return false
case .transferFailed: return false
case .waitingForRedirectCompletionHandler: return false
case .waitingForResponseCompletionHandler: return true
case .taskCompleted: return false
}
}
}
internal extension URLSessionTask {
/// Updates the (public) state based on private / internal state.
///
/// - Note: This must be called on the `workQueue`.
fileprivate func updateTaskState() {
func calculateState() -> URLSessionTask.State {
if case .taskCompleted = internalState {
return .completed
}
if suspendCount == 0 {
return .running
} else {
return .suspended
}
}
state = calculateState()
}
}
internal extension URLSessionTask {
enum _Body {
case none
case data(DispatchData)
/// Body data is read from the given file URL
case file(URL)
case stream(InputStream)
}
}
fileprivate extension URLSessionTask._Body {
enum _Error : Error {
case fileForBodyDataNotFound
}
/// - Returns: The body length, or `nil` for no body (e.g. `GET` request).
func getBodyLength() throws -> UInt64? {
switch self {
case .none:
return 0
case .data(let d):
return UInt64(d.count)
/// Body data is read from the given file URL
case .file(let fileURL):
guard let s = try FileManager.default.attributesOfItem(atPath: fileURL.path)[.size] as? NSNumber else {
throw _Error.fileForBodyDataNotFound
}
return s.uint64Value
case .stream:
return nil
}
}
}
/// Easy handle related
fileprivate extension URLSessionTask {
/// Start a new transfer
func startNewTransfer(with request: URLRequest) {
currentRequest = request
guard let url = request.url else { fatalError("No URL in request.") }
internalState = .transferReady(createTransferState(url: url))
configureEasyHandle(for: request)
if suspendCount < 1 {
performResume()
}
}
/// Creates a new transfer state with the given behaviour:
func createTransferState(url: URL) -> URLSessionTask._TransferState {
let drain = createTransferBodyDataDrain()
switch body {
case .none:
return URLSessionTask._TransferState(url: url, bodyDataDrain: drain)
case .data(let data):
let source = _HTTPBodyDataSource(data: data)
return URLSessionTask._TransferState(url: url, bodyDataDrain: drain, bodySource: source)
case .file(let fileURL):
let source = _HTTPBodyFileSource(fileURL: fileURL, workQueue: workQueue, dataAvailableHandler: { [weak self] in
// Unpause the easy handle
self?.easyHandle.unpauseSend()
})
return URLSessionTask._TransferState(url: url, bodyDataDrain: drain, bodySource: source)
case .stream:
NSUnimplemented()
}
}
/// The data drain.
///
/// This depends on what the delegate / completion handler need.
fileprivate func createTransferBodyDataDrain() -> URLSessionTask._TransferState._DataDrain {
switch session.behaviour(for: self) {
case .noDelegate:
return .ignore
case .taskDelegate:
// Data will be forwarded to the delegate as we receive it, we don't
// need to do anything about it.
return .ignore
case .dataCompletionHandler:
// Data needs to be concatenated in-memory such that we can pass it
// to the completion handler upon completion.
return .inMemory(nil)
case .downloadCompletionHandler:
// Data needs to be written to a file (i.e. a download task).
let fileHandle = try! FileHandle(forWritingTo: tempFileURL)
return .toFile(tempFileURL, fileHandle)
}
}
/// Set options on the easy handle to match the given request.
///
/// This performs a series of `curl_easy_setopt()` calls.
fileprivate func configureEasyHandle(for request: URLRequest) {
// At this point we will call the equivalent of curl_easy_setopt()
// to configure everything on the handle. Since we might be re-using
// a handle, we must be sure to set everything and not rely on defaul
// values.
//TODO: We could add a strong reference from the easy handle back to
// its URLSessionTask by means of CURLOPT_PRIVATE -- that would ensure
// that the task is always around while the handle is running.
// We would have to break that retain cycle once the handle completes
// its transfer.
// Behavior Options
easyHandle.set(verboseModeOn: enableLibcurlDebugOutput)
easyHandle.set(debugOutputOn: enableLibcurlDebugOutput, task: self)
easyHandle.set(passHeadersToDataStream: false)
easyHandle.set(progressMeterOff: true)
easyHandle.set(skipAllSignalHandling: true)
// Error Options:
easyHandle.set(errorBuffer: nil)
easyHandle.set(failOnHTTPErrorCode: false)
// Network Options:
guard let url = request.url else { fatalError("No URL in request.") }
easyHandle.set(url: url)
easyHandle.setAllowedProtocolsToHTTPAndHTTPS()
easyHandle.set(preferredReceiveBufferSize: Int.max)
do {
switch (body, try body.getBodyLength()) {
case (.none, _):
set(requestBodyLength: .noBody)
case (_, .some(let length)):
set(requestBodyLength: .length(length))
case (_, .none):
set(requestBodyLength: .unknown)
}
} catch let e {
// Fail the request here.
// TODO: We have multiple options:
// NSURLErrorNoPermissionsToReadFile
// NSURLErrorFileDoesNotExist
internalState = .transferFailed
failWith(errorCode: errorCode(fileSystemError: e), request: request)
return
}
// HTTP Options:
easyHandle.set(followLocation: false)
easyHandle.set(customHeaders: curlHeaders(for: request))
//Options unavailable on Ubuntu 14.04 (libcurl 7.36)
//TODO: Introduce something like an #if
//easyHandle.set(waitForPipeliningAndMultiplexing: true)
//easyHandle.set(streamWeight: priority)
//set the request timeout
//TODO: the timeout value needs to be reset on every data transfer
let s = session as! URLSession
easyHandle.set(timeout: Int(s.configuration.timeoutIntervalForRequest))
easyHandle.set(automaticBodyDecompression: true)
easyHandle.set(requestMethod: request.httpMethod ?? "GET")
if request.httpMethod == "HEAD" {
easyHandle.set(noBody: true)
} else if ((request.httpMethod == "POST") && (request.value(forHTTPHeaderField: "Content-Type") == nil)) {
easyHandle.set(customHeaders: ["Content-Type:application/x-www-form-urlencoded"])
}
}
}
fileprivate extension URLSessionTask {
/// These are a list of headers that should be passed to libcurl.
///
/// Headers will be returned as `Accept: text/html` strings for
/// setting fields, `Accept:` for disabling the libcurl default header, or
/// `Accept;` for a header with no content. This is the format that libcurl
/// expects.
///
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_HTTPHEADER.html
func curlHeaders(for request: URLRequest) -> [String] {
var result: [String] = []
var names = Set<String>()
if let hh = currentRequest?.allHTTPHeaderFields {
hh.forEach {
let name = $0.0.lowercased()
guard !names.contains(name) else { return }
names.insert(name)
if $0.1.isEmpty {
result.append($0.0 + ";")
} else {
result.append($0.0 + ": " + $0.1)
}
}
}
curlHeadersToSet.forEach {
let name = $0.0.lowercased()
guard !names.contains(name) else { return }
names.insert(name)
if $0.1.isEmpty {
result.append($0.0 + ";")
} else {
result.append($0.0 + ": " + $0.1)
}
}
curlHeadersToRemove.forEach {
let name = $0.lowercased()
guard !names.contains(name) else { return }
names.insert(name)
result.append($0 + ":")
}
return result
}
/// Any header values that should be passed to libcurl
///
/// These will only be set if not already part of the request.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_HTTPHEADER.html
var curlHeadersToSet: [(String,String)] {
var result = [("Connection", "keep-alive"),
("User-Agent", userAgentString),
]
if let language = NSLocale.current.languageCode {
result.append(("Accept-Language", language))
}
return result
}
/// Any header values that should be removed from the ones set by libcurl
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_HTTPHEADER.html
var curlHeadersToRemove: [String] {
if case .none = body {
return []
} else {
return ["Expect"]
}
}
}
fileprivate var userAgentString: String = {
// Darwin uses something like this: "xctest (unknown version) CFNetwork/760.4.2 Darwin/15.4.0 (x86_64)"
let info = ProcessInfo.processInfo
let name = info.processName
let curlVersion = CFURLSessionCurlVersionInfo()
//TODO: Should probably use sysctl(3) to get these:
// kern.ostype: Darwin
// kern.osrelease: 15.4.0
//TODO: Use NSBundle to get the version number?
return "\(name) (unknown version) curl/\(curlVersion.major).\(curlVersion.minor).\(curlVersion.patch)"
}()
fileprivate func errorCode(fileSystemError error: Error) -> Int {
func fromCocoaErrorCode(_ code: Int) -> Int {
switch code {
case CocoaError.fileReadNoSuchFile.rawValue:
return NSURLErrorFileDoesNotExist
case CocoaError.fileReadNoPermission.rawValue:
return NSURLErrorNoPermissionsToReadFile
default:
return NSURLErrorUnknown
}
}
switch error {
case let e as NSError where e.domain == NSCocoaErrorDomain:
return fromCocoaErrorCode(e.code)
default:
return NSURLErrorUnknown
}
}
fileprivate extension URLSessionTask {
/// Set request body length.
///
/// An unknown length
func set(requestBodyLength length: URLSessionTask._RequestBodyLength) {
switch length {
case .noBody:
easyHandle.set(upload: false)
easyHandle.set(requestBodyLength: 0)
case .length(let length):
easyHandle.set(upload: true)
easyHandle.set(requestBodyLength: Int64(length))
case .unknown:
easyHandle.set(upload: true)
easyHandle.set(requestBodyLength: -1)
}
}
enum _RequestBodyLength {
case noBody
///
case length(UInt64)
/// Will result in a chunked upload
case unknown
}
}
extension URLSessionTask: _EasyHandleDelegate {
func didReceive(data: Data) -> _EasyHandle._Action {
guard case .transferInProgress(let ts) = internalState else { fatalError("Received body data, but no transfer in progress.") }
guard ts.isHeaderComplete else { fatalError("Received body data, but the header is not complete, yet.") }
notifyDelegate(aboutReceivedData: data)
internalState = .transferInProgress(ts.byAppending(bodyData: data))
return .proceed
}
fileprivate func notifyDelegate(aboutReceivedData data: Data) {
if case .taskDelegate(let delegate) = session.behaviour(for: self),
let dataDelegate = delegate as? URLSessionDataDelegate,
let task = self as? URLSessionDataTask {
// Forward to the delegate:
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
dataDelegate.urlSession(s, dataTask: task, didReceive: data)
}
} else if case .taskDelegate(let delegate) = session.behaviour(for: self),
let downloadDelegate = delegate as? URLSessionDownloadDelegate,
let task = self as? URLSessionDownloadTask {
guard let s = session as? URLSession else { fatalError() }
let fileHandle = try! FileHandle(forWritingTo: tempFileURL)
_ = fileHandle.seekToEndOfFile()
fileHandle.write(data)
self.totalDownloaded += data.count
s.delegateQueue.addOperation {
downloadDelegate.urlSession(s, downloadTask: task, didWriteData: Int64(data.count), totalBytesWritten: Int64(self.totalDownloaded),
totalBytesExpectedToWrite: Int64(self.easyHandle.fileLength))
}
if Int(self.easyHandle.fileLength) == totalDownloaded {
fileHandle.closeFile()
s.delegateQueue.addOperation {
downloadDelegate.urlSession(s, downloadTask: task, didFinishDownloadingTo: self.tempFileURL)
}
}
}
}
func didReceive(headerData data: Data) -> _EasyHandle._Action {
guard case .transferInProgress(let ts) = internalState else { fatalError("Received body data, but no transfer in progress.") }
do {
let newTS = try ts.byAppending(headerLine: data)
internalState = .transferInProgress(newTS)
let didCompleteHeader = !ts.isHeaderComplete && newTS.isHeaderComplete
if didCompleteHeader {
// The header is now complete, but wasn't before.
didReceiveResponse()
}
return .proceed
} catch {
return .abort
}
}
func fill(writeBuffer buffer: UnsafeMutableBufferPointer<Int8>) -> _EasyHandle._WriteBufferResult {
guard case .transferInProgress(let ts) = internalState else { fatalError("Requested to fill write buffer, but transfer isn't in progress.") }
guard let source = ts.requestBodySource else { fatalError("Requested to fill write buffer, but transfer state has no body source.") }
switch source.getNextChunk(withLength: buffer.count) {
case .data(let data):
copyDispatchData(data, infoBuffer: buffer)
let count = data.count
assert(count > 0)
return .bytes(count)
case .done:
return .bytes(0)
case .retryLater:
// At this point we'll try to pause the easy handle. The body source
// is responsible for un-pausing the handle once data becomes
// available.
return .pause
case .error:
return .abort
}
}
func transferCompleted(withErrorCode errorCode: Int?) {
// At this point the transfer is complete and we can decide what to do.
// If everything went well, we will simply forward the resulting data
// to the delegate. But in case of redirects etc. we might send another
// request.
guard case .transferInProgress(let ts) = internalState else { fatalError("Transfer completed, but it wasn't in progress.") }
guard let request = currentRequest else { fatalError("Transfer completed, but there's no currect request.") }
guard errorCode == nil else {
internalState = .transferFailed
failWith(errorCode: errorCode!, request: request)
return
}
guard let response = ts.response else { fatalError("Transfer completed, but there's no response.") }
internalState = .transferCompleted(response: response, bodyDataDrain: ts.bodyDataDrain)
let action = completionAction(forCompletedRequest: request, response: response)
switch action {
case .completeTask:
completeTask()
case .failWithError(let errorCode):
internalState = .transferFailed
failWith(errorCode: errorCode, request: request)
case .redirectWithRequest(let newRequest):
redirectFor(request: newRequest)
}
}
func seekInputStream(to position: UInt64) throws {
// We will reset the body sourse and seek forward.
NSUnimplemented()
}
func updateProgressMeter(with propgress: _EasyHandle._Progress) {
//TODO: Update progress. Note that a single URLSessionTask might
// perform multiple transfers. The values in `progress` are only for
// the current transfer.
}
}
/// State Transfers
extension URLSessionTask {
func completeTask() {
guard case .transferCompleted(response: let response, bodyDataDrain: let bodyDataDrain) = internalState else {
fatalError("Trying to complete the task, but its transfer isn't complete.")
}
self.response = response
//because we deregister the task with the session on internalState being set to taskCompleted
//we need to do the latter after the delegate/handler was notified/invoked
switch session.behaviour(for: self) {
case .taskDelegate(let delegate):
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
delegate.urlSession(s, task: self, didCompleteWithError: nil)
self.internalState = .taskCompleted
}
case .noDelegate:
internalState = .taskCompleted
case .dataCompletionHandler(let completion):
guard case .inMemory(let bodyData) = bodyDataDrain else {
fatalError("Task has data completion handler, but data drain is not in-memory.")
}
guard let s = session as? URLSession else { fatalError() }
var data = Data()
if let body = bodyData {
data = Data(bytes: body.bytes, count: body.length)
}
s.delegateQueue.addOperation {
completion(data, response, nil)
self.internalState = .taskCompleted
self.session = nil
}
case .downloadCompletionHandler(let completion):
guard case .toFile(let url, let fileHandle?) = bodyDataDrain else {
fatalError("Task has data completion handler, but data drain is not a file handle.")
}
guard let s = session as? URLSession else { fatalError() }
//The contents are already written, just close the file handle and call the handler
fileHandle.closeFile()
s.delegateQueue.addOperation {
completion(url, response, nil)
self.internalState = .taskCompleted
self.session = nil
}
}
}
func completeTask(withError error: NSError) {
guard case .transferFailed = internalState else {
fatalError("Trying to complete the task, but its transfer isn't complete / failed.")
}
switch session.behaviour(for: self) {
case .taskDelegate(let delegate):
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
delegate.urlSession(s, task: self, didCompleteWithError: error as Error)
self.internalState = .taskCompleted
}
case .noDelegate:
internalState = .taskCompleted
case .dataCompletionHandler(let completion):
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
completion(nil, nil, error)
self.internalState = .taskCompleted
}
case .downloadCompletionHandler(let completion):
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
completion(nil, nil, error)
self.internalState = .taskCompleted
}
}
}
func failWith(errorCode: Int, request: URLRequest) {
//TODO: Error handling
let userInfo: [String : Any]? = request.url.map {
[
NSURLErrorFailingURLErrorKey: $0,
NSURLErrorFailingURLStringErrorKey: $0.absoluteString,
]
}
let error = NSError(domain: NSURLErrorDomain, code: errorCode, userInfo: userInfo)
completeTask(withError: error)
}
func redirectFor(request: URLRequest) {
//TODO: Should keep track of the number of redirects that this
// request has gone through and err out once it's too large, i.e.
// call into `failWith(errorCode: )` with NSURLErrorHTTPTooManyRedirects
guard case .transferCompleted(response: let response, bodyDataDrain: let bodyDataDrain) = internalState else {
fatalError("Trying to redirect, but the transfer is not complete.")
}
switch session.behaviour(for: self) {
case .taskDelegate(let delegate):
// At this point we need to change the internal state to note
// that we're waiting for the delegate to call the completion
// handler. Then we'll call the delegate callback
// (willPerformHTTPRedirection). The task will then switch out of
// its internal state once the delegate calls the completion
// handler.
//TODO: Should the `public response: URLResponse` property be updated
// before we call delegate API
// `func urlSession(session: session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest?) -> Void)`
// ?
internalState = .waitingForRedirectCompletionHandler(response: response, bodyDataDrain: bodyDataDrain)
// We need this ugly cast in order to be able to support `URLSessionTask.init()`
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
delegate.urlSession(s, task: self, willPerformHTTPRedirection: response, newRequest: request) { [weak self] (request: URLRequest?) in
guard let task = self else { return }
task.workQueue.async {
task.didCompleteRedirectCallback(request)
}
}
}
case .noDelegate, .dataCompletionHandler, .downloadCompletionHandler:
// Follow the redirect.
startNewTransfer(with: request)
}
}
fileprivate func didCompleteRedirectCallback(_ request: URLRequest?) {
guard case .waitingForRedirectCompletionHandler(response: let response, bodyDataDrain: let bodyDataDrain) = internalState else {
fatalError("Received callback for HTTP redirection, but we're not waiting for it. Was it called multiple times?")
}
// If the request is `nil`, we're supposed to treat the current response
// as the final response, i.e. not do any redirection.
// Otherwise, we'll start a new transfer with the passed in request.
if let r = request {
startNewTransfer(with: r)
} else {
internalState = .transferCompleted(response: response, bodyDataDrain: bodyDataDrain)
completeTask()
}
}
}
/// Response processing
fileprivate extension URLSessionTask {
/// Whenever we receive a response (i.e. a complete header) from libcurl,
/// this method gets called.
func didReceiveResponse() {
guard let dt = self as? URLSessionDataTask else { return }
guard case .transferInProgress(let ts) = internalState else { fatalError("Transfer not in progress.") }
guard let response = ts.response else { fatalError("Header complete, but not URL response.") }
switch session.behaviour(for: self) {
case .noDelegate:
break
case .taskDelegate(let delegate as URLSessionDataDelegate):
//TODO: There's a problem with libcurl / with how we're using it.
// We're currently unable to pause the transfer / the easy handle:
// https://curl.haxx.se/mail/lib-2016-03/0222.html
//
// For now, we'll notify the delegate, but won't pause the transfer,
// and we'll disregard the completion handler:
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
delegate.urlSession(s, dataTask: dt, didReceive: response, completionHandler: { _ in
print("warning: Ignoring dispotion from completion handler.")
})
}
case .taskDelegate:
break
case .dataCompletionHandler:
break
case .downloadCompletionHandler:
break
}
}
/// Give the delegate a chance to tell us how to proceed once we have a
/// response / complete header.
///
/// This will pause the transfer.
func askDelegateHowToProceedAfterCompleteResponse(_ response: HTTPURLResponse, delegate: URLSessionDataDelegate) {
// Ask the delegate how to proceed.
// This will pause the easy handle. We need to wait for the
// delegate before processing any more data.
guard case .transferInProgress(let ts) = internalState else { fatalError("Transfer not in progress.") }
internalState = .waitingForResponseCompletionHandler(ts)
let dt = self as! URLSessionDataTask
// We need this ugly cast in order to be able to support `URLSessionTask.init()`
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
delegate.urlSession(s, dataTask: dt, didReceive: response, completionHandler: { [weak self] disposition in
guard let task = self else { return }
task.workQueue.async {
task.didCompleteResponseCallback(disposition: disposition)
}
})
}
}
/// This gets called (indirectly) when the data task delegates lets us know
/// how we should proceed after receiving a response (i.e. complete header).
func didCompleteResponseCallback(disposition: URLSession.ResponseDisposition) {
guard case .waitingForResponseCompletionHandler(let ts) = internalState else { fatalError("Received response disposition, but we're not waiting for it.") }
switch disposition {
case .cancel:
//TODO: Fail the task with NSURLErrorCancelled
NSUnimplemented()
case .allow:
// Continue the transfer. This will unpause the easy handle.
internalState = .transferInProgress(ts)
case .becomeDownload:
/* Turn this request into a download */
NSUnimplemented()
case .becomeStream:
/* Turn this task into a stream task */
NSUnimplemented()
}
}
/// Action to be taken after a transfer completes
enum _CompletionAction {
case completeTask
case failWithError(Int)
case redirectWithRequest(URLRequest)
}
/// What action to take
func completionAction(forCompletedRequest request: URLRequest, response: HTTPURLResponse) -> _CompletionAction {
// Redirect:
if let request = redirectRequest(for: response, fromRequest: request) {
return .redirectWithRequest(request)
}
return .completeTask
}
/// If the response is a redirect, return the new request
///
/// RFC 7231 section 6.4 defines redirection behavior for HTTP/1.1
///
/// - SeeAlso: <https://tools.ietf.org/html/rfc7231#section-6.4>
func redirectRequest(for response: HTTPURLResponse, fromRequest: URLRequest) -> URLRequest? {
//TODO: Do we ever want to redirect for HEAD requests?
func methodAndURL() -> (String, URL)? {
guard
let location = response.value(forHeaderField: .location),
let targetURL = URL(string: location)
else {
// Can't redirect when there's no location to redirect to.
return nil
}
// Check for a redirect:
switch response.statusCode {
//TODO: Should we do this for 300 "Multiple Choices", too?
case 301, 302, 303:
// Change into "GET":
return ("GET", targetURL)
case 307:
// Re-use existing method:
return (fromRequest.httpMethod ?? "GET", targetURL)
default:
return nil
}
}
guard let (method, targetURL) = methodAndURL() else { return nil }
var request = fromRequest
request.httpMethod = method
request.url = targetURL
return request
}
}
fileprivate extension HTTPURLResponse {
/// Type safe HTTP header field name(s)
enum _Field: String {
/// `Location`
/// - SeeAlso: RFC 2616 section 14.30 <https://tools.ietf.org/html/rfc2616#section-14.30>
case location = "Location"
}
func value(forHeaderField field: _Field) -> String? {
return field.rawValue
}
}
public let URLSessionTaskPriorityDefault: Float = 0.5
public let URLSessionTaskPriorityLow: Float = 0.25
public let URLSessionTaskPriorityHigh: Float = 0.75
/*
* An URLSessionDataTask does not provide any additional
* functionality over an URLSessionTask and its presence is merely
* to provide lexical differentiation from download and upload tasks.
*/
open class URLSessionDataTask : URLSessionTask {
}
/*
* An URLSessionUploadTask does not currently provide any additional
* functionality over an URLSessionDataTask. All delegate messages
* that may be sent referencing an URLSessionDataTask equally apply
* to URLSessionUploadTasks.
*/
open class URLSessionUploadTask : URLSessionDataTask {
}
/*
* URLSessionDownloadTask is a task that represents a download to
* local storage.
*/
open class URLSessionDownloadTask : URLSessionTask {
internal var fileLength = -1.0
/* Cancel the download (and calls the superclass -cancel). If
* conditions will allow for resuming the download in the future, the
* callback will be called with an opaque data blob, which may be used
* with -downloadTaskWithResumeData: to attempt to resume the download.
* If resume data cannot be created, the completion handler will be
* called with nil resumeData.
*/
open func cancel(byProducingResumeData completionHandler: (NSData?) -> Void) { NSUnimplemented() }
}
/*
* An URLSessionStreamTask provides an interface to perform reads
* and writes to a TCP/IP stream created via URLSession. This task
* may be explicitly created from an URLSession, or created as a
* result of the appropriate disposition response to a
* -URLSession:dataTask:didReceiveResponse: delegate message.
*
* URLSessionStreamTask can be used to perform asynchronous reads
* and writes. Reads and writes are enquened and executed serially,
* with the completion handler being invoked on the sessions delegate
* queuee. If an error occurs, or the task is canceled, all
* outstanding read and write calls will have their completion
* handlers invoked with an appropriate error.
*
* It is also possible to create InputStream and OutputStream
* instances from an URLSessionTask by sending
* -captureStreams to the task. All outstanding read and writess are
* completed before the streams are created. Once the streams are
* delivered to the session delegate, the task is considered complete
* and will receive no more messsages. These streams are
* disassociated from the underlying session.
*/
open class URLSessionStreamTask : URLSessionTask {
/* Read minBytes, or at most maxBytes bytes and invoke the completion
* handler on the sessions delegate queue with the data or an error.
* If an error occurs, any outstanding reads will also fail, and new
* read requests will error out immediately.
*/
open func readData(ofMinLength minBytes: Int, maxLength maxBytes: Int, timeout: TimeInterval, completionHandler: (NSData?, Bool, NSError?) -> Void) { NSUnimplemented() }
/* Write the data completely to the underlying socket. If all the
* bytes have not been written by the timeout, a timeout error will
* occur. Note that invocation of the completion handler does not
* guarantee that the remote side has received all the bytes, only
* that they have been written to the kernel. */
open func write(data: NSData, timeout: TimeInterval, completionHandler: (NSError?) -> Void) { NSUnimplemented() }
/* -captureStreams completes any already enqueued reads
* and writes, and then invokes the
* URLSession:streamTask:didBecomeInputStream:outputStream: delegate
* message. When that message is received, the task object is
* considered completed and will not receive any more delegate
* messages. */
open func captureStreams() { NSUnimplemented() }
/* Enqueue a request to close the write end of the underlying socket.
* All outstanding IO will complete before the write side of the
* socket is closed. The server, however, may continue to write bytes
* back to the client, so best practice is to continue reading from
* the server until you receive EOF.
*/
open func closeWrite() { NSUnimplemented() }
/* Enqueue a request to close the read side of the underlying socket.
* All outstanding IO will complete before the read side is closed.
* You may continue writing to the server.
*/
open func closeRead() { NSUnimplemented() }
/*
* Begin encrypted handshake. The hanshake begins after all pending
* IO has completed. TLS authentication callbacks are sent to the
* session's -URLSession:task:didReceiveChallenge:completionHandler:
*/
open func startSecureConnection() { NSUnimplemented() }
/*
* Cleanly close a secure connection after all pending secure IO has
* completed.
*/
open func stopSecureConnection() { NSUnimplemented() }
}
/* Key in the userInfo dictionary of an NSError received during a failed download. */
public let URLSessionDownloadTaskResumeData: String = "" // NSUnimplemented
extension URLSession {
static func printDebug(_ text: @autoclosure () -> String) {
guard enableDebugOutput else { return }
debugPrint(text())
}
}
fileprivate let enableLibcurlDebugOutput: Bool = {
return (ProcessInfo.processInfo.environment["URLSessionDebugLibcurl"] != nil)
}()
fileprivate let enableDebugOutput: Bool = {
return (ProcessInfo.processInfo.environment["URLSessionDebug"] != nil)
}()
| apache-2.0 | 5e40d3d5eecb798c46ab99ce6307f5b1 | 41.563505 | 218 | 0.626735 | 5.213568 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/CryptoSwift/Array+Extension.swift | 2 | 2913 | //
// ArrayExtension.swift
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
extension Array {
init(reserveCapacity: Int) {
self = Array<Element>()
self.reserveCapacity(reserveCapacity)
}
var slice: ArraySlice<Element> {
return self[self.startIndex..<self.endIndex]
}
}
extension Array {
/// split in chunks with given chunk size
@available(*, deprecated: 0.8.0, message: "")
public func chunks(size chunksize: Int) -> Array<Array<Element>> {
var words = Array<Array<Element>>()
words.reserveCapacity(count / chunksize)
for idx in stride(from: chunksize, through: count, by: chunksize) {
words.append(Array(self[idx - chunksize..<idx])) // slow for large table
}
let remainder = suffix(count % chunksize)
if !remainder.isEmpty {
words.append(Array(remainder))
}
return words
}
}
extension Array where Element == UInt8 {
public init(hex: String) {
self.init(reserveCapacity: hex.unicodeScalars.lazy.underestimatedCount)
var buffer: UInt8?
var skip = hex.hasPrefix("0x") ? 2 : 0
for char in hex.unicodeScalars.lazy {
guard skip == 0 else {
skip -= 1
continue
}
guard char.value >= 48 && char.value <= 102 else {
removeAll()
return
}
let v: UInt8
let c: UInt8 = UInt8(char.value)
switch c {
case let c where c <= 57:
v = c - 48
case let c where c >= 65 && c <= 70:
v = c - 55
case let c where c >= 97:
v = c - 87
default:
removeAll()
return
}
if let b = buffer {
append(b << 4 | v)
buffer = nil
} else {
buffer = v
}
}
if let b = buffer {
append(b)
}
}
}
| mit | aa99b3d81ac7c5b98a73bdb0d943556f | 33.258824 | 217 | 0.575549 | 4.571429 | false | false | false | false |
cuappdev/tcat-ios | TCAT/Utilities/Phrases.swift | 1 | 8497 | //
// Personality.swift
//
// Created by Matthew Barker on 04/15/18
// Copyright © 2018 cuappdev. All rights reserved.
//
import Foundation
struct Messages {
static let walkingPhrases: [String] = [
"A little exercise never hurt anyone!",
"I hope it's a nice day!",
"Get yourself some Itha-calves"
]
static let shoppingPhrases: [String] = [
"Stock up on some Ramen noodles!",
"Paper or plastic?",
"Pro Tip: Never grocery shop on an empty stomach"
]
// MARK: - Cornell
static let rpcc: [String] = [
"In the kitchen, wrist twistin' like it's Mongo 🎵",
"The best place for 1 AM calzones 😋",
"Hear someone passionately scream out your name 😉"
]
static let bakerFlagpole: [String] = [
"You should try the food on East Campus some time!",
"Grab a snack at Jansen's 🍪",
"Admire how slope-y the slope is."
]
static let statler: [String] = [
"You can check out any time you like, but you can never leave 🎵",
"The Terrace has the best burritos on campus 🌯",
"You think dorms are expensive, try staying a night here!"
]
static let rockefeller: [String] = [
"Voted #3 Best Bus Stop Shelter in Tompkins County",
"Why is it called East Ave.? It doesn't even go east!",
"I bet there's a Rockefeller building on every old campus"
]
static let balch: [String] = [
"Home of the Balch Arch, aka the Barch!",
"Treat yourself with a Louie's milkshake 😋",
"Dorm sweet dorm!"
]
static let schwartz: [String] = [
"Try something new at CTB!",
"I wonder if eHub is crowded... probably",
"Welcome to the hustle and bustle of Collegetown"
]
// MARK: - Ithaca
static let regalCinema: [String] = [
"The trailers always take a half hour anyway...",
"Grab some popcorn! 🍿",
"Don't track your bus while the movie is playing 🙂"
]
static let target: [String] = [
"Do they even sell targets?",
"Can you get tar at target?"
] + Messages.shoppingPhrases
static let mall: [String] = [
"Let's go to the mall... today! 🎵",
"You should play some lazer tag!"
]
static let wegmans: [String] = [
"Make sure you grab a liter of Dr. W!",
"Weg it up."
] + Messages.shoppingPhrases
static let walmart: [String] = [
"But they don't sell any walls...",
"A small mom & pop shop owned by Wally and Marty"
] + Messages.shoppingPhrases
static let chipotle: [String] = [
"Honestly, the new queso is a bit underwhelming...",
"Get there early before they run out of guac!",
"Try getting a quesarito, a secret menu item!"
]
}
class Phrases {
/// Select random string from array
static func selectMessage(from messages: [String]) -> String {
let rand = Int(arc4random_uniform(UInt32(messages.count)))
return messages[rand]
}
}
class LocationPhrases: Phrases {
/// For new places, use: https://boundingbox.klokantech.com set to CSV.
/// For overlapping places, put the smaller one first
static let places: [CustomLocation] = [
CustomLocation(
messages: Messages.rpcc,
minimumLongitude: -76.4780073578,
minimumLatitude: 42.4555571687,
maximumLongitude: -76.4770239162,
maximumLatitude: 42.4562933289
),
CustomLocation(
messages: Messages.bakerFlagpole,
minimumLongitude: -76.4882680195,
minimumLatitude: 42.447154511,
maximumLongitude: -76.4869808879,
maximumLatitude: 42.4482142506
),
CustomLocation(
messages: Messages.statler,
minimumLongitude: -76.4826804461,
minimumLatitude: 42.445607399,
maximumLongitude: -76.4816523295,
maximumLatitude: 42.4467569576
),
CustomLocation(
messages: Messages.rockefeller,
minimumLongitude: -76.4828309704,
minimumLatitude: 42.4493108267,
maximumLongitude: -76.4824479047,
maximumLatitude: 42.44969019
),
CustomLocation(
messages: Messages.balch,
minimumLongitude: -76.4811291114,
minimumLatitude: 42.4526837484,
maximumLongitude: -76.4789034578,
maximumLatitude: 42.4536103104
),
CustomLocation(
messages: Messages.schwartz,
minimumLongitude: -76.4855623082,
minimumLatitude: 42.4424106249,
maximumLongitude: -76.4849883155,
maximumLatitude: 42.4428654009
),
CustomLocation(
messages: Messages.target,
minimumLongitude: -76.4927489222,
minimumLatitude: 42.4847167857,
maximumLongitude: -76.4889960764,
maximumLatitude: 42.4858172457
),
CustomLocation(
messages: Messages.regalCinema,
minimumLongitude: -76.493338437,
minimumLatitude: 42.4838963076,
maximumLongitude: -76.4914179754,
maximumLatitude: 42.4846716949
),
CustomLocation(
messages: Messages.mall,
minimumLongitude: -76.493291,
minimumLatitude: 42.480977,
maximumLongitude: -76.488651,
maximumLatitude: 42.48597
),
CustomLocation(
messages: Messages.wegmans,
minimumLongitude: -76.5114533069,
minimumLatitude: 42.4336357432,
maximumLongitude: -76.5093075397,
maximumLatitude: 42.4362012905
),
CustomLocation(
messages: Messages.walmart,
minimumLongitude: -76.5148997155,
minimumLatitude: 42.4265752766,
maximumLongitude: -76.511709343,
maximumLatitude: 42.4284506244
),
CustomLocation(
messages: Messages.chipotle,
minimumLongitude: -76.5082565033,
minimumLatitude: 42.4297004932,
maximumLongitude: -76.5080904931,
maximumLatitude: 42.4302749214
)
]
/// Return a string from the first location within the range of coordinates. Otherwise, return nil.
static func generateMessage(latitude: Double, longitude: Double) -> String? {
for place in places {
if place.isWithinRange(latitude: latitude, longitude: longitude) {
return selectMessage(from: place.messages)
}
}
return nil
}
}
class WalkingPhrases: Phrases {
/// If route is solely a walking direction, return message. Otherwise, return nil.
static func generateMessage(route: Route) -> String? {
let messages = Messages.walkingPhrases
return route.isRawWalkingRoute() ? selectMessage(from: messages) : nil
}
}
// MARK: - Utility Classes & Functions
/// A custom location the a user searches for. Coordinates used for matching.
struct CustomLocation: Equatable {
/// Messages related to location
var messages: [String]
// MARK: - Bounding Box Variables
/// The bottom left corner longitude value for the location's bounding box
var maximumLongitude: Double
/// The bottom right corner latitude value for the location's bounding box
var minimumLatitude: Double
/// The top right corner longitude value for the location's bounding box
var minimumLongitude: Double
/// The top left corner latitude value for the location's bounding box
var maximumLatitude: Double
init(messages: [String], minimumLongitude: Double, minimumLatitude: Double, maximumLongitude: Double, maximumLatitude: Double) {
self.messages = messages
self.minimumLongitude = minimumLongitude
self.minimumLatitude = minimumLatitude
self.maximumLongitude = maximumLongitude
self.maximumLatitude = maximumLatitude
}
/// Returns true is passed in coordinates are within the range of the location
func isWithinRange(latitude: Double, longitude: Double) -> Bool {
let isLatInRange = minimumLatitude <= latitude && latitude <= maximumLatitude
let isLongInRange = minimumLongitude <= longitude && longitude <= maximumLongitude
return isLatInRange && isLongInRange
}
}
| mit | b89634563c5f7c6d7527bf3e1bc2476f | 32.070313 | 132 | 0.61682 | 4.388802 | false | false | false | false |
uShip/iOSIdeaFlow | IdeaFlow/IdeaFlowEvent+AssociatedValues.swift | 1 | 2434 | //
// IdeaFlowEvent+Stuff.swift
// IdeaFlow
//
// Created by Matt Hayes on 8/14/15.
// Copyright (c) 2015 uShip. All rights reserved.
//
import Foundation
import UIKit
import CoreData
extension IdeaFlowEvent
{
enum EventType: String
{
case Productivity = "Productivity"
case Troubleshooting = "Troubleshooting"
case Learning = "Learning"
case Rework = "Rework"
case Pause = "Pause"
case Unknown = "Unknown"
init(int: Int32)
{
switch int
{
case 1:
self = .Productivity
case 2:
self = .Troubleshooting
case 3:
self = .Learning
case 4:
self = .Rework
case 5:
self = .Pause
default:
self = .Unknown
}
}
func intValue() -> Int32
{
switch (self)
{
case .Unknown:
return 0
case .Productivity:
return 1
case .Troubleshooting:
return 2
case .Learning:
return 3
case .Rework:
return 4
case .Pause:
return 5
}
}
}
func eventTypeName() -> String
{
return EventType(int: eventType.intValue).rawValue
}
func eventTypeColor() -> UIColor
{
switch EventType(int: eventType.intValue)
{
case .Productivity:
return UIColor.lightGrayColor()
case .Troubleshooting:
return UIColor.redColor()
case .Learning:
return UIColor.blueColor()
case .Rework:
return UIColor.orangeColor()
case .Pause:
return UIColor.blackColor()
default:
return UIColor.magentaColor()
}
}
class func csvColumnNames() -> String
{
return "startTimeStamp, eventType, identifier"
}
func asCSV() -> String
{
let eventTypeString = EventType(int: eventType.intValue).rawValue
let startTimeStampString = "\(startTimeStamp)"
//TODO: include notes
// for note in notes
// {
//
// }
return "\(startTimeStampString),\(eventTypeString),\(identifier)"
}
} | gpl-3.0 | 7d9ebd83ecfccc377c2d72fac0238b11 | 22.190476 | 73 | 0.483566 | 5.070833 | false | false | false | false |
ccrama/Slide-iOS | Slide for Reddit/NSDate+Extensions.swift | 1 | 678 | //
// NSDate+Extensions.swift
// Slide for Reddit
//
// Created by Jonathan Cole on 11/14/18.
// Copyright © 2018 Haptic Apps. All rights reserved.
//
import Foundation
extension Date {
var timeAgoString: String? {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.maximumUnitCount = 1
formatter.allowedUnits = [.year, .month, .day, .hour, .minute, .second]
guard let timeString = formatter.string(from: self, to: Date()) else {
return nil
}
let formatString = NSLocalizedString("%@ ago", comment: "")
return String(format: formatString, timeString)
}
}
| apache-2.0 | cdac2829dd248a6e8427292d30568fe9 | 26.08 | 79 | 0.635155 | 4.367742 | false | false | false | false |
pollarm/MondoKit | MondoKitTestApp/Accounts/AccountDetailsViewController.swift | 1 | 9320 | //
// AccountDetailsViewController.swift
// MondoKit
//
// Created by Mike Pollard on 24/01/2016.
// Copyright © 2016 Mike Pollard. All rights reserved.
//
import UIKit
import MondoKit
class AccountDetailsViewController: UIViewController {
@IBOutlet private var balanceLabel : UILabel!
@IBOutlet private var spentLabel : UILabel!
private var transactionsController : AccountTransactionsViewController!
var account : MondoAccount?
private var balance : MondoAccountBalance? {
didSet {
if let balance = balance {
let currencyFormatter = NSNumberFormatter()
currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyAccountingStyle
let locale = NSLocale.currentLocale()
let symbol = locale.displayNameForKey(NSLocaleCurrencySymbol, value: balance.currency)
currencyFormatter.currencySymbol = symbol
let currency = CurrencyFormatter(isoCode: balance.currency)
balanceLabel?.text = currency.stringFromMinorUnitsValue(balance.balance)
spentLabel?.text = currency.stringFromMinorUnitsValue(balance.spendToday)
}
else {
balanceLabel?.text = ""
spentLabel?.text = ""
}
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let account = account {
title = account.description
MondoAPI.instance.getBalanceForAccount(account) { [weak self] (balance, error) in
self?.balance = balance
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let transactionsController = segue.destinationViewController as? AccountTransactionsViewController {
transactionsController.account = account
self.transactionsController = transactionsController
transactionsController.selectionHandler = { _ in
self.performSegueWithIdentifier("showDetails", sender: nil)
}
}
if let detailsController = segue.destinationViewController as? TransactionDetailController,
transaction = transactionsController.selectedTransaction {
detailsController.transaction = transaction
}
}
}
class TransactionCell : UITableViewCell {
@IBOutlet private var descriptionLabel : UILabel!
@IBOutlet private var categoryLabel : UILabel!
@IBOutlet private var amountLabel : UILabel!
override func awakeFromNib() {
super.awakeFromNib()
amountLabel.font = UIFont.monospacedDigitSystemFontOfSize(amountLabel.font.pointSize, weight: UIFontWeightRegular)
}
}
class AccountTransactionsViewController : UIViewController {
@IBOutlet private var tableView : UITableView!
var account : MondoAccount!
var selectionHandler : ((selected: MondoTransaction) -> Void)?
var selectedTransaction : MondoTransaction? {
if let dataSourceWithTransactions = tableView.dataSource as? DataSourceWithTransactions,
indexPath = tableView.indexPathForSelectedRow,
transaction = dataSourceWithTransactions.transactionAtIndexPath(indexPath) {
return transaction
}
else {
return nil
}
}
private let transactionsDataSource = TransactionsDataSource()
private let feedDataSource = FeedDataSource()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = transactionsDataSource
tableView.delegate = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
transactionsDataSource.loadTransactionsForAccount(account) { [weak self] _ in
self?.tableView.reloadData()
}
}
@IBAction func segmentedValueChanged(segmentedControl: UISegmentedControl) {
if segmentedControl.selectedSegmentIndex == 0 {
tableView.dataSource = transactionsDataSource
transactionsDataSource.loadTransactionsForAccount(account) { [weak self] _ in
self?.tableView.reloadData()
}
}
else {
tableView.dataSource = feedDataSource
feedDataSource.loadFeedForAccount(account) { [weak self] _ in
self?.tableView.reloadData()
}
}
}
}
protocol DataSourceWithTransactions {
func transactionAtIndexPath(indexPath : NSIndexPath) -> MondoTransaction?
}
private class FeedDataSource : NSObject, UITableViewDataSource, DataSourceWithTransactions {
private static let FeedCellIdentifier = "TransactionCell2"
private var feedItems : [MondoFeedItem]?
private func loadFeedForAccount(account: MondoAccount, completion: ()->Void) {
MondoAPI.instance.listFeedForAccount(account) { [weak self] (items, error) in
if let items = items {
self?.feedItems = items
}
completion()
}
}
private func transactionAtIndexPath(indexPath : NSIndexPath) -> MondoTransaction? {
return feedItems?[indexPath.row].transaction
}
@objc func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return feedItems?.count ?? 0
}
@objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(FeedDataSource.FeedCellIdentifier, forIndexPath: indexPath) as! TransactionCell
if let feedItem = feedItems?[indexPath.row] {
if let transaction = feedItem.transaction {
if let m = transaction.merchant, case .Expanded(let merchant) = m {
cell.descriptionLabel.text = merchant.name
}
else {
cell.descriptionLabel.text = transaction.description
}
cell.categoryLabel.text = transaction.category.rawValue
let currency = CurrencyFormatter(isoCode: transaction.currency)
cell.amountLabel.text = currency.stringFromMinorUnitsValue(transaction.amount)
}
else {
cell.descriptionLabel.text = ""
cell.categoryLabel.text = feedItem.type.rawValue
cell.amountLabel.text = ""
}
}
return cell
}
}
private class TransactionsDataSource : NSObject, UITableViewDataSource, DataSourceWithTransactions {
private static let TransactionCellIdentifier = "TransactionCell2"
private var transactions : [MondoTransaction]?
private func loadTransactionsForAccount(account: MondoAccount, completion: ()->Void) {
MondoAPI.instance.listTransactionsForAccount(account, expand: "merchant") { [weak self] (transactions, error) in
if let transactions = transactions {
self?.transactions = transactions
}
completion()
}
}
private func transactionAtIndexPath(indexPath : NSIndexPath) -> MondoTransaction? {
return transactions?[indexPath.row]
}
@objc func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return transactions?.count ?? 0
}
@objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(TransactionsDataSource.TransactionCellIdentifier, forIndexPath: indexPath) as! TransactionCell
if let transaction = transactions?[indexPath.row] {
if let m = transaction.merchant, case .Expanded(let merchant) = m {
cell.descriptionLabel.text = merchant.name
}
else {
cell.descriptionLabel.text = transaction.description
}
cell.categoryLabel.text = transaction.category.rawValue
let currency = CurrencyFormatter(isoCode: transaction.currency)
cell.amountLabel.text = currency.stringFromMinorUnitsValue(transaction.amount)
}
return cell
}
}
extension AccountTransactionsViewController : UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let dataSourceWithTransactions = tableView.dataSource as? DataSourceWithTransactions,
transaction = dataSourceWithTransactions.transactionAtIndexPath(indexPath) {
selectionHandler?(selected: transaction)
}
}
}
| mit | 610dee21f70b82cdaa12223719d81f58 | 33.902622 | 157 | 0.633222 | 6.118844 | false | false | false | false |
Stitch7/Instapod | Instapod/Podcast/PodcastsViewController.swift | 1 | 15727 | //
// PodcastsViewController.swift
// Instapod
//
// Created by Christopher Reitz on 03.09.16.
// Copyright © 2016 Christopher Reitz. All rights reserved.
//
import UIKit
import CoreData
class PodcastsViewController: UIViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource, PodcastListDelegate, FeedUpdaterDelegate, FeedImporterDelegate, CoreDataContextInjectable {
// MARK: - Properties
var podcasts = [Podcast]()
var pageViewController: UIPageViewController?
var editingMode: PodcastListEditingMode = .off
var viewMode: PodcastListViewMode = .tableView
var tableViewController: PodcastsTableViewController?
var collectionViewController: PodcastsCollectionViewController?
var toolbarLabel: UILabel?
var updater: FeedUpdater?
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
podcasts = loadData(context: coreDataContext)
configureAppNavigationBar()
configureNavigationBar()
configureToolbar()
configureTableViewController()
configureCollectionViewController()
configurePageViewController()
updater = initFeedupdater(podcasts: podcasts)
}
override func viewWillAppear(_ animated: Bool) {
guard
let playerVC: PlayerViewController = UIStoryboard(name: "Main", bundle: nil).instantiate(),
let navVC = self.navigationController,
navVC.popupContent == nil
else { return }
navVC.presentPopupBar(withContentViewController: playerVC, openPopup: false, animated: false) {
navVC.dismissPopupBar(animated: false)
}
}
func initFeedupdater(podcasts: [Podcast]) -> FeedUpdater {
let updater = FeedUpdater(podcasts: podcasts)
updater.delegates.addDelegate(self)
if let tableVC = tableViewController {
updater.delegates.addDelegate(tableVC)
}
if let collectionVC = collectionViewController {
updater.delegates.addDelegate(collectionVC)
}
return updater
}
func configureNavigationBar() {
title = "Podcasts" // TODO: i18n
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Edit", // TODO: i18n
style: .plain,
target: self,
action: #selector(editButtonPressed))
let switchViewButton = UIButton(type: .custom)
let sortButtonImage = PodcastListViewMode.collectionView.image
switchViewButton.setImage(sortButtonImage, for: UIControlState())
switchViewButton.addTarget(self,
action: #selector(switchViewButtonPressed),
for: .touchUpInside)
switchViewButton.frame = CGRect(x: 0, y: 0, width: 22, height: 22)
let switchViewBarButton = UIBarButtonItem(customView: switchViewButton)
navigationItem.rightBarButtonItem = switchViewBarButton
}
func configureToolbar() {
configureToolbarItems()
configureToolbarApperance()
}
func configureToolbarItems() {
let spacer: () -> UIBarButtonItem = {
return UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
target: self,
action: nil)
}
let addButton = UIBarButtonItem(barButtonSystemItem: .add,
target: self,
action: #selector(addFeedButtonPressed))
let labelView = UILabel(frame: CGRect(x: 0, y: 0, width: 220, height: 22))
labelView.font = UIFont.systemFont(ofSize: 12)
labelView.textAlignment = .center
let label = UIBarButtonItem(customView: labelView)
self.toolbarLabel = labelView
updateToolbarLabel()
let sortButtonView = UIButton(type: .custom)
let sortButtonImage = UIImage(named: "sortButtonDesc")?.withRenderingMode(.alwaysTemplate)
sortButtonView.setImage(sortButtonImage, for: UIControlState())
sortButtonView.addTarget(self,
action: #selector(sortButtonPressed),
for: .touchUpInside)
sortButtonView.frame = CGRect(x: 0, y: 0, width: 22, height: 22)
let sortButton = UIBarButtonItem(customView: sortButtonView)
toolbarItems = [addButton, spacer(), label, spacer(), sortButton]
}
func updateToolbarLabel() {
toolbarLabel?.text = "\(podcasts.count) Subscriptions" // TODO: i18n
}
func configureToolbarApperance() {
guard let navController = navigationController else { return }
let screenWidth = UIScreen.main.bounds.size.width
let toolbarBarColor = ColorPalette.Background.withAlphaComponent(0.9)
let toolbar = navController.toolbar
toolbar?.setBackgroundImage(UIImage(), forToolbarPosition: .bottom, barMetrics: .default)
toolbar?.backgroundColor = toolbarBarColor
toolbar?.clipsToBounds = true
let toolbarView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: screenWidth, height: 20.0))
toolbarView.backgroundColor = toolbarBarColor
navController.view.addSubview(toolbarView)
navController.isToolbarHidden = false
}
func configureTableViewController() {
tableViewController = storyboard?.instantiate()
tableViewController?.podcasts = podcasts
tableViewController?.delegate = self
}
func configureCollectionViewController() {
collectionViewController = storyboard?.instantiate()
collectionViewController?.podcasts = podcasts
collectionViewController?.delegate = self
}
func configurePageViewController() {
guard let
tableVC = self.tableViewController,
let pageVC: UIPageViewController = storyboard?.instantiate()
else { return }
pageVC.delegate = self
pageVC.dataSource = self
pageVC.view.backgroundColor = UIColor.groupTableViewBackground
pageVC.setViewControllers([tableVC], direction: .forward, animated: false, completion: nil)
addChildViewController(pageVC)
view.addSubview(pageVC.view)
view.sendSubview(toBack: pageVC.view)
pageVC.didMove(toParentViewController: self)
pageViewController = pageVC
}
// MARK: - Database
func reload() {
podcasts = loadData(context: coreDataContext)
tableViewController?.podcasts = podcasts
tableViewController?.tableView.reloadData()
updateToolbarLabel()
}
func loadData(context: NSManagedObjectContext) -> [Podcast] {
var podcasts = [Podcast]()
do {
let fetchRequest: NSFetchRequest<NSManagedObject> = NSFetchRequest(entityName: "Podcast")
fetchRequest.sortDescriptors = [
NSSortDescriptor(key: "sortIndex", ascending: true)
]
let managedPodcasts = try context.fetch(fetchRequest) as! [PodcastManagedObject]
for managedPodcast in managedPodcasts {
podcasts.append(Podcast(managedObject: managedPodcast))
}
context.reset()
}
catch {
print("Error: Could not load podcasts from db: \(error)")
}
return podcasts
}
// MARK: - PodcastListDelegate
func updateFeeds() {
updater?.update()
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func podcastSelected(_ podcast: Podcast) {
performSegue(withIdentifier: "ShowEpisodes", sender: podcast)
}
// MARK: - FeedUpdaterDelegate
func feedUpdater(_ feedupdater: FeedUpdater, didFinishWithEpisode foundEpisode: Episode, ofPodcast podcast: Podcast) {
var affected: Podcast?
let newPodcast = podcast
for oldPodcast in podcasts {
if oldPodcast.uuid == newPodcast.uuid {
affected = oldPodcast
break
}
}
guard let affectedPodcast = affected else { return }
do {
guard let
coordinator = coreDataContext.persistentStoreCoordinator,
let id = affectedPodcast.id,
let objectID = coordinator.managedObjectID(forURIRepresentation: id as URL),
let managedPodcast = try coreDataContext.existingObject(with: objectID) as? PodcastManagedObject
else { return }
let newEpisode = foundEpisode.createEpisode(fromContext: coreDataContext)
managedPodcast.addObject(newEpisode, forKey: "episodes")
try coreDataContext.save()
reload()
} catch {
print("Could bot save new episode \(error)")
}
}
func feedUpdater(_ feedupdater: FeedUpdater, didFinishWithNumberOfEpisodes numberOfEpisodes: Int) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
var hearts = ""; for _ in 0..<numberOfEpisodes { hearts += "♥️" }; print(hearts)
}
// MARK: - FeedImporterDelegate
func feedImporter(_ feedImporter: FeedImporter, didFinishWithFeed feed: Podcast) {
do {
let _ = feed.createPodcast(fromContext: coreDataContext)
try coreDataContext.save()
coreDataContext.reset()
} catch {
print("Error: Could not save podcasts to db: \(error)")
}
reload()
}
func feedImporterDidFinishWithAllFeeds(_ feedImporter: FeedImporter) {
loadingHUD(show: false)
}
// MARK: - Actions
func editButtonPressed(_ sender: UIBarButtonItem) {
guard let
tableVC = tableViewController,
let collectionVC = collectionViewController
else { return }
editingMode.nextValue()
switch editingMode {
case .on:
let attrs = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)]
sender.setTitleTextAttributes(attrs, for: UIControlState())
sender.title = "Done" // TODO: i18n
case .off:
let attrs = [NSFontAttributeName: UIFont.systemFont(ofSize: 18)]
sender.setTitleTextAttributes(attrs, for: UIControlState())
sender.title = "Edit" // TODO: i18n
}
switch viewMode {
case .tableView:
tableVC.setEditing(editingMode.boolValue, animated: true)
case .collectionView:
collectionVC.setEditing(editingMode.boolValue, animated: true)
}
}
func switchViewButtonPressed(_ sender: UIButton) {
guard let
pageVC = pageViewController,
let tableVC = tableViewController,
let collectionVC = collectionViewController
else { return }
var vc: UIViewController
var direction: UIPageViewControllerNavigationDirection
switch viewMode {
case .tableView:
vc = collectionVC
direction = .forward
case .collectionView:
vc = tableVC
direction = .reverse
}
pageVC.setViewControllers([vc], direction: direction, animated: true) { completed in
if completed {
self.switchViewButtonImage()
self.viewMode.nextValue()
}
}
}
func switchViewButtonImage() {
guard let
switchViewBarButton = self.navigationItem.rightBarButtonItem,
let switchViewButton = switchViewBarButton.customView as? UIButton
else { return }
switchViewButton.setImage(self.viewMode.image, for: UIControlState())
self.navigationItem.rightBarButtonItem = switchViewBarButton
}
func addFeedButtonPressed(_ sender: UIBarButtonItem) {
let alertController = UIAlertController(
title: "Add new Podcast", // TODO: i18n
message: nil,
preferredStyle: .alert
)
var feedUrlTextField: UITextField?
alertController.addTextField { (textField) in
textField.placeholder = "Feed URL" // TODO: i18n
feedUrlTextField = textField
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in // TODO: i18n
guard
let path = Bundle.main.path(forResource: "subscriptions", ofType: "opml"),
let data = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
else {
print("Failed loading subscriptions.opml")
return
}
self.loadingHUD(show: true, dimsBackground: true)
let datasource = FeedImporterDatasourceAEXML(data: data)
let feedImporter = FeedImporter(datasource: datasource)
feedImporter.delegates.addDelegate(self)
feedImporter.start()
}
let okAction = UIAlertAction(title: "Add", style: .default) { (action) in // TODO: i18n
guard let _ = feedUrlTextField?.text else { return }
// self.tableView.reloadData()
}
alertController.addAction(cancelAction)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
// alertController.view.tintColor = ColorPalette.
}
func sortButtonPressed(_ sender: UIBarButtonItem) {
let alertController = UIAlertController(title: nil,
message: "Sort by", // TODO: i18n
preferredStyle: .actionSheet)
let titleAction = UIAlertAction(title: "Title", style: .default) { (action) in // TODO: i18n
print("Sort by last abc")
}
alertController.addAction(titleAction)
let unplayedAction = UIAlertAction(title: "Unplayed", style: .default) { (action) in // TODO: i18n
print("Sort by last unplayed")
}
alertController.addAction(unplayedAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) // TODO: i18n
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
// MARK: - UIPageViewControllerDelegate
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed {
switchViewButtonImage()
viewMode.nextValue()
}
}
// MARK: - UIPageViewControllerDataSource
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if viewController.isKind(of: PodcastsTableViewController.self) { return nil }
return tableViewController
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if viewController.isKind(of: PodcastsCollectionViewController.self) { return nil }
return collectionViewController
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let podcast = sender as? Podcast else { return }
guard let episodesVC = segue.destination as? EpisodesViewController else { return }
// episodesVC.hidesBottomBarWhenPushed = true
episodesVC.podcast = podcast
}
}
| mit | e1cb3bce86b49d9bb303687b5b2ac9e1 | 36.255924 | 201 | 0.631535 | 5.725419 | false | false | false | false |
google-research/swift-tfp | Sources/LibTFP/ConstraintTransforms.swift | 1 | 12810 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
////////////////////////////////////////////////////////////////////////////////
// MARK: Simple transforms
// Normalizes names of variables
func alphaNormalize(_ constraints: [Constraint]) -> [Constraint] {
var rename = DefaultDict<Var, Var>(withDefault: makeVariableGenerator())
return constraints.map{ substitute($0, using: { rename[$0].expr }) }
}
// Returns a list of constraints in the same order, but with no single
// constraint appearing twice (only the first occurence is retained.
public func deduplicate(_ constraints: [Constraint]) -> [Constraint] {
struct BoolExprPair: Hashable { let expr: BoolExpr; let assumption: BoolExpr }
var seen = Set<BoolExprPair>()
// TODO: prefer asserted constraints to implicit constraints
return constraints.compactMap {
let key = BoolExprPair(expr: $0.expr, assumption: $0.assumption)
guard !seen.contains(key) else { return nil }
seen.insert(key)
return $0
}
}
// Preprocess constraints to find the weakest assumption under which a
// variable is used. This is useful, because it allows us to e.g. inline
// equalities when we have a guarantee that all users of a variable have
// to satisfy the same assumption that the equality does.
func computeWeakestAssumptions(_ constraints: [Constraint]) -> [Var: BoolExpr] {
var userAssumptions = DefaultDict<Var, Set<BoolExpr>>{ _ in [] }
for constraint in constraints {
switch constraint {
case let .expr(expr, assuming: cond, _, _):
let _ = substitute(expr, using: {
userAssumptions[$0].insert(cond)
return nil
})
}
}
var weakestAssumption: [Var: BoolExpr] = [:]
for entry in userAssumptions.dictionary {
let assumptions = entry.value.sorted(by: { $0.description < $1.description })
var currentWeakest = assumptions[0]
for assumption in assumptions.suffix(from: 1) {
if assumption =>? currentWeakest {
continue
} else if currentWeakest =>? assumption {
currentWeakest = assumption
} else {
currentWeakest = .true
}
}
weakestAssumption[entry.key] = currentWeakest
}
return weakestAssumption
}
// Tries to iteratively go over expressions, simplify them, and in case they
// equate a variable with an expression, inline the definition of this variable
// into all following constraints.
func inline(_ originalConstraints: [Constraint],
canInline: (Constraint) -> Bool = { $0.complexity <= 20 },
simplifying shouldSimplify: Bool = true) -> [Constraint] {
// NB: It is safe to reuse this accross iterations.
let weakestAssumption = computeWeakestAssumptions(originalConstraints)
let simplifyExpr: (Expr) -> Expr = shouldSimplify ? simplify : { $0 }
let simplifyConstraint: (Constraint) -> Constraint = shouldSimplify ? simplify : { $0 }
var constraints = originalConstraints
while true {
var inlined: [Var: Expr] = [:]
var inlineForbidden = Set<Var>()
func subst(_ v: Var) -> Expr? {
if let replacement = inlined[v] {
return replacement
}
inlineForbidden.insert(v)
return nil
}
func tryInline(_ v: Var, _ originalExpr: Expr, assuming cond: BoolExpr) -> Bool {
guard !inlined.keys.contains(v),
weakestAssumption[v]! =>? cond else { return false }
let expr = simplifyExpr(substitute(originalExpr, using: subst))
// NB: The substitution above might have added the variable to inlineForbidden
guard !inlineForbidden.contains(v) else { return false }
inlined[v] = expr
return true
}
constraints = constraints.compactMap { constraint in
if canInline(constraint) {
let cond = constraint.assumption
switch constraint.expr {
case let .listEq(.var(v), expr),
let .listEq(expr, .var(v)):
if tryInline(.list(v), .list(expr), assuming: cond) { return nil }
case let .intEq(.var(v), expr),
let .intEq(expr, .var(v)):
if tryInline(.int(v), .int(expr), assuming: cond) { return nil }
case let .boolEq(.var(v), expr),
let .boolEq(expr, .var(v)):
if tryInline(.bool(v), .bool(expr), assuming: cond) { return nil }
default: break
}
}
return simplifyConstraint(substitute(constraint, using: subst))
}
if inlined.isEmpty { break }
}
return constraints
}
// Assertion instantiations produce patterns of the form:
// b4 = <cond>, b4
// This function tries to find those and inline the conditions.
public func inlineBoolVars(_ constraints: [Constraint]) -> [Constraint] {
return inline(constraints, canInline: {
switch $0 {
case .expr(.boolEq(.var(_), _), assuming: _, _, _): return true
case .expr(.boolEq(_, .var(_)), assuming: _, _, _): return true
default: return false
}
}, simplifying: false)
}
////////////////////////////////////////////////////////////////////////////////
// MARK: - Simplification
// Simplifies the constraint without any additional context. For example
// a subexpression [1, 2, 3][1] will get replaced by 2.
public func simplify(_ constraint: Constraint) -> Constraint {
switch constraint {
case let .expr(expr, assuming: cond, origin, stack):
return .expr(simplify(expr), assuming: simplify(cond), origin, stack)
}
}
public func simplify(_ genericExpr: Expr) -> Expr {
switch genericExpr {
case let .int(expr): return .int(simplify(expr))
case let .list(expr): return .list(simplify(expr))
case let .bool(expr): return .bool(simplify(expr))
case let .compound(expr): return .compound(simplify(expr))
}
}
public func simplify(_ expr: IntExpr) -> IntExpr {
func binaryOp(_ clhs: IntExpr, _ crhs: IntExpr,
_ f: (Int, Int) -> Int,
_ constructor: (IntExpr, IntExpr) -> IntExpr,
leftIdentity: Int? = nil,
rightIdentity: Int? = nil) -> IntExpr {
let (lhs, rhs) = (simplify(clhs), simplify(crhs))
if case let .literal(lhsValue) = lhs,
case let .literal(rhsValue) = rhs {
return .literal(f(lhsValue, rhsValue))
}
if let id = leftIdentity, case .literal(id) = lhs {
return rhs
}
if let id = rightIdentity, case .literal(id) = rhs {
return lhs
}
return constructor(lhs, rhs)
}
switch expr {
case .hole(_): return expr
case .var(_): return expr
case .literal(_): return expr
case let .length(of: clist):
let list = simplify(clist)
if case let .literal(elems) = list {
return .literal(elems.count)
}
return .length(of: list)
case let .element(offset, of: clist):
let list = simplify(clist)
if case let .literal(elems) = list {
let normalOffset = offset < 0 ? offset + elems.count : offset
if 0 <= normalOffset, normalOffset < elems.count,
let elem = elems[normalOffset] {
return elem
}
}
return .element(offset, of: list)
case let .add(clhs, crhs):
return binaryOp(clhs, crhs, +, IntExpr.add, leftIdentity: 0, rightIdentity: 0)
case let .sub(clhs, crhs):
return binaryOp(clhs, crhs, -, IntExpr.sub, rightIdentity: 0)
case let .mul(clhs, crhs):
return binaryOp(clhs, crhs, *, IntExpr.mul, leftIdentity: 1, rightIdentity: 1)
case let .div(clhs, crhs):
return binaryOp(clhs, crhs, /, IntExpr.div, rightIdentity: 1)
}
}
public func simplify(_ expr: ListExpr) -> ListExpr {
struct Break: Error {}
func tryBroadcast(_ lhs: [IntExpr?], _ rhs: [IntExpr?]) throws -> [IntExpr?] {
let paddedLhs = Array(repeating: 1, count: max(rhs.count - lhs.count, 0)) + lhs
let paddedRhs = Array(repeating: 1, count: max(lhs.count - rhs.count, 0)) + rhs
return try zip(paddedLhs, paddedRhs).map{ (l, r) in
if (l == nil || l == 1) { return r }
if (r == nil || r == 1) { return l }
if (r == l) { return l }
throw Break()
}
}
switch expr {
case .var(_): return expr
case let .literal(subexprs): return .literal(subexprs.map{ $0.map(simplify) })
case let .broadcast(clhs, crhs):
let (lhs, rhs) = (simplify(clhs), simplify(crhs))
if case let .literal(lhsElems) = lhs,
case let .literal(rhsElems) = rhs {
if let resultElems = try? tryBroadcast(lhsElems, rhsElems) {
return .literal(resultElems)
}
}
return .broadcast(lhs, rhs)
}
}
public func simplify(_ expr: BoolExpr) -> BoolExpr {
switch expr {
case .true: return expr
case .false: return expr
case .var(_): return expr
case let .not(.not(subexpr)): return simplify(subexpr)
case let .not(subexpr): return .not(simplify(subexpr))
// TODO(#20): Collapse and/or trees and filter out true/false
case let .and(subexprs): return .and(subexprs.map(simplify))
case let .or(subexprs): return .or(subexprs.map(simplify))
case let .intEq(lhs, rhs): return .intEq(simplify(lhs), simplify(rhs))
case let .intGt(lhs, rhs): return .intGt(simplify(lhs), simplify(rhs))
case let .intGe(lhs, rhs): return .intGe(simplify(lhs), simplify(rhs))
case let .intLt(lhs, rhs): return .intLt(simplify(lhs), simplify(rhs))
case let .intLe(lhs, rhs): return .intLe(simplify(lhs), simplify(rhs))
case let .listEq(lhs, rhs): return .listEq(simplify(lhs), simplify(rhs))
case let .boolEq(lhs, rhs): return .boolEq(simplify(lhs), simplify(rhs))
}
}
public func simplify(_ expr: CompoundExpr) -> CompoundExpr {
switch expr {
case let .tuple(subexprs): return .tuple(subexprs.map{ $0.map(simplify) })
}
}
////////////////////////////////////////////////////////////////////////////////
// MARK: - Complexity measure
// Returns an approximate measure of how hard to read the constraint will be when
// printed. In most cases it's equivalent to simply computing the number of nodes in
// the expression tree, but some rules don't conform to this specification.
extension Constraint {
var complexity: Int {
switch self {
case let .expr(expr, assuming: _, _, _): return expr.complexity
}
}
}
extension BoolExpr {
var complexity: Int {
switch self {
case .true: return 1
case .false: return 1
case .var(_): return 1
case let .not(subexpr): return 1 + subexpr.complexity
case let .and(subexprs): fallthrough
case let .or(subexprs): return 1 + subexprs.reduce(0, { $0 + $1.complexity })
case let .intEq(lhs, rhs): fallthrough
case let .intGt(lhs, rhs): fallthrough
case let .intGe(lhs, rhs): fallthrough
case let .intLt(lhs, rhs): fallthrough
case let .intLe(lhs, rhs):
return 1 + lhs.complexity + rhs.complexity
case let .listEq(lhs, rhs):
return 1 + lhs.complexity + rhs.complexity
case let .boolEq(lhs, rhs):
return 1 + lhs.complexity + rhs.complexity
}
}
}
extension IntExpr {
var complexity: Int {
switch self {
case .hole(_): return 1
case .var(_): return 1
case .literal(_): return 1
// NB: We don't add one, because both .rank and indexing does not increase
// the subjective complexity of the expression significantly
case let .length(of: list): return list.complexity
case let .element(_, of: list): return list.complexity
case let .add(lhs, rhs): fallthrough
case let .sub(lhs, rhs): fallthrough
case let .mul(lhs, rhs): fallthrough
case let .div(lhs, rhs):
return 1 + lhs.complexity + rhs.complexity
}
}
}
extension ListExpr {
var complexity: Int {
switch self {
case .var(_): return 1
// FIXME: If we changed the way we print list literals to e.g. explode one
// element per line then we could take a max instead of a sum here.
case let .literal(subexprs): return 1 + subexprs.reduce(0, { $0 + ($1?.complexity ?? 1) })
case let .broadcast(lhs, rhs): return 1 + lhs.complexity + rhs.complexity
}
}
}
extension CompoundExpr {
var complexity: Int {
switch self {
case let .tuple(elements): return 1 + elements.reduce(0, { $0 + ($1?.complexity ?? 1) })
}
}
}
extension Expr {
var complexity: Int {
switch self {
case let .int(expr): return expr.complexity
case let .bool(expr): return expr.complexity
case let .list(expr): return expr.complexity
case let .compound(expr): return expr.complexity
}
}
}
| apache-2.0 | 1fd46ae1317ae90f241893f245c25660 | 34.983146 | 94 | 0.642311 | 3.943966 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureForm/Sources/FeatureFormDomain/FormValidation.swift | 1 | 1379 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
import ToolKit
extension FormQuestion {
var isValid: Bool {
let isValid: Bool
switch type {
case .singleSelection:
let selections = children.filter { $0.checked == true }
isValid = selections.count == 1 && selections.hasAllValidAnswers
case .multipleSelection:
let selections = children.filter { $0.checked == true }
isValid = selections.count >= 1 && selections.hasAllValidAnswers
case .openEnded:
if let regex = regex {
isValid = input.emptyIfNil ~= regex
} else {
isValid = input.isNilOrEmpty
}
}
return isValid
}
}
extension FormAnswer {
var isValid: Bool {
var isValid = checked == true || input.isNotNilOrEmpty
if let children = children {
isValid = isValid && children.hasAllValidAnswers
}
if let regex = regex {
isValid = isValid && input.emptyIfNil ~= regex
}
return isValid
}
}
extension Array where Element == FormAnswer {
var hasAllValidAnswers: Bool {
allSatisfy(\.isValid)
}
}
extension Array where Element == FormQuestion {
public var isValidForm: Bool {
allSatisfy(\.isValid)
}
}
| lgpl-3.0 | b48b42dcbc5a48a294a0c22a6284db10 | 24.518519 | 76 | 0.584906 | 4.869258 | false | false | false | false |
proxpero/Placeholder | Placeholder/FileStorage.swift | 1 | 1256 | //
// FileStorage.swift
// Placeholder
//
// Created by Todd Olsen on 4/8/17.
// Copyright © 2017 proxpero. All rights reserved.
//
import Foundation
/// A class to manage storing and retrieving data from disk.
public struct FileStorage {
// The base URL.
private let baseURL: URL
/// Initialize with a baseURL, which has a default value of the document
/// directory in the user domain mask.
init(baseURL: URL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)) {
self.baseURL = baseURL
}
/// A subscript for reading and writing data at the address represented
/// by `key`. Setting a value of `nil` clears the cache for that `key`.
subscript(key: String) -> Data? {
get {
let url = baseURL.appendingPathComponent(key)
return try? Data(contentsOf: url)
}
set {
let url = baseURL.appendingPathComponent(key)
if let newValue = newValue {
_ = try? newValue.write(to: url)
} else {
// If `newValue` is `nil` then clear the cache.
_ = try? FileManager.default.removeItem(at: url)
}
}
}
}
| mit | c7ac3c9468baf06c4ed89756e6ab8d7b | 30.375 | 136 | 0.601594 | 4.327586 | false | false | false | false |
cubixlabs/GIST-Framework | GISTFramework/Classes/BaseClasses/BaseUIStackView.swift | 1 | 2855 | //
// BaseUIStackView.swift
// GISTFramework
//
// Created by Shoaib Abdul on 13/02/2017.
// Copyright © 2017 Social Cubix. All rights reserved.
//
import UIKit
/// BaseUIStackView is a subclass of UIStackView and implements BaseView. It has some extra proporties and support for SyncEngine.
@available(iOS 9.0, *)
open class BaseUIStackView: UIStackView, BaseView {
//MARK: - Properties
/// Overriden property to update spacing with ratio.
open override var spacing:CGFloat {
get {
return super.spacing;
}
set {
super.spacing = GISTUtility.convertToRatio(newValue, sizedForIPad: sizeForIPad);
}
}
/// Flag for whether to resize the values for iPad.
@IBInspectable open var sizeForIPad:Bool = GIST_CONFIG.sizeForIPad;
/// Background color key from Sync Engine.
@IBInspectable open var bgColorStyle:String? = nil {
didSet {
self.backgroundColor = SyncedColors.color(forKey: bgColorStyle);
}
}
/// Width of View Border.
@IBInspectable open var border:Int = 0 {
didSet {
if let borderCStyle:String = borderColorStyle {
self.addBorder(SyncedColors.color(forKey: borderCStyle), width: border)
}
}
}
/// Border color key from Sync Engine.
@IBInspectable open var borderColorStyle:String? = nil {
didSet {
if let borderCStyle:String = borderColorStyle {
self.addBorder(SyncedColors.color(forKey: borderCStyle), width: border)
}
}
}
/// Corner Radius for View.
@IBInspectable open var cornerRadius:Int = 0 {
didSet {
self.addRoundedCorners(GISTUtility.convertToRatio(CGFloat(cornerRadius), sizedForIPad: sizeForIPad));
}
}
/// Flag for making circle/rounded view.
@IBInspectable open var rounded:Bool = false {
didSet {
if rounded {
self.addRoundedCorners();
}
}
}
/// Flag for Drop Shadow.
@IBInspectable open var hasDropShadow:Bool = false {
didSet {
if (hasDropShadow) {
self.addDropShadow();
} else {
// TO HANDLER
}
}
}
//MARK: - Overridden Methods
/// Overridden method to setup/ initialize components.
override open func awakeFromNib() {
super.awakeFromNib();
} //F.E.
/// Overridden methed to update layout.
override open func layoutSubviews() {
super.layoutSubviews();
if rounded {
self.addRoundedCorners();
}
if (hasDropShadow) {
self.addDropShadow();
}
} //F.E.
} //CLS END
| agpl-3.0 | a3429cf459989aacb78dcf48efe377d3 | 25.924528 | 130 | 0.571479 | 4.91222 | false | false | false | false |
sora0077/RelayoutKit | RelayoutKit/TableView/TableController+Cell.swift | 1 | 9025 | //
// TableController+Cell.swift
// RelayoutKit
//
// Created by 林達也 on 2015/09/10.
// Copyright © 2015年 jp.sora0077. All rights reserved.
//
import Foundation
//MARK: Cell
extension TableController {
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let row = sections[indexPath.section].internalRows[indexPath.row]
row.setIndexPath(indexPath)
row.setSuperview(tableView)
return row.estimatedSize.height
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.size.height
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = sections[indexPath.section].internalRows[indexPath.row]
let clazz = row.dynamicType
let identifier = clazz.identifier
if !registeredCells.contains(identifier) {
clazz.register(tableView)
registeredCells.insert(identifier)
}
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
updateCell(cell, indexPath: indexPath, row: row)
return cell
}
private func updateCell(cell: UITableViewCell, indexPath: NSIndexPath, row: TableRowProtocolInternal) {
cell.indentationLevel = row.indentationLevel
cell.indentationWidth = row.indentationWidth
cell.accessoryType = row.accessoryType
cell.selectionStyle = row.selectionStyle
cell.selected = row.selected
cell.relayoutKit_row = Wrapper(row)
row.setRenderer(cell)
row.setSuperview(tableView)
row.setIndexPath(indexPath)
row.componentUpdate()
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.relayoutKit_defaultSeparatorInset == nil {
cell.relayoutKit_defaultSeparatorInset = Wrapper(cell.separatorInset)
}
if let row = cell.relayoutKit_row?.value {
func applySeparatorStyle(style: UITableViewCellSeparatorStyle) {
switch style {
case .None:
cell.separatorInset.right = tableView.frame.width - cell.separatorInset.left
default:
if let inset = row.separatorInset {
cell.separatorInset = inset
} else if let inset = cell.relayoutKit_defaultSeparatorInset?.value {
cell.separatorInset = inset
}
}
}
let prev = sections[indexPath.section].internalRows[safe: indexPath.row - 1]
let next = sections[indexPath.section].internalRows[safe: indexPath.row + 1]
if let style = prev?.nextSeparatorStyle {
applySeparatorStyle(style)
} else if let style = next?.previousSeparatorStyle {
applySeparatorStyle(style)
} else {
applySeparatorStyle(row.separatorStyle)
}
row.willDisplayCell()
}
}
func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let row = cell.relayoutKit_row?.value {
row.didEndDisplayingCell()
row.setRenderer(nil)
cell.relayoutKit_row = nil
}
}
func tableView(tableView: UITableView, indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.indentationLevel
}
}
extension TableController {
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.willSelect(indexPath)
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let row = sections[indexPath.section].internalRows[indexPath.row]
row.didSelect(indexPath)
if !row.selected {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
func tableView(tableView: UITableView, willDeselectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.willDeselect(indexPath)
}
func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
let row = sections[indexPath.section].internalRows[indexPath.row]
row.accessoryButtonTapped(indexPath)
}
}
//MARK: - Editing Table Rows
extension TableController {
func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.shouldIndentWhileEditing()
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.editingStyle
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.editActions()
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let row = sections[indexPath.section].internalRows[indexPath.row]
row.commit(editingStyle: editingStyle)
}
func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.titleForDeleteConfirmationButton
}
func tableView(tableView: UITableView, willBeginEditingRowAtIndexPath indexPath: NSIndexPath) {
let row = sections[indexPath.section].internalRows[indexPath.row]
row.willBeginEditingRow()
}
}
private extension TableController {
func row(indexPath: NSIndexPath) -> TableRowProtocolInternal {
return sections[indexPath.section].internalRows[indexPath.row]
}
func row(safe indexPath: NSIndexPath) -> TableRowProtocolInternal? {
return sections[safe: indexPath.section]?.internalRows[safe: indexPath.row]
}
}
extension TableController {
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.canMove
}
func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath {
let source = row(sourceIndexPath)
if let destination = row(safe: proposedDestinationIndexPath) {
if source.canMove && destination.canMove {
if source.willMove(to: destination) && destination.willMove(from: source) {
return proposedDestinationIndexPath
}
}
} else {
if source.canMove {
return proposedDestinationIndexPath
}
}
return sourceIndexPath
}
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
let source = row(sourceIndexPath)
sections[sourceIndexPath.section].removeAtIndex(sourceIndexPath.row)
sections[destinationIndexPath.section].insert(source, atIndex: destinationIndexPath.row)
for (idx, row) in sections[sourceIndexPath.section].internalRows.enumerate() {
let indexPath = NSIndexPath(forRow: idx, inSection: sourceIndexPath.section)
row.setIndexPath(indexPath)
}
for (idx, row) in sections[destinationIndexPath.section].internalRows.enumerate() {
let indexPath = NSIndexPath(forRow: idx, inSection: destinationIndexPath.section)
row.setIndexPath(indexPath)
}
}
}
private func pindexPath(indexPath: NSIndexPath) -> String {
return "indexPath(row: \(indexPath.row), section: \(indexPath.section))"
}
| mit | ac9a13d78a5fd6e0ed421b32a1cda8e9 | 36.882353 | 193 | 0.661823 | 5.746335 | false | false | false | false |
Limon-O-O/Lego | Modules/Door/Door/WelcomeViewController.swift | 1 | 6715 | //
// WelcomeViewController.swift
// Door
//
// Created by Limon.F on 19/2/2017.
// Copyright © 2017 Limon.F. All rights reserved.
//
import UIKit
import EggKit
import RxSwift
import MonkeyKing
class WelcomeViewController: UIViewController {
var innateParams: [String: Any] = [:]
@IBOutlet private weak var loginButton: UIButton!
@IBOutlet private weak var registerButton: UIButton!
@IBOutlet private weak var weiboButton: UIButton!
@IBOutlet private weak var qqButton: UIButton!
@IBOutlet private weak var wechatButton: UIButton!
@IBOutlet private weak var phoneButton: UIButton!
@IBOutlet private weak var loginWayLabel: UILabel!
fileprivate var showStatusBar = false
fileprivate let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
title = "Welcome"
loginWayLabel.text = "select_login_way".egg.localized
weiboButton.setTitle("button.weibo_login".egg.localized, for: .normal)
qqButton.setTitle("button.qq_login".egg.localized, for: .normal)
wechatButton.setTitle("button.wechat_login".egg.localized, for: .normal)
phoneButton.setTitle("button.phone_login".egg.localized, for: .normal)
registerButton.setTitle("button.register_by_phone".egg.localized, for: .normal)
loginButton.rx.tap
.throttle(0.3, scheduler: MainScheduler.instance)
.subscribe(onNext: { [weak self] in
let accessToken = "002dS5ZGOoM5BCd78614ac1dJnIUWD"
let userID: Int = 007
DoorUserDefaults.accessToken = accessToken
DoorUserDefaults.userID = userID
let alertController = UIAlertController(title: nil, message: "登录成功", preferredStyle: .alert)
let action: UIAlertAction = UIAlertAction(title: "确定", style: .default) { _ in
let deliverParams: [String: Any] = [
"accessToken": accessToken,
"userID": userID
]
// 通过闭包回调出去,这样不用依赖 Main Project
(self?.innateParams["callbackAction"] as? ([String: Any]) -> Void)?(deliverParams)
}
alertController.addAction(action)
self?.present(alertController, animated: true, completion: nil)
})
.addDisposableTo(disposeBag)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let navigationBarHidden = (innateParams["navigationBarHidden"] as? Bool) ?? true
showStatusBar = !navigationBarHidden
navigationController?.setNavigationBarHidden(navigationBarHidden, animated: true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 0.2) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
override var prefersStatusBarHidden : Bool {
return !showStatusBar
}
deinit {
print("WelcomeViewController Deinit")
}
}
// MARK: - Segue
extension WelcomeViewController: SegueHandlerType {
enum SegueIdentifier: String {
case showLogin
case showPhoneNumberPicker
}
@IBAction private func register(_ sender: UIButton) {
performSegue(withIdentifier: .showPhoneNumberPicker, sender: nil)
}
@IBAction private func login(_ sender: UIButton) {
performSegue(withIdentifier: .showLogin, sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
showStatusBar = true
setNeedsStatusBarAppearanceUpdate()
switch segueIdentifier(for: segue) {
case .showLogin:
let vc = segue.destination as? LoginViewController
vc?.innateParams = innateParams
case .showPhoneNumberPicker:
let vc = segue.destination as? PhoneNumberPickerViewController
vc?.innateParams = innateParams
}
}
}
// MARK: - Actions
extension WelcomeViewController {
private func login(platform: LoginPlatform, token: String, openID: String) {
UserProvider.request(.login(["": ""]))
.mapObject(type: LoginUser.self)
.observeOn(MainScheduler.asyncInstance)
.subscribe(onNext: { success in
}, onError: { error in
})
.addDisposableTo(disposeBag)
}
@IBAction private func qqLogin(_ sender: UIButton) {
let account = MonkeyKing.Account.qq(appID: Configure.Account.QQ.appID)
MonkeyKing.registerAccount(account)
MonkeyKing.oauth(for: .qq) { [weak self] info, response, error in
guard
let unwrappedInfo = info,
let token = unwrappedInfo["access_token"] as? String,
let openID = unwrappedInfo["openid"] as? String else {
return
}
self?.login(platform: .qq, token: token, openID: openID)
}
}
@IBAction private func weiboLogin(_ sender: UIButton) {
let account = MonkeyKing.Account.weibo(appID: Configure.Account.Weibo.appID, appKey: Configure.Account.Weibo.appKey, redirectURL: Configure.Account.Weibo.redirectURL)
MonkeyKing.registerAccount(account)
MonkeyKing.oauth(for: .weibo) { [weak self] info, response, error in
// App or Web: token & userID
guard
let unwrappedInfo = info,
let token = (unwrappedInfo["access_token"] as? String) ?? (unwrappedInfo["accessToken"] as? String),
let userID = (unwrappedInfo["uid"] as? String) ?? (unwrappedInfo["userID"] as? String) else {
return
}
self?.login(platform: .weibo, token: token, openID: userID)
}
}
@IBAction private func weChatLogin(_ sender: UIButton) {
let account = MonkeyKing.Account.weChat(appID: Configure.Account.Wechat.appID, appKey: Configure.Account.Wechat.appKey)
MonkeyKing.registerAccount(account)
MonkeyKing.oauth(for: .weChat) { [weak self] oauthInfo, response, error in
guard
let token = oauthInfo?["access_token"] as? String,
let userID = oauthInfo?["openid"] as? String else {
return
}
self?.login(platform: .weChat, token: token, openID: userID)
}
}
}
| mit | 6c80d27a123f2a8a4a890559fba6f7b4 | 31.546341 | 174 | 0.623651 | 4.942222 | false | false | false | false |
cburrows/swift-protobuf | Sources/SwiftProtobuf/Message+JSONAdditions.swift | 1 | 5646 | // Sources/SwiftProtobuf/Message+JSONAdditions.swift - JSON format primitive types
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Extensions to `Message` to support JSON encoding/decoding.
///
// -----------------------------------------------------------------------------
import Foundation
/// JSON encoding and decoding methods for messages.
extension Message {
/// Returns a string containing the JSON serialization of the message.
///
/// Unlike binary encoding, presence of required fields is not enforced when
/// serializing to JSON.
///
/// - Returns: A string containing the JSON serialization of the message.
/// - Parameters:
/// - options: The JSONEncodingOptions to use.
/// - Throws: `JSONEncodingError` if encoding fails.
public func jsonString(
options: JSONEncodingOptions = JSONEncodingOptions()
) throws -> String {
if let m = self as? _CustomJSONCodable {
return try m.encodedJSONString(options: options)
}
let data = try jsonUTF8Data(options: options)
return String(data: data, encoding: String.Encoding.utf8)!
}
/// Returns a Data containing the UTF-8 JSON serialization of the message.
///
/// Unlike binary encoding, presence of required fields is not enforced when
/// serializing to JSON.
///
/// - Returns: A Data containing the JSON serialization of the message.
/// - Parameters:
/// - options: The JSONEncodingOptions to use.
/// - Throws: `JSONEncodingError` if encoding fails.
public func jsonUTF8Data(
options: JSONEncodingOptions = JSONEncodingOptions()
) throws -> Data {
if let m = self as? _CustomJSONCodable {
let string = try m.encodedJSONString(options: options)
let data = string.data(using: String.Encoding.utf8)! // Cannot fail!
return data
}
var visitor = try JSONEncodingVisitor(type: Self.self, options: options)
visitor.startObject(message: self)
try traverse(visitor: &visitor)
visitor.endObject()
return visitor.dataResult
}
/// Creates a new message by decoding the given string containing a
/// serialized message in JSON format.
///
/// - Parameter jsonString: The JSON-formatted string to decode.
/// - Parameter options: The JSONDecodingOptions to use.
/// - Throws: `JSONDecodingError` if decoding fails.
public init(
jsonString: String,
options: JSONDecodingOptions = JSONDecodingOptions()
) throws {
try self.init(jsonString: jsonString, extensions: nil, options: options)
}
/// Creates a new message by decoding the given string containing a
/// serialized message in JSON format.
///
/// - Parameter jsonString: The JSON-formatted string to decode.
/// - Parameter extensions: An ExtensionMap for looking up extensions by name
/// - Parameter options: The JSONDecodingOptions to use.
/// - Throws: `JSONDecodingError` if decoding fails.
public init(
jsonString: String,
extensions: ExtensionMap? = nil,
options: JSONDecodingOptions = JSONDecodingOptions()
) throws {
if jsonString.isEmpty {
throw JSONDecodingError.truncated
}
if let data = jsonString.data(using: String.Encoding.utf8) {
try self.init(jsonUTF8Data: data, extensions: extensions, options: options)
} else {
throw JSONDecodingError.truncated
}
}
/// Creates a new message by decoding the given `Data` containing a
/// serialized message in JSON format, interpreting the data as UTF-8 encoded
/// text.
///
/// - Parameter jsonUTF8Data: The JSON-formatted data to decode, represented
/// as UTF-8 encoded text.
/// - Parameter options: The JSONDecodingOptions to use.
/// - Throws: `JSONDecodingError` if decoding fails.
public init(
jsonUTF8Data: Data,
options: JSONDecodingOptions = JSONDecodingOptions()
) throws {
try self.init(jsonUTF8Data: jsonUTF8Data, extensions: nil, options: options)
}
/// Creates a new message by decoding the given `Data` containing a
/// serialized message in JSON format, interpreting the data as UTF-8 encoded
/// text.
///
/// - Parameter jsonUTF8Data: The JSON-formatted data to decode, represented
/// as UTF-8 encoded text.
/// - Parameter extensions: The extension map to use with this decode
/// - Parameter options: The JSONDecodingOptions to use.
/// - Throws: `JSONDecodingError` if decoding fails.
public init(
jsonUTF8Data: Data,
extensions: ExtensionMap? = nil,
options: JSONDecodingOptions = JSONDecodingOptions()
) throws {
self.init()
try jsonUTF8Data.withUnsafeBytes { (body: UnsafeRawBufferPointer) in
// Empty input is valid for binary, but not for JSON.
guard body.count > 0 else {
throw JSONDecodingError.truncated
}
var decoder = JSONDecoder(source: body, options: options,
messageType: Self.self, extensions: extensions)
if decoder.scanner.skipOptionalNull() {
if let customCodable = Self.self as? _CustomJSONCodable.Type,
let message = try customCodable.decodedFromJSONNull() {
self = message as! Self
} else {
throw JSONDecodingError.illegalNull
}
} else {
try decoder.decodeFullObject(message: &self)
}
if !decoder.scanner.complete {
throw JSONDecodingError.trailingGarbage
}
}
}
}
| apache-2.0 | 6a19e6f4b4cd9a23171f071727e43351 | 36.64 | 82 | 0.67074 | 4.744538 | false | false | false | false |
stowy/LayoutKit | Sources/Views/StackView.swift | 5 | 5831 | // Copyright 2016 LinkedIn Corp.
// 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.
import UIKit
/**
A view that stacks its subviews along a single axis.
It is similar to UIStackView except that it uses StackLayout instead of Auto Layout, which means layout is much faster.
Although StackView is faster than UIStackView, it still does layout on the main thread.
If you want to get the full benefit of LayoutKit, use StackLayout directly.
Unlike UIStackView, if you position StackView with Auto Layout, you must call invalidateIntrinsicContentSize on that StackView
whenever any of its subviews' intrinsic content sizes change (e.g. changing the text of a UILabel that is positioned by the StackView).
Otherwise, Auto Layout won't recompute the layout of the StackView.
Subviews MUST implement sizeThatFits so StackView can allocate space correctly.
If a subview uses Auto Layout, then the subview may implement sizeThatFits by calling systemLayoutSizeFittingSize.
*/
open class StackView: UIView {
/// The axis along which arranged views are stacked.
open let axis: Axis
/**
The distance in points between adjacent edges of sublayouts along the axis.
For Distribution.EqualSpacing, this is a minimum spacing. For all other distributions it is an exact spacing.
*/
open let spacing: CGFloat
/// The distribution of space along the stack's axis.
open let distribution: StackLayoutDistribution
/// The distance that the arranged views are inset from the stack view. Defaults to 0.
open let contentInsets: UIEdgeInsets
/// The stack's alignment inside its parent.
open let alignment: Alignment
/// The stack's flexibility.
open let flexibility: Flexibility?
private var arrangedSubviews: [UIView] = []
public init(axis: Axis,
spacing: CGFloat = 0,
distribution: StackLayoutDistribution = .leading,
contentInsets: UIEdgeInsets = .zero,
alignment: Alignment = .fill,
flexibility: Flexibility? = nil) {
self.axis = axis
self.spacing = spacing
self.distribution = distribution
self.contentInsets = contentInsets
self.alignment = alignment
self.flexibility = flexibility
super.init(frame: .zero)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
Adds a subview to the stack.
Subviews MUST implement sizeThatFits so StackView can allocate space correctly.
If a subview uses Auto Layout, then the subview can implement sizeThatFits by calling systemLayoutSizeFittingSize.
*/
open func addArrangedSubviews(_ subviews: [UIView]) {
arrangedSubviews.append(contentsOf: subviews)
for subview in subviews {
addSubview(subview)
}
invalidateIntrinsicContentSize()
setNeedsLayout()
}
/**
Deletes all subviews from the stack.
*/
open func removeArrangedSubviews() {
for subview in arrangedSubviews {
subview.removeFromSuperview()
}
arrangedSubviews.removeAll()
invalidateIntrinsicContentSize()
setNeedsLayout()
}
open override func sizeThatFits(_ size: CGSize) -> CGSize {
return stackLayout.measurement(within: size).size
}
open override var intrinsicContentSize: CGSize {
return sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
}
open override func layoutSubviews() {
stackLayout.measurement(within: bounds.size).arrangement(within: bounds).makeViews(in: self)
}
private var stackLayout: Layout {
let sublayouts = arrangedSubviews.map { view -> Layout in
return ViewLayout(view: view)
}
let stack = StackLayout(
axis: axis,
spacing: spacing,
distribution: distribution,
alignment: alignment,
flexibility: flexibility,
sublayouts: sublayouts,
config: nil)
return InsetLayout(insets: contentInsets, sublayout: stack)
}
}
/// Wraps a UIView so that it conforms to the Layout protocol.
private struct ViewLayout: ConfigurableLayout {
let needsView = true
let view: UIView
let viewReuseId: String? = nil
func measurement(within maxSize: CGSize) -> LayoutMeasurement {
let size = view.sizeThatFits(maxSize)
return LayoutMeasurement(layout: self, size: size, maxSize: maxSize, sublayouts: [])
}
func arrangement(within rect: CGRect, measurement: LayoutMeasurement) -> LayoutArrangement {
return LayoutArrangement(layout: self, frame: rect, sublayouts: [])
}
func makeView() -> UIView {
return view
}
func configure(view: UIView) {
// Nothing to configure.
}
var flexibility: Flexibility {
let horizontal = flexForAxis(.horizontal)
let vertical = flexForAxis(.vertical)
return Flexibility(horizontal: horizontal, vertical: vertical)
}
private func flexForAxis(_ axis: UILayoutConstraintAxis) -> Flexibility.Flex {
switch view.contentHuggingPriority(for: .horizontal) {
case UILayoutPriorityRequired:
return nil
case let priority:
return -Int32(priority)
}
}
}
| apache-2.0 | b94a62f068637d819f1584c6abc4cc99 | 34.339394 | 136 | 0.682559 | 5.281703 | false | false | false | false |
linhaosunny/smallGifts | 小礼品/小礼品/Classes/Module/Me/Chat/ViewModels/VoiceChatCellViewModel.swift | 1 | 1324 | //
// VoiceChatCellViewModel.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/4/28.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
fileprivate let voiceCellWidth:CGFloat = 80.0
fileprivate let voiceCellHeight:CGFloat = 45.0
class VoiceChatCellViewModel: BaseChatCellViewModel {
var voiceStatus:RecordStatus?
var voicebackImage:UIImage?
var voicebackHightLightImage:UIImage?
var voiceTimeLabelFont:UIFont?
var voiceTimeLabelText:String?
init(withVoiceMessage msg: VoiceMessage) {
super.init(withMsgModel: msg as MessageModel)
if viewLocation == .right {
voicebackImage = #imageLiteral(resourceName: "SenderTextNodeBkg")
voicebackHightLightImage = #imageLiteral(resourceName: "SenderTextNodeBkgHL")
}
else{
voicebackImage = #imageLiteral(resourceName: "ReceiverTextNodeBkg")
voicebackHightLightImage = #imageLiteral(resourceName: "ReceiverTextNodeBkgHL")
}
voiceTimeLabelFont = fontSize14
voiceTimeLabelText = String(format: "%.0lf\"\n", msg.time)
voiceStatus = msg.status
viewFrame.contentSize = CGSize(width: voiceCellWidth, height: voiceCellHeight)
viewFrame.height += viewFrame.contentSize.height
}
}
| mit | 98321d539b1d00354ccb29bee551591d | 31.575 | 91 | 0.689946 | 4.57193 | false | false | false | false |
jay0420/jigsaw | JKPinTu-Swift/Util/Extension/UIKit/JKUIViewExtension.swift | 1 | 1405 | //
// JKUIViewExtension.swift
// JKPinTu-Swift
//
// Created by bingjie-macbookpro on 15/12/15.
// Copyright © 2015年 Bingjie. All rights reserved.
//
import Foundation
import UIKit
extension UIView
{
public func left()->CGFloat{
return self.frame.origin.x
}
public func right()->CGFloat{
return self.frame.origin.x + self.frame.size.width
}
public func top()->CGFloat{
return self.frame.origin.y
}
public func bottom()->CGFloat{
return self.frame.origin.y + self.frame.size.height
}
public func width()->CGFloat{
return self.frame.size.width
}
public func height()->CGFloat{
return self.frame.size.height
}
public func addTapGesturesTarget(_ target:AnyObject, action selector:Selector){
self.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer.init(target: target, action: selector)
tapGesture.numberOfTapsRequired = 1
self.addGestureRecognizer(tapGesture)
}
public func removeAllSubviews(){
while (self.subviews.count != 0)
{
let child = self.subviews.last
child!.removeFromSuperview()
}
}
public func makeSubviewRandomColor(){
for view in self.subviews{
view.backgroundColor = UIColor.randomColor()
}
}
}
| mit | 32cabbb36574760fc7d1341a5c73dd10 | 22.762712 | 86 | 0.620542 | 4.522581 | false | false | false | false |
symentis/Corridor | Sources/Resolver.swift | 1 | 5551 | //
// Resolver.swift
// Corridor
//
// Created by Elmar Kretzer on 06.08.17.
// Copyright © 2017 Elmar Kretzer. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// --------------------------------------------------------------------------------
// MARK: - Resolver
//
// TL;DR:
// The resolver resolves access to the context for a given Source and Context.
// --------------------------------------------------------------------------------
/// Will be created with
/// - a generic type `S` a.k.a the Source that resolves.
/// - a generic type `C` a.k.a the Context protocol that we are resolving from.
public struct Resolver<S, C>: CustomStringConvertible where S: HasContext {
/// The typealias for the Context Protocol in your app.
public typealias Context = C
/// The typeaias for the Source that holds the resolver.
public typealias Source = S
/// The stored context which is used to access the injected types.
public private(set) var context: C
/// Inititializer needs a actual implementation of the Context protocol.
/// example usage:
///
/// static var mock: Resolver<Self, AppContext> {
/// return Resolver(context: MockContext())
/// }
///
public init(context: C) {
self.context = context
}
/// A public function to swap the Context for e.g. mocks
public mutating func apply(_ context: C) {
self.context = context
}
// --------------------------------------------------------------------------------
// MARK: - Subscripting a.k.a Resolving
//
// TL:DR;
// Subscripts are used to provide a config-ish access to injected values
// on a protocol level.
//
// The examples will use HasInstanceAppContext
// which is a protocol to pin the Context typealias for convenience.
// protocol HasInstanceAppContext: HasInstanceContext where Self.Context == AppContext {}
// --------------------------------------------------------------------------------
/// Subscripting any regular Type from the Context.
/// This basic subscribt can be seen as an eqivalent to extract on a Coreader
/// Example usage:
///
/// extension HasInstanceAppContext {
///
/// var now: Date {
/// return resolve[\.now]
/// }
/// }
///
public subscript<D>(_ k: KeyPath<C, D>) -> D {
return context[keyPath: k]
}
/// Subscripting an Type that conforms to `HasInstanceContext` from the Context.
/// This subscript can be seen as an eqivalent to extend on a Coreader
/// This will be called when the Type D implements HasInstanceContext,
/// which will result in passing on the context.
/// Example usage:
///
/// extension HasInstanceAppContext {
///
/// /// Api itself implements HasInstanceAppContext
/// var api: Api {
/// return resolve[\.api]
/// }
/// }
///
public subscript<D>(_ k: KeyPath<C, D>) -> D where D: HasInstanceContext, D.Context == C {
var d = context[keyPath: k]
d.resolve.apply(context)
return d
}
/// Subscripting an Type that conforms to `HasStaticContext` from the Context.
/// This subscript can be seen as an eqivalent to extend on a Coreader
/// This will be called when the Type D implements HasStaticContext,
/// which will result in passing on the context.
public subscript<D>(_ k: KeyPath<C, D>) -> D where D: HasStaticContext, D.Context == C {
D.resolve.apply(context)
return context[keyPath: k]
}
/// Subscripting an Type that conforms to `HasInstanceContext` from the Context.
/// This is used to provide on-the-fly context passing to types that are not
/// defined in the context.
/// e.g. viewmodels in a controller
///
/// extension HasInstanceAppContext where Source == MyViewController {
/// var myModel: MyModel {
/// return resolve[MyModel()]
/// }
/// }
///
/// class MyViewController: HasInstanceAppContext {
/// var resolve = `default`
/// lazy var model: MyModel = { myModel }()
/// }
///
public subscript<D>(_ d: D) -> D where D: HasInstanceContext, D.Context == C {
var dx = d
dx.resolve.apply(context)
return dx
}
// --------------------------------------------------------------------------------
// MARK: - CustomStringConvertible
// --------------------------------------------------------------------------------
public var description: String {
return "Resolver with \(context)"
}
}
| mit | 45ab2449ce9671278856428442e22f08 | 36.248322 | 92 | 0.606306 | 4.632721 | false | false | false | false |
letzgro/GooglePlacesPicker | Classes/GooglePlacesPresentationAnimationController.swift | 1 | 2998 | //
// GooglePlacesPresentationAnimationController.swift
//
// Created by Ihor Rapalyuk on 2/3/16.
// Copyright © 2016 Lezgro. All rights reserved.
//
import UIKit
open class GooglePlacesPresentationAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
let isPresenting: Bool
let duration: TimeInterval = 0.5
init(isPresenting: Bool) {
self.isPresenting = isPresenting
super.init()
}
//MARK UIViewControllerAnimatedTransitioning methods
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return self.duration
}
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if isPresenting {
self.animatePresentationWithTransitionContext(transitionContext)
} else {
self.animateDismissalWithTransitionContext(transitionContext)
}
}
//MARK Helper methods
fileprivate func animatePresentationWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
let presentedController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let presentedControllerView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
// Position the presented view off the top of the container view
presentedControllerView.frame = transitionContext.finalFrame(for: presentedController)
presentedControllerView.center.y -= transitionContext.containerView.bounds.size.height
transitionContext.containerView.addSubview(presentedControllerView)
self.animateWithPresentedControllerView(presentedControllerView, andContainerView: transitionContext.containerView
, andTransitionContext: transitionContext)
}
fileprivate func animateDismissalWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
guard let presentedControllerView = transitionContext.view(forKey: UITransitionContextViewKey.from) else {
return
}
self.animateWithPresentedControllerView(presentedControllerView, andContainerView: transitionContext.containerView
, andTransitionContext: transitionContext)
}
fileprivate func animateWithPresentedControllerView(_ presentedControllerView: UIView, andContainerView containerView: UIView, andTransitionContext transitionContext: UIViewControllerContextTransitioning) {
// Animate the presented view off the bottom of the view
UIView.animate(withDuration: self.duration, delay: 0.0, usingSpringWithDamping: 1.0,
initialSpringVelocity: 0.0, options: .allowUserInteraction, animations: {
presentedControllerView.center.y += containerView.bounds.size.height
}, completion: {(completed: Bool) -> Void in
transitionContext.completeTransition(completed)
})
}
}
| mit | f21273cdab24a5084c9f918b8b65798a | 42.434783 | 210 | 0.751752 | 6.487013 | 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.