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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
danielsaidi/iExtra | iExtra/UI/Layout/UICollectionViewFlowLayout+Layouts.swift | 1 | 1201 | //
// UICollectionViewFlowLayout+Layouts.swift
// iExtra
//
// Created by Daniel Saidi on 2019-02-01.
// Copyright © 2019 Daniel Saidi. All rights reserved.
//
import UIKit
public extension UICollectionViewFlowLayout {
private static var idiom: UIUserInterfaceIdiom { return UIDevice.current.userInterfaceIdiom }
static var isPadLayout: Bool { return isPadLayoutIdiom(idiom) }
static var isPhoneLayout: Bool { return isPhoneLayoutIdiom(idiom) }
static var isTVLayout: Bool { return isTVLayoutIdiom(idiom) }
var idiom: UIUserInterfaceIdiom { return UICollectionViewFlowLayout.idiom }
var isPadLayout: Bool { return UICollectionViewFlowLayout.isPadLayout }
var isPhoneLayout: Bool { return UICollectionViewFlowLayout.isPhoneLayout }
var isTVLayout: Bool { return UICollectionViewFlowLayout.isTVLayout }
static func isPadLayoutIdiom(_ idiom: UIUserInterfaceIdiom) -> Bool {
return idiom == .pad
}
static func isPhoneLayoutIdiom(_ idiom: UIUserInterfaceIdiom) -> Bool {
return idiom == .phone
}
static func isTVLayoutIdiom(_ idiom: UIUserInterfaceIdiom) -> Bool {
return idiom == .tv
}
}
| mit | 8acb5c0a7168bc7e5e8005a15b3f7e16 | 33.285714 | 97 | 0.7175 | 5.194805 | false | false | false | false |
troystribling/BlueCap | BlueCapKit/External/FutureLocation/BeaconRegion.swift | 1 | 3617 | //
// BeaconRegion.swift
// BlueCap
//
// Created by Troy Stribling on 9/14/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import Foundation
import CoreLocation
public class BeaconRegion : Region {
internal let beaconPromise: StreamPromise<[Beacon]>
internal var _beacons = [Beacon]()
internal let clBeaconRegion: CLBeaconRegion
public var beacons: [Beacon] {
return self._beacons.sorted() {(b1: Beacon, b2: Beacon) -> Bool in
switch b1.discoveredAt.compare(b2.discoveredAt as Date) {
case .orderedSame:
return true
case .orderedDescending:
return false
case .orderedAscending:
return true
}
}
}
public var proximityUUID: UUID? {
return self.clBeaconRegion.proximityUUID
}
public var major : Int? {
if let _major = self.clBeaconRegion.major {
return _major.intValue
} else {
return nil
}
}
public var minor: Int? {
if let _minor = self.clBeaconRegion.minor {
return _minor.intValue
} else {
return nil
}
}
public var notifyEntryStateOnDisplay: Bool {
get {
return self.clBeaconRegion.notifyEntryStateOnDisplay
}
set {
self.clBeaconRegion.notifyEntryStateOnDisplay = newValue
}
}
public init(region: CLBeaconRegion, capacity: Int = Int.max) {
self.clBeaconRegion = region
self.beaconPromise = StreamPromise<[Beacon]>(capacity: capacity)
super.init(region:region, capacity: capacity)
self.notifyEntryStateOnDisplay = true
}
public convenience init(proximityUUID: UUID, identifier: String, capacity: Int = Int.max) {
self.init(region:CLBeaconRegion(proximityUUID: proximityUUID, identifier: identifier), capacity: capacity)
}
public convenience init(proximityUUID: UUID, identifier: String, major: UInt16, capacity: Int = Int.max) {
let beaconMajor : CLBeaconMajorValue = major
let beaconRegion = CLBeaconRegion(proximityUUID: proximityUUID, major: beaconMajor, identifier: identifier)
self.init(region: beaconRegion, capacity: capacity)
}
public convenience init(proximityUUID: UUID, identifier: String, major: UInt16, minor: UInt16, capacity: Int = Int.max) {
let beaconMinor : CLBeaconMinorValue = minor
let beaconMajor : CLBeaconMajorValue = major
let beaconRegion = CLBeaconRegion(proximityUUID:proximityUUID, major:beaconMajor, minor:beaconMinor, identifier:identifier)
self.init(region:beaconRegion, capacity:capacity)
}
public override class func isMonitoringAvailableForClass() -> Bool {
return CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self)
}
public func peripheralDataWithMeasuredPower(_ measuredPower: Int?) -> [String : AnyObject] {
let power: [NSObject : AnyObject]
if let measuredPower = measuredPower {
power = self.clBeaconRegion.peripheralData(withMeasuredPower: NSNumber(value: measuredPower)) as [NSObject:AnyObject]
} else {
power = self.clBeaconRegion.peripheralData(withMeasuredPower: nil) as [NSObject : AnyObject]
}
var result = [String : AnyObject]()
for key in power.keys {
if let keyPower = power[key], let key = key as? String {
result[key] = keyPower
}
}
return result
}
}
| mit | 323096894cb5e14e681bd495878608fb | 33.122642 | 131 | 0.634504 | 4.894452 | false | false | false | false |
hallas/agent | Agent/Agent.swift | 1 | 6541 | //
// Agent.swift
// Agent
//
// Created by Christoffer Hallas on 6/2/14.
// Copyright (c) 2014 Christoffer Hallas. All rights reserved.
//
import Foundation
public class Agent {
public typealias Headers = Dictionary<String, String>
public typealias Response = (NSHTTPURLResponse?, AnyObject?, NSError?) -> Void
public typealias RawResponse = (NSHTTPURLResponse?, NSData?, NSError?) -> Void
/**
* Members
*/
var base: NSURL?
var headers: Dictionary<String, String>?
var request: NSMutableURLRequest?
let queue = NSOperationQueue()
/**
* Initialize
*/
init(url: String, headers: Dictionary<String, String>?) {
self.base = NSURL(string: url)
self.headers = headers
}
convenience init(url: String) {
self.init(url: url, headers: nil)
}
init(method: String, url: String, headers: Dictionary<String, String>?) {
self.headers = headers
self.request(method, path: url)
}
convenience init(method: String, url: String) {
self.init(method: method, url: url, headers: nil)
}
/**
* Request
*/
func request(method: String, path: String) -> Agent {
var u: NSURL
if self.base != nil {
u = self.base!.URLByAppendingPathComponent(path)
} else {
u = NSURL(string: path)!
}
self.request = NSMutableURLRequest(URL: u)
self.request!.HTTPMethod = method
if self.headers != nil {
self.request!.allHTTPHeaderFields = self.headers
}
return self
}
/**
* GET
*/
public class func get(url: String) -> Agent {
return Agent(method: "GET", url: url, headers: nil)
}
public class func get(url: String, headers: Headers) -> Agent {
return Agent(method: "GET", url: url, headers: headers)
}
public class func get(url: String, done: Response) -> Agent {
return Agent.get(url).end(done)
}
public class func get(url: String, headers: Headers, done: Response) -> Agent {
return Agent.get(url, headers: headers).end(done)
}
public func get(url: String, done: Response) -> Agent {
return self.request("GET", path: url).end(done)
}
/**
* POST
*/
public class func post(url: String) -> Agent {
return Agent(method: "POST", url: url, headers: nil)
}
public class func post(url: String, headers: Headers) -> Agent {
return Agent(method: "POST", url: url, headers: headers)
}
public class func post(url: String, done: Response) -> Agent {
return Agent.post(url).end(done)
}
public class func post(url: String, headers: Headers, data: AnyObject) -> Agent {
return Agent.post(url, headers: headers).send(data)
}
public class func post(url: String, data: AnyObject) -> Agent {
return Agent.post(url).send(data)
}
public class func post(url: String, data: AnyObject, done: Response) -> Agent {
return Agent.post(url, data: data).send(data).end(done)
}
public class func post(url: String, headers: Headers, data: AnyObject, done: Response) -> Agent {
return Agent.post(url, headers: headers, data: data).send(data).end(done)
}
public func POST(url: String, data: AnyObject, done: Response) -> Agent {
return self.request("POST", path: url).send(data).end(done)
}
/**
* PUT
*/
public class func put(url: String) -> Agent {
return Agent(method: "PUT", url: url, headers: nil)
}
public class func put(url: String, headers: Headers) -> Agent {
return Agent(method: "PUT", url: url, headers: headers)
}
public class func put(url: String, done: Response) -> Agent {
return Agent.put(url).end(done)
}
public class func put(url: String, headers: Headers, data: AnyObject) -> Agent {
return Agent.put(url, headers: headers).send(data)
}
public class func put(url: String, data: AnyObject) -> Agent {
return Agent.put(url).send(data)
}
public class func put(url: String, data: AnyObject, done: Response) -> Agent {
return Agent.put(url, data: data).send(data).end(done)
}
public class func put(url: String, headers: Headers, data: AnyObject, done: Response) -> Agent {
return Agent.put(url, headers: headers, data: data).send(data).end(done)
}
public func PUT(url: String, data: AnyObject, done: Response) -> Agent {
return self.request("PUT", path: url).send(data).end(done)
}
/**
* DELETE
*/
public class func delete(url: String) -> Agent {
return Agent(method: "DELETE", url: url, headers: nil)
}
public class func delete(url: String, headers: Headers) -> Agent {
return Agent(method: "DELETE", url: url, headers: headers)
}
public class func delete(url: String, done: Response) -> Agent {
return Agent.delete(url).end(done)
}
public class func delete(url: String, headers: Headers, done: Response) -> Agent {
return Agent.delete(url, headers: headers).end(done)
}
public func delete(url: String, done: Response) -> Agent {
return self.request("DELETE", path: url).end(done)
}
/**
* Methods
*/
public func data(data: NSData?, mime: String) -> Agent {
self.set("Content-Type", value: mime)
self.request!.HTTPBody = data
return self
}
public func send(data: AnyObject) -> Agent {
var error: NSError?
let json = NSJSONSerialization.dataWithJSONObject(data, options: nil, error: &error)
return self.data(json, mime: "application/json")
}
public func set(header: String, value: String) -> Agent {
self.request!.setValue(value, forHTTPHeaderField: header)
return self
}
public func end(done: Response) -> Agent {
let completion = { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if error != .None {
done(.None, data, error)
return
}
var error: NSError?
var json: AnyObject!
if data != .None {
json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error)
}
let res = response as! NSHTTPURLResponse
done(res, json, error)
}
NSURLConnection.sendAsynchronousRequest(self.request!, queue: self.queue, completionHandler: completion)
return self
}
public func raw(done: RawResponse) -> Agent {
let completion = { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if error != .None {
done(.None, data, error)
return
}
done(response as? NSHTTPURLResponse, data, error)
}
NSURLConnection.sendAsynchronousRequest(self.request!, queue: self.queue, completionHandler: completion)
return self
}
}
| mit | 1d6591c6c83a3a8f178470a3a02ad46d | 26.141079 | 108 | 0.645314 | 3.791884 | false | false | false | false |
jbrudvik/swift-playgrounds | multiple-optional-unwrapping.playground/Contents.swift | 1 | 186 | // Multiple optionals can be unwrapped at once
var a: Int? = 1
var b: Int? = 2
var c: Int? = 3
if let a = a, b = b, c = c where c != 0 {
println(a)
println(b)
println(c)
}
| mit | 374e12d967b320cf38bef248b335d902 | 15.909091 | 46 | 0.553763 | 2.619718 | false | false | false | false |
mdiep/Logician | Sources/State.swift | 1 | 10884 | //
// State.swift
// Logician
//
// Created by Matt Diephouse on 9/2/16.
// Copyright © 2016 Matt Diephouse. All rights reserved.
//
import Foundation
public enum Error: Swift.Error {
case UnificationError
}
/// A partial or complete solution to a logic problem.
public struct State {
/// Type-erased information about a set of unified variables.
private struct Info {
/// The value of the variables, if any.
var value: Any?
/// Mapping from a key to the derived variable.
///
/// All variables that share the same basis must be unified.
var derived: [AnyVariable.Basis.Key: AnyVariable] = [:]
/// Functions that unify variables from bijections.
var bijections: [AnyVariable: Bijection]
init(_ bijections: [AnyVariable: Bijection] = [:]) {
self.bijections = bijections
}
}
/// The data backing the state.
private var context = Context<AnyVariable, Info>()
/// The constraints on the state.
private var constraints: [Constraint] = []
/// Look up the value of a property.
///
/// - parameters:
/// - property: A property of a variable in the state
///
/// - returns: The value of the property, or `nil` if the value is unknown
/// or the variable isn't in the `State`.
public func value<Value>(of property: Property<Value>) -> Value? {
return value(of: property.variable)
.map { property.transform($0) as! Value }
}
/// Look up the value of a variable.
///
/// - parameters:
/// - variable: A variable in the state
///
/// - returns: The value of the variable, or `nil` if the value is unknown
/// or the variable isn't in the `State`.
internal func value(of variable: AnyVariable) -> Any? {
return context[variable]?.value
}
/// Look up the value of a variable.
///
/// - parameters:
/// - variable: A variable in the state
///
/// - returns: The value of the variable, or `nil` if the value is unknown
/// or the variable isn't in the `State`.
public func value<Value>(of variable: Variable<Value>) -> Value? {
// ! because asking for the value of a variable can't change it
return try! bijecting(variable)
.value(of: variable.erased)
.map { $0 as! Value }
}
/// Add a constraint to the state.
internal mutating func constrain(_ constraint: @escaping Constraint) throws {
try constraint(self)
constraints.append(constraint)
}
/// Add a constraint to the state.
internal func constraining(_ constraint: @escaping Constraint) throws -> State {
var state = self
try state.constrain(constraint)
return state
}
/// Add a bijection to the state, unifying the variable it came from if the
/// other variable has a value.
private func bijecting<Value>(_ variable: Variable<Value>) throws -> State {
// We've already gone through this for this variable
if context[variable.erased] != nil { return self }
// This isn't a bijection.
if variable.bijections.isEmpty { return self }
var state = self
// If the variable doesn't have a basis, then this *must* be a 1-to-1
// bijection. So the source is the variable that isn't passed in.
let source = variable.erased.basis?.source
?? variable.bijections.keys.first { $0 != variable.erased }!
let unifySource = variable.bijections[source]!
// Unify all derived variables that share the same key. They are, by
// definition, unified.
var info = state.context[source] ?? Info()
for (variable, bijection) in variable.bijections {
if variable == source { continue }
info.bijections[variable] = bijection
if let key = variable.basis?.key {
if let existing = info.derived[key] {
// Since variable is new, it can't have a value. So just
// assume the existing variable's info.
state.context.merge(existing, variable) { lhs, _ in lhs }
} else {
info.derived[key] = variable
state.context[variable] = Info([source: unifySource])
}
} else {
state.context[variable] = Info([source: unifySource])
}
}
state.context[source] = info
// Try to unify each bijection
for bijection in variable.bijections.values {
state = try bijection(state)
}
try state.verifyConstraints()
return state
}
/// Verify that all the constraints in the state have been maintained,
/// throwing if any have been violated.
private func verifyConstraints() throws {
for constraint in constraints {
try constraint(self)
}
}
/// Unify a variable with a value.
///
/// - parameters:
/// - variable: The variable to unify
/// - value: The value to give the variable
///
/// - note: `throws` if `variable` already has a different value.
public mutating func unify<Value>(_ variable: Variable<Value>, _ value: Value) throws {
self = try unifying(variable, value)
}
/// Unify a variable with a value.
///
/// - parameters:
/// - variable: The variable to unify
/// - value: The value to give the variable
///
/// - returns: The unified state.
///
/// - note: `throws` if `variable` already has a different value.
public func unifying<Value>(_ variable: Variable<Value>, _ value: Value) throws -> State {
return try bijecting(variable)
.unifying(variable.erased, value)
}
/// Unify a variable with a value.
///
/// - important: `value` must be of the same type as `variable`'s `Value`.
///
/// - parameters:
/// - variable: The variable to unify
/// - value: The value to give the variable
///
/// - note: `throws` if `variable` already has a different value.
internal mutating func unify(_ variable: AnyVariable, _ value: Any) throws {
self = try unifying(variable, value)
}
/// Unify a variable with a value.
///
/// - important: `value` must be of the same type as `variable`'s `Value`.
///
/// - parameters:
/// - variable: The variable to unify
/// - value: The value to give the variable
///
/// - returns: The unified state.
///
/// - note: `throws` if `variable` already has a different value.
internal func unifying(_ variable: AnyVariable, _ value: Any) throws -> State {
var state = self
var info = state.context[variable] ?? Info()
if let oldValue = info.value {
if !variable.equal(oldValue, value) {
throw Error.UnificationError
}
} else {
info.value = value
state.context[variable] = info
for unify in info.bijections.values {
state = try unify(state)
}
try state.verifyConstraints()
}
return state
}
/// Unify two variables.
///
/// - parameters:
/// - lhs: The first variable to unify
/// - rhs: The second variable to unify
///
/// - note: `throws` if the variables have existing, inequal values.
public mutating func unify<Value>(_ lhs: Variable<Value>, _ rhs: Variable<Value>) throws {
self = try unifying(lhs, rhs)
}
/// Unify two variables.
///
/// - parameters:
/// - lhs: The first variable to unify
/// - rhs: The second variable to unify
///
/// - returns: The unified state.
///
/// - note: `throws` if `variable` already has a different value.
public func unifying<Value>(_ lhs: Variable<Value>, _ rhs: Variable<Value>) throws -> State {
return try self
.bijecting(lhs)
.bijecting(rhs)
.unifying(lhs.erased, rhs.erased)
}
/// Unify two variables.
///
/// - important: The two variables must have the same `Value` type.
///
/// - parameters:
/// - lhs: The first variable to unify
/// - rhs: The second variable to unify
///
/// - note: `throws` if the variables have existing, inequal values.
internal mutating func unify(_ lhs: AnyVariable, _ rhs: AnyVariable) throws {
self = try unifying(lhs, rhs)
}
/// Unify two variables.
///
/// - important: The two variables must have the same `Value` type.
///
/// - parameters:
/// - lhs: The first variable to unify
/// - rhs: The second variable to unify
///
/// - returns: The unified state.
///
/// - note: `throws` if `variable` already has a different value.
internal func unifying(_ lhs: AnyVariable, _ rhs: AnyVariable) throws -> State {
func merge<Key, Value>(
_ a: [Key: Value]?,
_ b: [Key: Value]?,
combine: (Value, Value) -> Value
) -> [Key: Value] {
var result: [Key: Value] = [:]
var allKeys = Set<Key>()
if let a = a?.keys { allKeys.formUnion(a) }
if let b = b?.keys { allKeys.formUnion(b) }
for key in allKeys {
let a = a?[key]
let b = b?[key]
if let a = a, let b = b {
result[key] = combine(a, b)
} else {
result[key] = a ?? b
}
}
return result
}
let equal = lhs.equal
var state = self
var unify: [(AnyVariable, AnyVariable)] = []
try state.context.merge(lhs, rhs) { lhs, rhs in
if let left = lhs?.value, let right = rhs?.value, !equal(left, right) {
throw Error.UnificationError
}
var info = Info()
info.value = lhs?.value ?? rhs?.value
info.bijections = merge(lhs?.bijections, rhs?.bijections) { a, _ in a }
info.derived = merge(lhs?.derived, rhs?.derived) { a, b in
unify.append((a, b))
return a
}
return info
}
for (a, b) in unify {
try state.unify(a, b)
}
let info = state.context[lhs]!
for bijection in info.bijections.values {
state = try bijection(state)
}
try state.verifyConstraints()
return state
}
}
| mit | 8a84f8361d066bdff43ff97c3d19c2c1 | 33.115987 | 97 | 0.547184 | 4.504553 | false | false | false | false |
Donkey-Tao/SinaWeibo | SinaWeibo/SinaWeibo/Classes/Discover/TFDiscoverViewController.swift | 1 | 2983 | //
// TFDiscoverViewController.swift
// SinaWeibo
//
// Created by Donkey-Tao on 2016/10/20.
// Copyright © 2016年 http://taofei.me All rights reserved.
//
import UIKit
class TFDiscoverViewController: TFBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
visitorView.setupVisitorViewInfo(iconName: "visitordiscover_image_message", tip: "登录后,别人评论你的微薄,给你发信息,都会在这里收到")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 71a90790a326157404d68ff34cfe525b | 31.175824 | 136 | 0.66735 | 5.101045 | false | false | false | false |
Off-Piste/Trolley.io-cocoa | Trolley/Core/Networking/Realtime/TRLWebSocketConnection.swift | 2 | 3538 | //
// TRLWebSocket.swift
// Pods
//
// Created by Harry Wright on 16.06.17.
//
//
import Foundation
import Alamofire
var kUserAgent: String {
let systemVersion = TRLAppEnviroment.current.systemVersion
let deviceName = UIDevice.current.model
let bundleIdentifier: String? = Bundle.main.bundleIdentifier
let ua: String = "Trolley/13/\(systemVersion)/\(deviceName)_\((bundleIdentifier) ?? "unknown")"
return ua
}
public let ServerDown: Notification.Name = Notification.Name(rawValue: "ServerDown")
class TRLWebSocketConnection {
fileprivate private(set) var webSocket: WebSocket
var delegate: TRLWebSocketDelegate?
var wasEverConnected: Bool = false
var serverDown: Bool = false
var attempts: Int = 0
init(url: URLConvertible, protocols: [String]?) throws {
self.webSocket = WebSocket(
url: try url.asURL(),
QOS: .background,
protocols: protocols,
userAgent: kUserAgent
)
self.webSocket.delegate = self
}
}
extension TRLWebSocketConnection {
func open() {
assert(delegate != nil, "TRLWebSocketDelegate must be set")
if self.serverDown { return }
attempts += 1
TRLCoreLogger.debug("This is WebSocket attempt #\(attempts)")
self.webSocket.connect()
self.waitForTimeout(10)
}
func close() {
self.webSocket.disconnect()
}
func send(_ message: String) {
self.webSocket.write(string: message)
}
func waitForTimeout(_ time: TimeInterval) {
TRLTimer(for: time).once {
if self.wasEverConnected { return }
TRLCoreNetworkingLogger.debug("WebSocket timed out after \(time) seconds")
self.webSocket.disconnect()
}
}
}
extension TRLWebSocketConnection : WebSocketDelegate {
func webSocketDidConnect(_ socket: WebSocket) {
self.wasEverConnected = true
self.delegate?.webSocketOnConnection(self)
}
func webSocket(_ socket: WebSocket, didReceiveData data: Data) {
self.delegate?.webSocket(self, onMessage: ["Data" : data])
}
func webSocket(_ socket: WebSocket, didReceiveMessage message: String) {
if message == "0" { self.delegate?.webSocket(self, onTextMessage: message) }
else if let data = message.data(using: .utf8, allowLossyConversion: true) {
self.delegate?.webSocket(self, onMessage: JSON(data: data))
} else { self.delegate?.webSocket(self, onMessage: JSON(message)) }
}
func webSocket(_ socket: WebSocket, didDisconnect error: NSError?) {
if error != nil, (error!.code == 61 && Trolley.shared.reachability.isReachable) {
let errorResponse = "Server is down [(url: \(socket.currentURL)) ( error: \(error!.localizedDescription)) (reachability: \(Trolley.shared.reachability.currentReachabilityString))]"
TRLCoreNetworkingLogger.error(errorResponse)
// In the TRLUIComponents we will have some view watching
// this to display an error
NotificationCenter.default.post(name: ServerDown, object: nil)
}
self.delegate?.webSocketOnDisconnect(self, wasEverConnected: self.wasEverConnected)
}
}
extension TRLWebSocketConnection : CustomStringConvertible {
var description: String {
return self.webSocket.description
}
}
| mit | 5a20b14e946ce1afe818e5991bdf0e37 | 28.731092 | 192 | 0.632561 | 4.774629 | false | false | false | false |
crazypoo/PTools | Pods/SwifterSwift/Sources/SwifterSwift/SwiftStdlib/ArrayExtensions.swift | 1 | 5471 | //
// ArrayExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/5/16.
// Copyright © 2016 SwifterSwift
//
// MARK: - Methods
public extension Array {
/// SwifterSwift: Insert an element at the beginning of array.
///
/// [2, 3, 4, 5].prepend(1) -> [1, 2, 3, 4, 5]
/// ["e", "l", "l", "o"].prepend("h") -> ["h", "e", "l", "l", "o"]
///
/// - Parameter newElement: element to insert.
mutating func prepend(_ newElement: Element) {
insert(newElement, at: 0)
}
/// SwifterSwift: Safely swap values at given index positions.
///
/// [1, 2, 3, 4, 5].safeSwap(from: 3, to: 0) -> [4, 2, 3, 1, 5]
/// ["h", "e", "l", "l", "o"].safeSwap(from: 1, to: 0) -> ["e", "h", "l", "l", "o"]
///
/// - Parameters:
/// - index: index of first element.
/// - otherIndex: index of other element.
mutating func safeSwap(from index: Index, to otherIndex: Index) {
guard index != otherIndex else { return }
guard startIndex..<endIndex ~= index else { return }
guard startIndex..<endIndex ~= otherIndex else { return }
swapAt(index, otherIndex)
}
/// SwifterSwift: Sort an array like another array based on a key path. If the other array doesn't contain a certain value, it will be sorted last.
///
/// [MyStruct(x: 3), MyStruct(x: 1), MyStruct(x: 2)].sorted(like: [1, 2, 3], keyPath: \.x)
/// -> [MyStruct(x: 1), MyStruct(x: 2), MyStruct(x: 3)]
///
/// - Parameters:
/// - otherArray: array containing elements in the desired order.
/// - keyPath: keyPath indiciating the property that the array should be sorted by
/// - Returns: sorted array.
func sorted<T: Hashable>(like otherArray: [T], keyPath: KeyPath<Element, T>) -> [Element] {
let dict = otherArray.enumerated().reduce(into: [:]) { $0[$1.element] = $1.offset }
return sorted {
guard let thisIndex = dict[$0[keyPath: keyPath]] else { return false }
guard let otherIndex = dict[$1[keyPath: keyPath]] else { return true }
return thisIndex < otherIndex
}
}
}
// MARK: - Methods (Equatable)
public extension Array where Element: Equatable {
/// SwifterSwift: Remove all instances of an item from array.
///
/// [1, 2, 2, 3, 4, 5].removeAll(2) -> [1, 3, 4, 5]
/// ["h", "e", "l", "l", "o"].removeAll("l") -> ["h", "e", "o"]
///
/// - Parameter item: item to remove.
/// - Returns: self after removing all instances of item.
@discardableResult
mutating func removeAll(_ item: Element) -> [Element] {
removeAll(where: { $0 == item })
return self
}
/// SwifterSwift: Remove all instances contained in items parameter from array.
///
/// [1, 2, 2, 3, 4, 5].removeAll([2,5]) -> [1, 3, 4]
/// ["h", "e", "l", "l", "o"].removeAll(["l", "h"]) -> ["e", "o"]
///
/// - Parameter items: items to remove.
/// - Returns: self after removing all instances of all items in given array.
@discardableResult
mutating func removeAll(_ items: [Element]) -> [Element] {
guard !items.isEmpty else { return self }
removeAll(where: { items.contains($0) })
return self
}
/// SwifterSwift: Remove all duplicate elements from Array.
///
/// [1, 2, 2, 3, 4, 5].removeDuplicates() -> [1, 2, 3, 4, 5]
/// ["h", "e", "l", "l", "o"]. removeDuplicates() -> ["h", "e", "l", "o"]
///
/// - Returns: Return array with all duplicate elements removed.
@discardableResult
mutating func removeDuplicates() -> [Element] {
// Thanks to https://github.com/sairamkotha for improving the method
self = reduce(into: [Element]()) {
if !$0.contains($1) {
$0.append($1)
}
}
return self
}
/// SwifterSwift: Return array with all duplicate elements removed.
///
/// [1, 1, 2, 2, 3, 3, 3, 4, 5].withoutDuplicates() -> [1, 2, 3, 4, 5])
/// ["h", "e", "l", "l", "o"].withoutDuplicates() -> ["h", "e", "l", "o"])
///
/// - Returns: an array of unique elements.
///
func withoutDuplicates() -> [Element] {
// Thanks to https://github.com/sairamkotha for improving the method
return reduce(into: [Element]()) {
if !$0.contains($1) {
$0.append($1)
}
}
}
/// SwifterSwift: Returns an array with all duplicate elements removed using KeyPath to compare.
///
/// - Parameter path: Key path to compare, the value must be Equatable.
/// - Returns: an array of unique elements.
func withoutDuplicates<E: Equatable>(keyPath path: KeyPath<Element, E>) -> [Element] {
return reduce(into: [Element]()) { (result, element) in
if !result.contains(where: { $0[keyPath: path] == element[keyPath: path] }) {
result.append(element)
}
}
}
/// SwifterSwift: Returns an array with all duplicate elements removed using KeyPath to compare.
///
/// - Parameter path: Key path to compare, the value must be Hashable.
/// - Returns: an array of unique elements.
func withoutDuplicates<E: Hashable>(keyPath path: KeyPath<Element, E>) -> [Element] {
var set = Set<E>()
return filter { set.insert($0[keyPath: path]).inserted }
}
}
| mit | b6fac9096da7070b2c07c5caf2a9a9a0 | 38.352518 | 151 | 0.550091 | 3.785467 | false | false | false | false |
TermiT/Flycut | Flycut-iOS/ViewController.swift | 1 | 21026 | //
// ViewController.swift
// Flycut-iOS
//
// Created by Mark Jerde on 7/12/17.
//
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, FlycutStoreDelegate, FlycutOperatorDelegate, MJCloudKitUserDefaultsSyncDelegate {
let flycut:FlycutOperator = FlycutOperator()
var activeUpdates:Int = 0
var tableView:UITableView!
var currentAnimation = UITableView.RowAnimation.none
var pbCount:Int = -1
var rememberedSyncSettings:Bool = false
var rememberedSyncClippings:Bool = false
var ignoreCKAccountStatusNoAccount = false
let pasteboardInteractionQueue = DispatchQueue(label: "com.Flycut.pasteboardInteractionQueue")
let alertHandlingSemaphore = DispatchSemaphore(value: 0)
let defaultsChangeHandlingQueue = DispatchQueue(label: "com.Flycut.defaultsChangeHandlingQueue")
let isURLDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
// Some buttons we will reuse.
var deleteButton:MGSwipeButton? = nil
var openURLButton:MGSwipeButton? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Uncomment the following line to load the demo state for screenshots.
//UserDefaults.standard.set(NSNumber(value: true), forKey: "demoForAppStoreScreenshots")
// Use this command to get screenshots:
// while true; do xcrun simctl io booted screenshot;sleep 1;done
MJCloudKitUserDefaultsSync.shared()?.setDelegate(self)
if ( UserDefaults.standard.bool(forKey: "demoForAppStoreScreenshots") )
{
// Ensure we will not load or save clippings in demo mode.
let savePref = UserDefaults.standard.integer(forKey: "savePreference")
if ( 0 < savePref )
{
UserDefaults.standard.set(0, forKey: "savePreference")
}
}
tableView = self.view.subviews.first as! UITableView
tableView.delegate = self
tableView.dataSource = self
tableView.register(MGSwipeTableCell.self, forCellReuseIdentifier: "FlycutCell")
deleteButton = MGSwipeButton(title: "Delete", backgroundColor: .red, callback: { (cell) -> Bool in
let indexPath = self.tableView.indexPath(for: cell)
if ( nil != indexPath ) {
let previousAnimation = self.currentAnimation
self.currentAnimation = UITableView.RowAnimation.left // Use .left to look better with swiping left to delete.
self.flycut.setStackPositionTo( Int32((indexPath?.row)! ))
self.flycut.clearItemAtStackPosition()
self.currentAnimation = previousAnimation
}
return true;
})
openURLButton = MGSwipeButton(title: "Open", backgroundColor: .blue, callback: { (cell) -> Bool in
let indexPath = self.tableView.indexPath(for: cell)
if ( nil != indexPath ) {
let url = URL(string: self.flycut.clippingString(withCount: Int32((indexPath?.row)!) )! )
if #available(iOS 10.0, *) {
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
UIApplication.shared.openURL(url!)
}
self.tableView.reloadRows(at: [indexPath!], with: UITableView.RowAnimation.none)
}
return true;
})
// Force sync disable for test if needed.
//UserDefaults.standard.set(NSNumber(value: false), forKey: "syncSettingsViaICloud")
//UserDefaults.standard.set(NSNumber(value: false), forKey: "syncClippingsViaICloud")
// Force to ask to enable sync for test if needed.
//UserDefaults.standard.set(false, forKey: "alreadyAskedToEnableSync")
// Ensure these are false since there isn't a way to access the saved clippings on iOS as this point.
UserDefaults.standard.set(NSNumber(value: false), forKey: "saveForgottenClippings")
UserDefaults.standard.set(NSNumber(value: false), forKey: "saveForgottenFavorites")
flycut.setClippingsStoreDelegate(self)
flycut.delegate = self
flycut.awake(fromNibDisplaying: 10, withDisplayLength: 140, withSave: #selector(savePreferences(toDict:)), forTarget: self) // The 10 isn't used in iOS right now and 140 characters seems to be enough to cover the width of the largest screen.
NotificationCenter.default.addObserver(self, selector: #selector(self.checkForClippingAddedToClipboard), name: UIPasteboard.changedNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillTerminate), name: UIApplication.willTerminateNotification, object: nil)
// Check for clipping whenever we become active.
NotificationCenter.default.addObserver(self, selector: #selector(self.checkForClippingAddedToClipboard), name: UIApplication.didBecomeActiveNotification, object: nil)
checkForClippingAddedToClipboard() // Since the first-launch notification will occur before we add observer.
// Register for notifications for the scenarios in which we should save the engine.
[ UIApplication.willResignActiveNotification,
UIApplication.didEnterBackgroundNotification,
UIApplication.willTerminateNotification ]
.forEach { (notification) in
NotificationCenter.default.addObserver(self,
selector: #selector(self.saveEngine),
name: notification,
object: nil)
}
NotificationCenter.default.addObserver(self, selector: #selector(self.defaultsChanged), name: UserDefaults.didChangeNotification, object: nil)
if ( UserDefaults.standard.bool(forKey: "demoForAppStoreScreenshots") )
{
// Make sure we won't send these change to iCloud.
UserDefaults.standard.set(NSNumber(value: false), forKey: "syncSettingsViaICloud")
UserDefaults.standard.set(NSNumber(value: false), forKey: "syncClippingsViaICloud")
self.flycut.registerOrDeregisterICloudSync()
NotificationCenter.default.removeObserver(self)
// Load sample content, reverse order.
self.flycut.addClipping("https://www.apple.com", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil)
self.flycut.addClipping("App Store is a digital distribution platform, developed and maintained by Apple Inc., for mobile apps on its iOS operating system.", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil)
self.flycut.addClipping("https://itunesconnect.apple.com/", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil)
self.flycut.addClipping("The party is at 123 Main St. 6 PM. Please bring some chips to share.", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil)
self.flycut.addClipping("You are going to love this new design I found. It takes half the effort and resonates with today's hottest trends. With our throughput up we can now keep up with demand.", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil)
self.flycut.addClipping("http://www.makeuseof.com/tag/5-best-mac-clipboard-manager-apps-improve-workflow/", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil)
self.flycut.addClipping("Swipe left to delete", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil)
self.flycut.addClipping("Swipe right to open web links", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil)
self.flycut.addClipping("Tap to copy", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil)
self.flycut.addClipping("Manage your clippings in iOS", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil)
self.flycut.addClipping("Flycut has made the leap from macOS to iOS", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil)
self.flycut.addClipping("Flycut has made the leap from OS X to iOS", ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil)
// Unset the demo setting.
UserDefaults.standard.set(NSNumber(value: false), forKey: "demoForAppStoreScreenshots")
}
}
@objc func defaultsChanged() {
// This seems to be the only way to respond to Settings changes, though it doesn't inform us what changed so we will have to check each to see if they were the one(s).
// Don't use DispatchQueue.main.async since that will still end up blocking the UI draw until the user responds to what hasn't been drawn yet.
// Use async on a sequential queue to avoid concurrent response to the same change. This allows enqueuing of defaultsChanged calls in reponse to changes made within the handling, but using sync causes EXC_BAD_ACCESS in this case.
defaultsChangeHandlingQueue.async {
let newRememberNum = Int32(UserDefaults.standard.integer(forKey: "rememberNum"))
if ( UserDefaults.standard.value(forKey: "rememberNum") is String )
{
// Reset the value, since TextField will make it a String and CloudKit sync will object to changing the type. Check this independent of value change, since the type could be changed without a change in value and we don't want it left around causing confusion.
UserDefaults.standard.set(newRememberNum, forKey: "rememberNum")
}
if ( self.flycut.rememberNum() != newRememberNum ) {
self.flycut.setRememberNum(newRememberNum, forPrimaryStore: true)
}
let syncSettings = UserDefaults.standard.bool(forKey: "syncSettingsViaICloud")
let syncClippings = UserDefaults.standard.bool(forKey: "syncClippingsViaICloud")
if ( syncSettings != self.rememberedSyncSettings
|| syncClippings != self.rememberedSyncClippings )
{
self.rememberedSyncSettings = syncSettings
self.rememberedSyncClippings = syncClippings
if ( self.rememberedSyncClippings )
{
if ( 2 > UserDefaults.standard.integer(forKey: "savePreference") )
{
UserDefaults.standard.set(2, forKey: "savePreference")
}
}
self.flycut.registerOrDeregisterICloudSync()
}
}
}
override func viewDidAppear(_ animated: Bool) {
// Ask once to enable Sync. The syntax below will take the else unless alreadyAnswered is non-nil and true.
let alreadyAsked = UserDefaults.standard.value(forKey: "alreadyAskedToEnableSync")
if let answer = alreadyAsked, answer as! Bool
{
}
else
{
// Don't use DispatchQueue.main.async since that will still end up blocking the UI draw until the user responds to what hasn't been drawn yet. Just create a queue to get us away from main, since this is a one-time code path.
DispatchQueue(label: "com.Flycut.alertHandlingQueue", qos: .userInitiated ).async {
let selection = self.alert(withMessageText: "iCloud Sync", informationText: "Would you like to enable Flycut's iCloud Sync for Settings and Clippings?", buttonsTexts: ["Yes", "No"])
let response = (selection == "Yes");
UserDefaults.standard.set(NSNumber(value: response), forKey: "syncSettingsViaICloud")
UserDefaults.standard.set(NSNumber(value: response), forKey: "syncClippingsViaICloud")
UserDefaults.standard.set(true, forKey: "alreadyAskedToEnableSync")
self.flycut.registerOrDeregisterICloudSync()
}
}
// This is a suitable place to prepare to possible eventual display of preferences, resetting values that should reset before each display of preferences.
flycut.willShowPreferences()
}
@objc func savePreferences(toDict: NSMutableDictionary)
{
}
func beginUpdates()
{
if ( !Thread.isMainThread )
{
DispatchQueue.main.sync { beginUpdates() }
return
}
print("Begin updates")
print("Num rows: \(tableView.dataSource?.tableView(tableView, numberOfRowsInSection: 0))")
if ( 0 == activeUpdates )
{
tableView.beginUpdates()
}
activeUpdates += 1
}
func endUpdates()
{
if ( !Thread.isMainThread )
{
DispatchQueue.main.sync { endUpdates() }
return
}
print("End updates");
activeUpdates -= 1;
if ( 0 == activeUpdates )
{
tableView.endUpdates()
}
}
func insertClipping(at index: Int32) {
if ( !Thread.isMainThread )
{
DispatchQueue.main.sync { insertClipping(at: index) }
return
}
print("Insert row \(index)")
tableView.insertRows(at: [IndexPath(row: Int(index), section: 0)], with: currentAnimation) // We will override the animation for now, because we are the ViewController and should guide the UX.
}
func deleteClipping(at index: Int32) {
if ( !Thread.isMainThread )
{
DispatchQueue.main.sync { deleteClipping(at: index) }
return
}
print("Delete row \(index)")
tableView.deleteRows(at: [IndexPath(row: Int(index), section: 0)], with: currentAnimation) // We will override the animation for now, because we are the ViewController and should guide the UX.
}
func reloadClipping(at index: Int32) {
if ( !Thread.isMainThread )
{
DispatchQueue.main.sync { reloadClipping(at: index) }
return
}
print("Reloading row \(index)")
tableView.reloadRows(at: [IndexPath(row: Int(index), section: 0)], with: currentAnimation) // We will override the animation for now, because we are the ViewController and should guide the UX.
}
func moveClipping(at index: Int32, to newIndex: Int32) {
if ( !Thread.isMainThread )
{
DispatchQueue.main.sync { moveClipping(at: index, to: newIndex) }
return
}
print("Moving row \(index) to \(newIndex)")
tableView.moveRow(at: IndexPath(row: Int(index), section: 0), to: IndexPath(row: Int(newIndex), section: 0))
}
func alert(withMessageText message: String!, informationText information: String!, buttonsTexts buttons: [Any]!) -> String! {
// Don't use DispatchQueue.main.async since that will still end up blocking the UI draw until the user responds to what hasn't been drawn yet. This isn't a great check, as it is OS-version-limited and results in a EXC_BAD_INSTRUCTION if it fails, but is good enough for development / test.
if #available(iOS 10.0, *) {
__dispatch_assert_queue_not(DispatchQueue.main)
}
let alertController = UIAlertController(title: message, message: information, preferredStyle: .alert)
var selection:String? = nil
for option in buttons
{
alertController.addAction(UIAlertAction(title: option as? String, style: .default) { action in
selection = action.title
self.alertHandlingSemaphore.signal()
})
}
if var topController = UIApplication.shared.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
// topController should now be your topmost view controller
// Transform the asynchronous UIAlertController into a synchronous alert by waiting, after presenting, on a semaphore that is initialized to zero and only signaled in the selection handler.
DispatchQueue.main.async {
topController.present(alertController, animated: true)
}
alertHandlingSemaphore.wait() // To wait for queue to resume.
}
return selection
}
@objc func checkForClippingAddedToClipboard()
{
pasteboardInteractionQueue.async {
// This is a suitable place to prepare to possible eventual display of preferences, resetting values that should reset before each display of preferences.
self.flycut.willShowPreferences()
if ( UIPasteboard.general.changeCount != self.pbCount )
{
self.pbCount = UIPasteboard.general.changeCount;
if UIPasteboard.general.types.contains("public.utf8-plain-text"),
let pasteboard = UIPasteboard.general.value(forPasteboardType: "public.utf8-plain-text") as? String
{
self.flycut.addClipping(pasteboard, ofType: "public.utf8-plain-text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil)
}
else if UIPasteboard.general.types.contains("public.text"),
let pasteboard = UIPasteboard.general.value(forPasteboardType: "public.text") as? String
{
self.flycut.addClipping(pasteboard, ofType: "public.text", fromApp: "iOS", withAppBundleURL: "iOS", target: nil, clippingAddedSelector: nil)
}
}
}
}
@objc func applicationWillTerminate()
{
saveEngine()
}
@objc func saveEngine()
{
flycut.saveEngine()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
saveEngine()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Int(flycut.jcListCount())
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item: MGSwipeTableCell = tableView.dequeueReusableCell(withIdentifier: "FlycutCell", for: indexPath) as! MGSwipeTableCell
item.textLabel?.text = flycut.previousDisplayStrings(Int32(indexPath.row + 1), containing: nil).last as! String?
//configure left buttons
var removeAll:Bool = true
if let content = flycut.clippingString(withCount: Int32(indexPath.row) )
{
// Detect if something is a URL before passing it to canOpenURL because on iOS 9 and later, if building with an earlier SDK, there is a limit of 50 distinct URL schemes before canOpenURL will just return false. This limit is theorized to prevent apps from detecting what other apps are installed. The limit should be okay, assuming any user encounters fewer than 50 URL schemes, since those that the user actually uses will be allowed through before reaching the limit. For building with an iOS 9 or later SDK a whitelist of schemes in the Info.plist will be used, but filtering before calling canOpenURL decreases the volume of log messages.
// NSTextCheckingResult.CheckingType.link.rawValue blocks things like single words that URL() would let in
// URL() blocks things like paragraphs of text containing a URL that NSTextCheckingResult.CheckingType.link.rawValue would let in
let matches = isURLDetector?.matches(in: content, options: .reportCompletion, range: NSMakeRange(0, content.count))
if let matchesCount = matches?.count
{
if matchesCount > 0
{
if let url = URL(string: content)
{
if UIApplication.shared.canOpenURL( url ) {
if(!item.leftButtons.contains(openURLButton!))
{
item.leftButtons.append(openURLButton!)
item.leftSwipeSettings.transition = .border
item.leftExpansion.buttonIndex=0
removeAll = false
}
}
}
}
}
}
if ( removeAll ) {
item.leftButtons.removeAll()
}
//configure right buttons
if ( 0 == item.rightButtons.count )
{
// Setup the right buttons only if they haven't been before.
item.rightButtons.append(deleteButton!)
item.rightSwipeSettings.transition = .border
item.rightExpansion.buttonIndex = 0
}
return item
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if ( MGSwipeState.none == (tableView.cellForRow(at: indexPath) as! MGSwipeTableCell).swipeState ) {
tableView.deselectRow(at: indexPath, animated: true) // deselect before getPaste since getPaste may reorder the list
let content = flycut.getPasteFrom(Int32(indexPath.row))
print("Select: \(indexPath.row) \(content) OK")
pasteboardInteractionQueue.async {
// Capture value before setting the pastboard for reasons noted below.
self.pbCount = UIPasteboard.general.changeCount
// This call will clear all other content types and appears to immediately increment the changeCount.
UIPasteboard.general.setValue(content as Any, forPasteboardType: "public.utf8-plain-text")
// Apple documents that "UIPasteboard waits until the end of the current event loop before incrementing the change count", but this doesn't seem to be the case for the above call. Handle both scenarios by doing a simple increment if unchanged and an update-to-match if changed.
if ( UIPasteboard.general.changeCount == self.pbCount )
{
self.pbCount += 1
}
else
{
self.pbCount = UIPasteboard.general.changeCount
}
}
}
}
func notifyCKAccountStatusNoAccount() {
DispatchQueue.main.async {
guard !self.ignoreCKAccountStatusNoAccount else { return }
let alert = UIAlertController(title: "No iCloud Account", message: "An iCloud account with iCloud Drive enabled is required for iCloud sync.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Preferences", style: .default, handler: { (_) in
if #available(iOS 10.0, *)
{
// Opens iCloud Prefs < iOS 11.0, main Prefs >= iOS 11.0
UIApplication.shared.openURL(URL(string: "App-Prefs:root=CASTLE")!)
}
else
{
UIApplication.shared.openURL(URL(string: "prefs:root=CASTLE")!)
}
}))
alert.addAction(UIAlertAction(title: "Ignore", style: .cancel, handler: { (_) in
self.ignoreCKAccountStatusNoAccount = true
}))
self.present(alert, animated: true, completion: nil)
}
}
}
| mit | aa4c3ff5873fdce470db035944aa66ca | 43.73617 | 649 | 0.73704 | 4.067711 | false | false | false | false |
robconrad/fledger-ios | fledger-ios/controllers/type/TypesTableView.swift | 1 | 3791 | //
// AccountTableView.swift
// fledger-ios
//
// Created by Robert Conrad on 5/2/15.
// Copyright (c) 2015 Robert Conrad. All rights reserved.
//
import UIKit
import FledgerCommon
class TypesTableView: AppUITableView, UITableViewDataSource, UITableViewDelegate {
private var typeId: Int64?
private var types: [Type]?
private var sections: [String] = []
private var sectionIndices: [String] = []
private var sectionRows: [String: [Type]] = [:]
private var selected: NSIndexPath?
var selectHandler: SelectIdHandler?
override internal func setup() {
super.setup()
delegate = self
dataSource = self
sectionIndexBackgroundColor = AppColors.bgHighlight()
}
func setType(id: Int64) {
self.typeId = id
selectType()
}
private func selectType() {
if typeId != nil {
let type = types!.filter { $0.id == self.typeId }.first!
let section = type.group().name
let index = sectionRows[section]?.find { $0.id == self.typeId }
if let i = index {
let indexPath = NSIndexPath(forRow: i, inSection: sections.find { $0 == section }!)
selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.Middle)
}
}
}
override func reloadData() {
sections = []
sectionRows = [:]
types = TypeSvc().all()
for type in types! {
let section = type.group().name
if sectionRows[section] == nil {
sectionRows[section] = []
}
sectionRows[section]!.append(type)
}
for section in sectionRows.keys {
sections.append(section)
}
sections.sortInPlace({ left, right in
return left.lowercaseString < right.lowercaseString
})
for section in sections {
sectionIndices.append(section.substringToIndex(section.startIndex.advancedBy(min(3, section.characters.count))))
}
super.reloadData()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sectionRows[sections[section]]!.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.textLabel!.textColor = AppColors.text()
header.contentView.backgroundColor = AppColors.bgHighlight()
}
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]! {
return sectionIndices
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var reuseIdentifier = "default"
var label = "failure"
if let type = sectionRows[sections[indexPath.section]]?[indexPath.row] {
if type.id == typeId {
reuseIdentifier = "selected"
}
label = type.name
}
let cell = dequeueReusableCellWithIdentifier(reuseIdentifier)!
cell.textLabel?.text = label
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let handler = selectHandler, typeId = self.sectionRows[sections[indexPath.section]]?[indexPath.row].id {
handler(typeId)
}
}
} | mit | 1945446a098279a74720e624a9303bee | 30.6 | 124 | 0.607491 | 5.207418 | false | false | false | false |
octanner/ios-environment-switcher | EnvironmentSwitcher/EnvironmentSwitcherViewController.swift | 1 | 3944 | //
// EnvironmentSwitcherViewController.swift
// EnvironmentSwitcher
//
// Created by Ben Norris on 2/12/16.
// Copyright © 2016 OC Tanner. All rights reserved.
//
import UIKit
import NetworkStack
public protocol EnvironmentSwitcherDelegate {
func closeEnvironmentSwitcher(appNetworkStateChanged: Bool)
}
public class EnvironmentSwitcherViewController: UIViewController {
// MARK: - Public properties
public var delegate: EnvironmentSwitcherDelegate?
public var environments = [AppNetworkState]()
// MARK: - Internal properties
@IBOutlet weak var apiURLField: UITextField!
@IBOutlet weak var tokenURLField: UITextField!
@IBOutlet weak var picker: UIPickerView!
// MARK: - Constants
private let customName = "custom"
// MARK: - Lifecycle overrides
public override func viewDidLoad() {
super.viewDidLoad()
guard let appEnvironment = AppNetworkState.currentAppState else { fatalError("Must have app environment") }
for (index, environment) in environments.enumerate() {
if appEnvironment.environmentKey == environment.environmentKey {
let custom = environment.environmentKey == customName
picker.selectRow(index, inComponent: 0, animated: false)
apiURLField.text = environment.apiURLString
apiURLField.enabled = custom
tokenURLField.text = environment.tokenEndpointURLString
tokenURLField.enabled = custom
break
}
}
}
// MARK: - Internal functions
@IBAction func saveSwitch(sender: AnyObject) {
view.endEditing(true)
let updatedEnvironment = environments[picker.selectedRowInComponent(0)]
AppNetworkState.currentAppState = updatedEnvironment
delegate?.closeEnvironmentSwitcher(true)
}
@IBAction func cancelSwitch(sender: AnyObject) {
delegate?.closeEnvironmentSwitcher(false)
}
}
// MARK: - Text field delegate
extension EnvironmentSwitcherViewController: UITextFieldDelegate {
public func textFieldDidEndEditing(textField: UITextField) {
let index = picker.selectedRowInComponent(0)
let custom = environments[index]
if custom.environmentKey != customName { return }
let updatedCustom = AppNetworkState(apiURLString: apiURLField.text!, tokenEndpointURLString: tokenURLField.text!, environmentKey: customName)
environments[index] = updatedCustom
}
public func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == apiURLField {
tokenURLField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return true
}
}
// MARK: - Picker delegate
extension EnvironmentSwitcherViewController: UIPickerViewDelegate {
public func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let environment = environments[row]
return environment.environmentKey
}
public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let environment = environments[row]
let custom = environment.environmentKey == customName
apiURLField.text = environment.apiURLString
apiURLField.enabled = custom
tokenURLField.text = environment.tokenEndpointURLString
tokenURLField.enabled = custom
}
}
// MARK: - Picker data source
extension EnvironmentSwitcherViewController: UIPickerViewDataSource {
public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return environments.count
}
}
| mit | 4ab3bba36c501d0a37fda04380e28ef7 | 29.330769 | 149 | 0.678925 | 5.689755 | false | false | false | false |
MA806P/SwiftDemo | SwiftTestDemo/SwiftTestDemo/ARC.swift | 1 | 6512 | //
// ARC.swift
// SwiftTestDemo
//
// Created by MA806P on 2018/9/10.
// Copyright © 2018年 myz. All rights reserved.
//
import Foundation
/*
Automatic Reference Counting
引用计数只适用于实例对象。结构体和枚举是值类型,不是引用类型,并且不通过引用存储和传递的。
解决实例之间的强引用循环
Swift 提供了两种方法解决你在使用类的属性而产生的强引用循环:弱引用( weak )和无主引用( unowned )。
弱引用( weak )和无主引用( unowned )能确保一个实例在循环引用中引用另一个实例,
而不用保持强引用关系。这样实例就可以相互引用且不会产生强引用循环。
//weak
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { print("\(name) is being deinitialized") }
}
class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
weak var tenant: Person? // <---------------
deinit { print("Apartment \(unit) is being deinitialized") }
}
//unowned
与弱引用不同的是,无主引用适用于其他实例有相同的生命周期或是更长的生命周期的场景。
无主引用总是有值的。因而,ARC也不会将无主引用的值设置为 nil,这也意味着无主引用要被定义为非可选类型。
只有在确保引用的实例 永远 不会释放,才能使用无主引用。
如果你在无主引用的对象释放之后,视图访问该值,会触发运行时错误
对于需要禁掉运行时安全检查的情况,Swift 也提供了不安全的无主引用--例如,出于性能考虑。
想其他不安全操作一样,你需要负责检查代码的安全性。
unowned(unsafe) 表示这是一个不安全的无主引用。当你试图访问已经释放了的不安全的无主引用实例时,
程序会试图访问该实例指向的内存区域,这是一种不安全的操作。
Person 和 Apartment 的例子展示了两个属性都允许设置为 nil,并会造成潜在的强引用循环。这种场景最适合用弱引用来解决。
Customer 和 CreditCard 的例子展示了一个属性允许设置为 nil,而另一个属性不允许设置为 nil,并会造成潜在的强引用循环。这种场景最适合用无主引用来解决。
然而,还有第三种场景,两个属性 都 必须有值,初始化之后属性都不能为 nil。在这场景下,需要一个类使用无主引用属性,另一个类使用隐式解析可选类型属性。
闭包引起的强引用循环
强引用循环还可能发生在将一个闭包赋值给一个实例的属性,并且这个闭包又捕获到这个实例的时候。捕获的原因可能是在闭包的内部需要访问实例的属性
当你把一个闭包赋值给一个属性时,其实赋值的是这个闭包的引用,和之前的问题一样--都是两个强引用互相持有对方不被释放
Swift 提供了一个优雅的解决方案,称之为 闭包捕获列表(closure capture list)。
解决闭包引起的强引用循环
定义闭包的时候同时定义 捕获列表 ,并作为闭包的一部分,通过这种方式可以解决闭包和实例之间的强引用循环。
捕获列表定义了在闭包内部捕获一个或多个引用类型的规则。像解决两个实例的强引用循环一样,
将每一个捕获类型声明为弱引用(weak)或是无主引用(unowned),而不是声明为强引用。
至于是使用弱引用(weak)还是无主引用(unowned)取决于你代码中的不同部分之间的关系。
Swift强制要求
闭包内部使用 self 的成员,必须要写成 self.someProperty 或 self.someMethod()
(而不是仅仅写成 someProperty 或 someMethod())。这提醒你可能会一不小心就捕获了 self。
定义捕获列表
捕获列表中的每一项都是由 weak 或 unowned 关键字和实例的引用(如 self)
或是由其他值初始化的变量(如delegate = self.delegate!)成组构成的。
它们每一组都写在方括号中,组之间用逗号隔开。
lazy var someClosure: (Int, String) -> String = {
[unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in
// closure body goes here
}
如果一个闭包没有指定的参数列表或是返回值,则可以在上下文中推断出来,此时要把捕获列表放在闭包的开始位置,其后跟着关键字 in :
lazy var someClosure: () -> String = {
[unowned self, weak delegate = self.delegate!] in
// closure body goes here
}
弱引用和无主引用
当闭包和它捕获的实例始终互相持有对方的时候,将闭包的捕获定义为无主引用,那闭包和它捕获的实例总会同时释放。
相反的,将捕获定义弱引用时,捕获的引用也许会在将来的某一时刻变成 nil。弱引用总是可选类型的,
并且,当引用的实例释放的时候,弱引用自动变成 nil。 这就需要你在闭包内部检查它的值是否存在。
*/
class HTMLElement {
let name: String
let text: String?
// lazy var asHTML: () -> String = {
// if let text = self.text {
// return "<\(self.name)>\(text)</\(self.name)>"
// } else {
// return "<\(self.name) />"
// }
// }
lazy var asHTML: () -> String = {
[unowned self] in
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit {
print("\(name) is being deinitialized")
}
}
//let heading = HTMLElement(name: "h1")
//let defaultText = "some default text"
//heading.asHTML = {
// return "<\(heading.name)>\(heading.text ?? defaultText)</\(heading.name)>"
//}
//print(heading.asHTML())
//// "<h1>some default text</h1>"
//var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world")
//print(paragraph!.asHTML())
//// Prints "<p>hello, world</p>"
////置变量 paragraph 为 nil,断开它对 HTMLElement 实例的强引用,但是,HTMLElement 实例和它的闭包都不释放,这是因为强引用循环:
//paragraph = nil
////我们注意到 HTMLElement 实例的析构函数中的消息并没有打印
| apache-2.0 | 1aee03f8289fba6d10d8170a86024601 | 23.081761 | 98 | 0.691042 | 2.735 | false | false | false | false |
tidepool-org/nutshell-ios | Nutshell/Resources/NutshellStyles.swift | 1 | 15054 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import Foundation
import UIKit
extension UIColor {
convenience init(hex: UInt, opacity: Float) {
self.init(
red: CGFloat((hex & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hex & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(hex & 0x0000FF) / 255.0,
alpha: CGFloat(opacity)
)
}
convenience init(hex: UInt) {
self.init(hex: hex, opacity: 1.0)
}
}
open class Styles: NSObject {
// This table determines the background style design to color mapping in the UI. Setting "usage" variables in storyboards will determine color settings via this table; actual colors are defined below and can be changed globally there.
static var usageToBackgroundColor = [
// general usage
"brightBackground": brightBlueColor,
"darkBackground": darkPurpleColor,
"lightBackground": veryLightGreyColor,
"whiteBackground": whiteColor,
// login & signup
"brightBackgroundButton": brightBlueColor,
"userDataEntry": whiteColor,
// menu and account settings
"rowSeparator": dimmedDarkGreyColor,
"darkBackgroundButton": darkPurpleColor,
// add/edit event scenes
"addEditViewSaveButton": brightBlueColor,
]
// This table is used for mapping usage to font and font color for UI elements including fonts (UITextField, UILabel, UIButton). An entry may appear here as well as in the basic color mapping table above to set both font attributes as well as background coloring.
static var usageToFontWithColor = [
// general usage
"brightBackgroundButton": (largeRegularFont, whiteColor),
"darkBackgroundButton": (largeRegularFont, whiteColor),
// login & signup scenes
"userDataEntry": (mediumRegularFont, darkPurpleColor),
"dataEntryErrorFeedback": (smallSemiboldFont, redErrorColor),
"brightLinkText": (mediumRegularFont, brightBlueColor),
"networkDisconnectText" : (largeRegularFont, whiteColor),
// event list table scene
"eventListCellTitle": (mediumSemiboldFont, altDarkGreyColor),
"eventListCellLocation": (smallSemiboldFont, altDarkGreyColor),
"eventListCellRepeatCount": (mediumSemiboldFont, altDarkGreyColor),
"searchPlaceholder": (mediumLightFont, blackColor),
"searchText": (largeRegularFont, blackColor),
// grouped event list table scene
"groupedEventHeaderTitle": (mediumSemiboldFont, whiteColor),
"groupedEventHeaderLocation": (smallSemiboldFont, whiteColor),
"groupedEventHeaderButton": (mediumVerySmallSemiboldFont, whiteColor),
"groupedEventCellTitle": (mediumSmallSemiboldFont, darkGreyColor),
"groupedEventCellDate": (smallRegularFont, altDarkGreyColor),
// event detail view scene
"detailHeaderTitle": (mediumLargeBoldFont, whiteColor),
"detailHeaderNotes": (mediumRegularFont, whiteColor),
"detailHeaderDate": (smallRegularFont, whiteColor),
"detailHeaderLocation": (smallBoldFont, whiteColor),
"detailViewButtonText": (mediumSmallBoldFont, whiteColor),
"advisoryText": (mediumSemiboldFont, darkGreyColor),
"advisorySubtext": (mediumRegularFont, lightDarkGreyColor),
"greenLink": (mediumRegularFont, lightGreenColor),
// event detail graph area
"currentGraphDate" : (smallRegularFont, lightDarkGreyColor),
// add/edit event scenes
"addEditViewTitle": (mediumLargeBoldFont, whiteColor),
"addEditViewNotes": (mediumRegularFont, whiteColor),
"addEditViewHint": (smallRegularFont, whiteColor),
"addEditViewDate": (smallRegularFont, whiteColor),
"addEditViewLocation": (smallRegularFont, whiteColor),
"addEditViewSaveButton": (mediumBoldFont, whiteColor),
// account configuration scene
"sidebarSettingUserName": (mediumLargeBoldFont, blackColor),
"sidebarSettingItem": (mediumRegularFont, darkGreyColor),
"sidebarSettingItemSmall": (mediumSmallRegularFont, darkGreyColor),
"sidebarLogoutButton": (mediumSemiboldFont, darkGreyColor),
"sidebarOtherLinks": (mediumVerySmallSemiboldFont, darkGreyColor),
"sidebarSettingHKEnable": (mediumLargeBoldFont, darkGreyColor),
"sidebarSettingHKMainStatus": (mediumSmallSemiboldFont, darkGreyColor),
"sidebarSettingHKMinorStatus": (mediumSmallRegularFont, darkGreyColor),
]
class func backgroundImageofSize(_ size: CGSize, style: String) -> UIImage? {
if let backColor = Styles.usageToBackgroundColor[style] {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
// draw background
let rectanglePath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: size.width, height: size.height))
backColor.setFill()
rectanglePath.fill()
let backgroundImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return backgroundImage
} else {
return nil
}
}
//
// MARK: - Fonts
//
//// Cache
fileprivate struct FontCache {
static let verySmallRegularFont: UIFont = UIFont(name: "OpenSans", size: 10.0)!
static let smallRegularFont: UIFont = UIFont(name: "OpenSans", size: 12.0)!
static let mediumRegularFont: UIFont = UIFont(name: "OpenSans", size: 17.0)!
static let mediumSmallRegularFont: UIFont = UIFont(name: "OpenSans", size: 15.0)!
static let largeRegularFont: UIFont = UIFont(name: "OpenSans", size: 20.0)!
static let smallSemiboldFont: UIFont = UIFont(name: "OpenSans-Semibold", size: 12.0)!
static let mediumSemiboldFont: UIFont = UIFont(name: "OpenSans-Semibold", size: 17.0)!
static let mediumSmallSemiboldFont: UIFont = UIFont(name: "OpenSans-Semibold", size: 15.0)!
static let mediumVerySmallSemiboldFont: UIFont = UIFont(name: "OpenSans-Semibold", size: 14.0)!
static let veryLargeSemiboldFont: UIFont = UIFont(name: "OpenSans-Semibold", size: 25.5)!
static let smallBoldFont: UIFont = UIFont(name: "OpenSans-Bold", size: 12.0)!
static let mediumSmallBoldFont: UIFont = UIFont(name: "OpenSans-Bold", size: 14.0)!
static let mediumBoldFont: UIFont = UIFont(name: "OpenSans-Bold", size: 16.0)!
static let mediumLargeBoldFont: UIFont = UIFont(name: "OpenSans-Bold", size: 17.5)!
static let navTitleBoldFont: UIFont = UIFont(name: "OpenSans-Bold", size: 20.0)!
static let smallLightFont: UIFont = UIFont(name: "OpenSans-Light", size: 12.0)!
static let mediumLightFont: UIFont = UIFont(name: "OpenSans-Light", size: 17.0)!
// Fonts for special graph view
static let tinyRegularFont: UIFont = UIFont(name: "OpenSans", size: 8.5)!
static let verySmallSemiboldFont: UIFont = UIFont(name: "OpenSans-Semibold", size: 10.0)!
static let veryTinySemiboldFont: UIFont = UIFont(name: "OpenSans-Semibold", size: 8.0)!
}
static let uniformDateFormat: String = "MMM d, yyyy h:mm a"
open class var smallRegularFont: UIFont { return FontCache.smallRegularFont }
open class var mediumRegularFont: UIFont { return FontCache.mediumRegularFont }
open class var mediumSmallRegularFont: UIFont { return FontCache.mediumSmallRegularFont }
open class var largeRegularFont: UIFont { return FontCache.largeRegularFont }
open class var smallSemiboldFont: UIFont { return FontCache.smallSemiboldFont }
open class var mediumSemiboldFont: UIFont { return FontCache.mediumSemiboldFont }
open class var mediumSmallSemiboldFont: UIFont { return FontCache.mediumSmallSemiboldFont }
open class var mediumVerySmallSemiboldFont: UIFont { return FontCache.mediumVerySmallSemiboldFont }
open class var veryLargeSemiboldFont: UIFont { return FontCache.veryLargeSemiboldFont }
open class var smallBoldFont: UIFont { return FontCache.smallBoldFont }
open class var mediumSmallBoldFont: UIFont { return FontCache.mediumSmallBoldFont }
open class var mediumBoldFont: UIFont { return FontCache.mediumBoldFont }
open class var mediumLargeBoldFont: UIFont { return FontCache.mediumLargeBoldFont }
open class var navTitleBoldFont: UIFont { return FontCache.navTitleBoldFont }
open class var smallLightFont: UIFont { return FontCache.smallLightFont }
open class var mediumLightFont: UIFont { return FontCache.mediumLightFont }
// Fonts for special graph view
open class var verySmallRegularFont: UIFont { return FontCache.verySmallRegularFont }
open class var tinyRegularFont: UIFont { return FontCache.tinyRegularFont }
open class var verySmallSemiboldFont: UIFont { return FontCache.verySmallSemiboldFont }
open class var veryTinySemiboldFont: UIFont { return FontCache.veryTinySemiboldFont }
//
// MARK: - Background Colors
//
//// Cache
fileprivate struct ColorCache {
static let darkPurpleColor: UIColor = UIColor(hex: 0x281946)
static let brightBlueColor: UIColor = UIColor(hex: 0x627cff)
static let lightGreyColor: UIColor = UIColor(hex: 0xeaeff0)
static let veryLightGreyColor: UIColor = UIColor(hex: 0xf2f3f5)
static let redErrorColor: UIColor = UIColor(hex: 0xff354e)
static let pinkColor: UIColor = UIColor(hex: 0xf58fc7, opacity: 0.75)
static let purpleColor: UIColor = UIColor(hex: 0xb29ac9)
static let darkGreyColor: UIColor = UIColor(hex: 0x4a4a4a)
static let lightDarkGreyColor: UIColor = UIColor(hex: 0x5c5c5c)
static let altDarkGreyColor: UIColor = UIColor(hex: 0x4d4e4c)
static let mediumLightGreyColor: UIColor = UIColor(hex: 0xd0d3d4)
static let mediumGreyColor: UIColor = UIColor(hex: 0xb8b8b8)
static let whiteColor: UIColor = UIColor(hex: 0xffffff)
static let dimmedWhiteColor: UIColor = UIColor(hex: 0xffffff, opacity: 0.30)
static let blackColor: UIColor = UIColor(hex: 0x000000)
static let peachColor: UIColor = UIColor(hex: 0xf88d79)
static let peachDeleteColor: UIColor = UIColor(hex: 0xf66f56)
static let greenColor: UIColor = UIColor(hex: 0x98ca63)
static let lightGreenColor: UIColor = UIColor(hex: 0x4cd964)
static let lightBlueColor: UIColor = UIColor(hex: 0xc5e5f1)
static let blueColor: UIColor = UIColor(hex: 0x7aceef)
static let mediumBlueColor: UIColor = UIColor(hex: 0x6db7d4)
static let goldColor: UIColor = UIColor(hex: 0xffd382)
static let lineColor: UIColor = UIColor(hex: 0x281946)
static let goldStarColor: UIColor = UIColor(hex: 0xf8ad04)
static let greyStarColor: UIColor = UIColor(hex: 0xd0d3d4)
static let dimmedDarkGreyColor: UIColor = UIColor(hex: 0x979797, opacity: 0.5)
}
open class var darkPurpleColor: UIColor { return ColorCache.darkPurpleColor }
open class var brightBlueColor: UIColor { return ColorCache.brightBlueColor }
open class var lightGreyColor: UIColor { return ColorCache.lightGreyColor }
open class var veryLightGreyColor: UIColor { return ColorCache.veryLightGreyColor }
//
// MARK: - Text Colors
//
open class var pinkColor: UIColor { return ColorCache.pinkColor }
open class var redErrorColor: UIColor { return ColorCache.redErrorColor }
open class var darkGreyColor: UIColor { return ColorCache.darkGreyColor }
open class var lightDarkGreyColor: UIColor { return ColorCache.lightDarkGreyColor }
open class var altDarkGreyColor: UIColor { return ColorCache.altDarkGreyColor }
open class var mediumLightGreyColor: UIColor { return ColorCache.mediumLightGreyColor }
open class var mediumGreyColor: UIColor { return ColorCache.mediumGreyColor }
open class var whiteColor: UIColor { return ColorCache.whiteColor }
open class var dimmedWhiteColor: UIColor { return ColorCache.dimmedWhiteColor }
open class var blackColor: UIColor { return ColorCache.blackColor }
open class var peachColor: UIColor { return ColorCache.peachColor }
open class var peachDeleteColor: UIColor { return ColorCache.peachDeleteColor }
open class var purpleColor: UIColor { return ColorCache.purpleColor }
open class var greenColor: UIColor { return ColorCache.greenColor }
open class var lightGreenColor: UIColor { return ColorCache.lightGreenColor }
//
// MARK: - Graph Colors
//
// background, left side/right side
// public class var lightGreyColor: UIColor { return lightGreyColor }
// public class var veryLightGreyColor: UIColor { return veryLightGreyColor }
// axis text
// public class var darkGreyColor: UIColor { return darkGreyColor }
// insulin bar
open class var lightBlueColor: UIColor { return ColorCache.lightBlueColor }
open class var blueColor: UIColor { return ColorCache.blueColor }
// Open Sans Semibold 10: custom graph insulin amount text
open class var mediumBlueColor: UIColor { return ColorCache.mediumBlueColor }
// blood glucose data
// public class var peachColor: UIColor { return peachColor }
// public class var purpleColor: UIColor { return purpleColor }
// public class var greenColor: UIColor { return greenColor }
// event carb amount circle and vertical line
open class var goldColor: UIColor { return ColorCache.goldColor }
open class var lineColor: UIColor { return ColorCache.lineColor }
//
// MARK: - Misc Colors
//
// Icon: favorite star colors
open class var goldStarColor: UIColor { return ColorCache.goldStarColor }
open class var greyStarColor: UIColor { return ColorCache.greyStarColor }
// View: table row line separator
open class var dimmedDarkGreyColor: UIColor { return ColorCache.dimmedDarkGreyColor }
//
// MARK: - Strings
//
open class var placeholderTitleString: String { return "Meal name" }
open class var titleHintString: String { return "Simple and repeatable" }
open class var placeholderNotesString: String { return "Notes" }
open class var noteHintString: String { return "Sides, dessert, anything else?" }
open class var placeholderLocationString: String { return "Location" }
}
| bsd-2-clause | 51fef602b2e9953333e4bbe7aeb3a442 | 50.731959 | 267 | 0.707719 | 4.937357 | false | false | false | false |
egorio/devslopes-showcase | devslopes-showcase/Services/DataService.swift | 1 | 1089 | //
// DataService.swift
// devslopes-showcase
//
// Created by Egorio on 3/15/16.
// Copyright © 2016 Egorio. All rights reserved.
//
import Foundation
import Firebase
class DataService {
static let instance = DataService()
private var _firebase = Firebase(url: "https://egorio-showcase.firebaseio.com")
private var _users = Firebase(url: "https://egorio-showcase.firebaseio.com/users")
private var _posts = Firebase(url: "https://egorio-showcase.firebaseio.com/posts")
var firebase: Firebase {
return _firebase
}
var users: Firebase {
return _users
}
var posts: Firebase {
return _posts
}
var currentUser: Firebase {
let id = NSUserDefaults.standardUserDefaults().valueForKey(Auth.userKey) as! String
return Firebase(url: "\(_users)").childByAppendingPath(id)!
}
func createUser(id: String, user: [String: String]) {
users.childByAppendingPath(id).setValue(user)
}
func createPost(post: [String: AnyObject]) {
posts.childByAutoId().setValue(post)
}
} | mit | 22ef7dd6c71af19cb4266fcf57d2bf41 | 24.325581 | 91 | 0.65625 | 4.10566 | false | false | false | false |
sunweifeng/SWFKit | SWFKit/Classes/Utils/PresentationController/SWFPresentationController.swift | 1 | 1735 | //
// SWFPresentationController.swift
// SWFKit
//
// Created by 孙伟峰 on 2017/6/19.
// Copyright © 2017年 Sun Weifeng. All rights reserved.
//
import UIKit
public class SWFPresentationController: UIPresentationController {
lazy var dimmingView: UIView = {
let view = UIView(frame: self.containerView!.bounds)
view.backgroundColor = UIColor(white: 0, alpha: 0.5)
view.alpha = 0.0
return view
}()
override public func presentationTransitionWillBegin() {
guard let containerView = self.containerView,
let presentedView = self.presentedView else {
return
}
dimmingView.frame = containerView.bounds
containerView.addSubview(dimmingView)
dimmingView.addSubview(presentedView)
let transitionCoordinator = presentingViewController.transitionCoordinator
transitionCoordinator?.animate(alongsideTransition: { (context) in
self.dimmingView.alpha = 1.0
}, completion: { (context) in
})
}
override public func presentationTransitionDidEnd(_ completed: Bool) {
if !completed {
dimmingView.removeFromSuperview()
}
}
override public func dismissalTransitionWillBegin() {
let transitionCoordinator = presentingViewController.transitionCoordinator
transitionCoordinator?.animate(alongsideTransition: { (context) in
self.dimmingView.alpha = 0.0
}, completion: { (context) in
})
}
override public func dismissalTransitionDidEnd(_ completed: Bool) {
if completed {
self.dimmingView.removeFromSuperview()
}
}
}
| mit | f5a47d0211b5318df46e7b0d32c07451 | 29.821429 | 82 | 0.640788 | 5.462025 | false | false | false | false |
yuhao-ios/DouYuTVForSwift | DouYuTVForSwift/DouYuTVForSwift/Home/Controller/RecommendVC.swift | 1 | 3548 | //
// RecommendVC.swift
// DouYuTVForSwift
//
// Created by t4 on 17/4/24.
// Copyright © 2017年 t4. All rights reserved.
//
//推荐控制器
import UIKit
class RecommendVC: BaseAnchorViewController {
//MARK: - 懒加载
//创建ViewModel的属性
lazy var recommandVM : RecommendVM = RecommendVM()
//创建轮播图
fileprivate lazy var cycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x: 0, y: -(kCycleViewHeight+90), width: kMainWidth, height: kCycleViewHeight)
return cycleView
}()
//创建显示游戏名字的视图
fileprivate lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -90, width: kMainWidth, height: 90)
return gameView
}()
}
//MARK: - 设置UI界面
extension RecommendVC {
//重写父类的布局
override func loadUI() {
super.loadUI()
collectionView.addSubview(cycleView)
collectionView.addSubview(gameView)
//设置collectionView内边距
collectionView.contentInset = UIEdgeInsetsMake(kCycleViewHeight + 90, 0, 0, 0)
}
// 重写父类 请求网络数据 的方法
override func loadData(){
super.loadData()
//给父类赋值
baseAnchorVm = recommandVM
//加载推荐直播数据
recommandVM.requestData {
//1.刷新collectionView
self.collectionView .reloadData()
//2.
var groups = self.recommandVM.anchorGroups
//2.1.移除前两组数据 添加一组更多数据
groups.remove(at: 0)
groups.remove(at: 0)
let moreGroup = AnchorGroupModel()
moreGroup.tag_name = "更多"
groups.append(moreGroup)
//2.2给gameView设置数据
self.gameView.groups = groups
//3.数据加载完成 展示内容
self.showContentView()
}
//加载无限轮播数据
recommandVM.requestCycleData {
self.cycleView.cycles = self.recommandVM.cycles
}
}
}
//MARK: - UICollectionViewDataSource UICollectionViewDelegateFlowLayout
extension RecommendVC : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kItemWidth, height: kPrettyItemHeight)
}
return CGSize(width: kItemWidth, height: kNormalItemHeight)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//section = 1 返回自己的cell
if indexPath.section == 1 {
let prettyCell = collectionView.dequeueReusableCell(withReuseIdentifier:prettyCellID , for: indexPath) as! CollectionPrettyCell
// 2.设置数据
prettyCell.anchor = recommandVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return prettyCell
}
//否则返回父类的cell
return super.collectionView(collectionView, cellForItemAt: indexPath)
}
}
| mit | b9271f2903003e9a51082fbbf6c61e67 | 26.621849 | 160 | 0.608153 | 5.152038 | false | false | false | false |
sascha/DrawerController | KitchenSink/ExampleFiles/ViewControllers/ExampleSideDrawerViewController.swift | 1 | 13801 | // Copyright (c) 2017 evolved.io (http://evolved.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import DrawerController
enum DrawerSection: Int {
case viewSelection
case drawerWidth
case shadowToggle
case openDrawerGestures
case closeDrawerGestures
case centerHiddenInteraction
case stretchDrawer
}
class ExampleSideDrawerViewController: ExampleViewController, UITableViewDataSource, UITableViewDelegate {
var tableView: UITableView!
let drawerWidths: [CGFloat] = [160, 200, 240, 280, 320]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView = UITableView(frame: self.view.bounds, style: .grouped)
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.addSubview(self.tableView)
self.tableView.autoresizingMask = [ .flexibleWidth, .flexibleHeight ]
self.tableView.backgroundColor = UIColor(red: 110 / 255, green: 113 / 255, blue: 115 / 255, alpha: 1.0)
self.tableView.separatorStyle = .none
self.navigationController?.navigationBar.barTintColor = UIColor(red: 161 / 255, green: 164 / 255, blue: 166 / 255, alpha: 1.0)
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor(red: 55 / 255, green: 70 / 255, blue: 77 / 255, alpha: 1.0)]
self.view.backgroundColor = UIColor.clear
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// See https://github.com/sascha/DrawerController/issues/12
self.navigationController?.view.setNeedsLayout()
let integersRange = NSRange(location: 0, length: self.tableView.numberOfSections - 1)
self.tableView.reloadSections(IndexSet(integersIn: Range(integersRange) ?? 0..<0), with: .none)
}
override func contentSizeDidChange(_ size: String) {
self.tableView.reloadData()
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 7
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case DrawerSection.viewSelection.rawValue:
return 2
case DrawerSection.drawerWidth.rawValue:
return self.drawerWidths.count
case DrawerSection.shadowToggle.rawValue:
return 1
case DrawerSection.openDrawerGestures.rawValue:
return 3
case DrawerSection.closeDrawerGestures.rawValue:
return 6
case DrawerSection.centerHiddenInteraction.rawValue:
return 3
case DrawerSection.stretchDrawer.rawValue:
return 1
default:
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let CellIdentifier = "Cell"
var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) as UITableViewCell?
if cell == nil {
cell = SideDrawerTableViewCell(style: .default, reuseIdentifier: CellIdentifier)
cell.selectionStyle = .blue
}
switch (indexPath as NSIndexPath).section {
case DrawerSection.viewSelection.rawValue:
if (indexPath as NSIndexPath).row == 0 {
cell.textLabel?.text = "Quick View Change"
} else {
cell.textLabel?.text = "Full View Change"
}
cell.accessoryType = .disclosureIndicator
case DrawerSection.drawerWidth.rawValue:
// Implement in Subclass
break
case DrawerSection.shadowToggle.rawValue:
cell.textLabel?.text = "Show Shadow"
if self.evo_drawerController != nil && self.evo_drawerController!.showsShadows {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
case DrawerSection.openDrawerGestures.rawValue:
switch (indexPath as NSIndexPath).row {
case 0:
cell.textLabel?.text = "Pan Nav Bar"
if self.evo_drawerController != nil && self.evo_drawerController!.openDrawerGestureModeMask.contains(.panningNavigationBar) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
case 1:
cell.textLabel?.text = "Pan Center View"
if self.evo_drawerController != nil && self.evo_drawerController!.openDrawerGestureModeMask.contains(.panningCenterView) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
case 2:
cell.textLabel?.text = "Bezel Pan Center View"
if self.evo_drawerController != nil && self.evo_drawerController!.openDrawerGestureModeMask.contains(.bezelPanningCenterView) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
default:
break
}
case DrawerSection.closeDrawerGestures.rawValue:
switch (indexPath as NSIndexPath).row {
case 0:
cell.textLabel?.text = "Pan Nav Bar"
if self.evo_drawerController != nil && self.evo_drawerController!.closeDrawerGestureModeMask.contains(.panningNavigationBar) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
case 1:
cell.textLabel?.text = "Pan Center View"
if self.evo_drawerController != nil && self.evo_drawerController!.closeDrawerGestureModeMask.contains(.panningCenterView) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
case 2:
cell.textLabel?.text = "Bezel Pan Center View"
if self.evo_drawerController != nil && self.evo_drawerController!.closeDrawerGestureModeMask.contains(.bezelPanningCenterView) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
case 3:
cell.textLabel?.text = "Tap Nav Bar"
if self.evo_drawerController != nil && self.evo_drawerController!.closeDrawerGestureModeMask.contains(.tapNavigationBar) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
case 4:
cell.textLabel?.text = "Tap Center View"
if self.evo_drawerController != nil && self.evo_drawerController!.closeDrawerGestureModeMask.contains(.tapCenterView) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
case 5:
cell.textLabel?.text = "Pan Drawer View"
if self.evo_drawerController != nil && self.evo_drawerController!.closeDrawerGestureModeMask.contains(.panningDrawerView) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
default:
break
}
case DrawerSection.centerHiddenInteraction.rawValue:
cell.selectionStyle = .blue
switch (indexPath as NSIndexPath).row {
case 0:
cell.textLabel?.text = "None"
if self.evo_drawerController != nil && self.evo_drawerController!.centerHiddenInteractionMode == .none {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
case 1:
cell.textLabel?.text = "Full"
if self.evo_drawerController != nil && self.evo_drawerController!.centerHiddenInteractionMode == .full {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
case 2:
cell.textLabel?.text = "Nav Bar Only"
if self.evo_drawerController != nil && self.evo_drawerController!.centerHiddenInteractionMode == .navigationBarOnly {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
default:
break
}
case DrawerSection.stretchDrawer.rawValue:
cell.textLabel?.text = "Stretch Drawer"
if self.evo_drawerController != nil && self.evo_drawerController!.shouldStretchDrawer {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
default:
break
}
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case DrawerSection.viewSelection.rawValue:
return "New Center View"
case DrawerSection.drawerWidth.rawValue:
return "Drawer Width"
case DrawerSection.shadowToggle.rawValue:
return "Shadow"
case DrawerSection.openDrawerGestures.rawValue:
return "Drawer Open Gestures"
case DrawerSection.closeDrawerGestures.rawValue:
return "Drawer Close Gestures"
case DrawerSection.centerHiddenInteraction.rawValue:
return "Open Center Interaction Mode"
case DrawerSection.stretchDrawer.rawValue:
return "Stretch Drawer"
default:
return nil
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = SideDrawerSectionHeaderView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 56.0))
headerView.autoresizingMask = [ .flexibleHeight, .flexibleWidth ]
headerView.title = tableView.dataSource?.tableView?(tableView, titleForHeaderInSection: section)
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 56
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch (indexPath as NSIndexPath).section {
case DrawerSection.viewSelection.rawValue:
let center = ExampleCenterTableViewController()
let nav = UINavigationController(rootViewController: center)
if (indexPath as NSIndexPath).row % 2 == 0 {
self.evo_drawerController?.setCenter(nav, withCloseAnimation: true, completion: nil)
} else {
self.evo_drawerController?.setCenter(nav, withFullCloseAnimation: true, completion: nil)
}
case DrawerSection.drawerWidth.rawValue:
// Implement in Subclass
break
case DrawerSection.shadowToggle.rawValue:
self.evo_drawerController?.showsShadows = !self.evo_drawerController!.showsShadows
tableView.reloadSections(IndexSet(integer: (indexPath as NSIndexPath).section), with: .none)
case DrawerSection.openDrawerGestures.rawValue:
switch (indexPath as NSIndexPath).row {
case 0:
self.evo_drawerController?.openDrawerGestureModeMask.formSymmetricDifference(.panningNavigationBar)
case 1:
self.evo_drawerController?.openDrawerGestureModeMask.formSymmetricDifference(.panningCenterView)
case 2:
self.evo_drawerController?.openDrawerGestureModeMask.formSymmetricDifference(.bezelPanningCenterView)
default:
break
}
tableView.reloadRows(at: [indexPath], with: .none)
case DrawerSection.closeDrawerGestures.rawValue:
switch (indexPath as NSIndexPath).row {
case 0:
self.evo_drawerController?.closeDrawerGestureModeMask.formSymmetricDifference(.panningNavigationBar)
case 1:
self.evo_drawerController?.closeDrawerGestureModeMask.formSymmetricDifference(.panningCenterView)
case 2:
self.evo_drawerController?.closeDrawerGestureModeMask.formSymmetricDifference(.bezelPanningCenterView)
case 3:
self.evo_drawerController?.closeDrawerGestureModeMask.formSymmetricDifference(.tapNavigationBar)
case 4:
self.evo_drawerController?.closeDrawerGestureModeMask.formSymmetricDifference(.tapCenterView)
case 5:
self.evo_drawerController?.closeDrawerGestureModeMask.formSymmetricDifference(.panningDrawerView)
default:
break
}
tableView.reloadRows(at: [indexPath], with: .none)
case DrawerSection.centerHiddenInteraction.rawValue:
self.evo_drawerController?.centerHiddenInteractionMode = DrawerOpenCenterInteractionMode(rawValue: ((indexPath as NSIndexPath).row))!
tableView.reloadSections(IndexSet(integer: (indexPath as NSIndexPath).section), with: .none)
case DrawerSection.stretchDrawer.rawValue:
self.evo_drawerController?.shouldStretchDrawer = !self.evo_drawerController!.shouldStretchDrawer
tableView.reloadRows(at: [indexPath], with: .none)
default:
break
}
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
tableView.deselectRow(at: indexPath, animated: true)
}
}
| mit | 8c2abc1ccb2222f621b48efdcafc5579 | 37.442897 | 175 | 0.687631 | 5.073897 | false | false | false | false |
sareninden/DataSourceFramework | DataSourceFrameworkDemo/DataSourceFrameworkDemo/InsertingTableViewController.swift | 1 | 2529 | import Foundation
import UIKit
import DataSourceFramework
class InsertingTableViewController : BaseTableViewController {
// MARK:- Class Variables
// MARK:- Variables
// MARK:- Init and Dealloc
override init() {
super.init()
title = "Inserting"
tableView.editing = true
tableController.editingDelegate = self
tableController.titleForDeleteConfirmation = "Delete"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- Public Class Methods
// MARK:- Internal Instance Methods
override func loadData() {
for sectionIndex in 0 ..< 3 {
let section = sectionWithHeaderTitle("Section \(sectionIndex)")
for row in 0 ... 15 {
let item = TableItem(text: "Start row \(row)")
section.addItem(item)
}
tableController.addSection(section)
}
}
}
extension InsertingTableViewController : TableControllerEditingInterface {
func tableController(tableController : TableController, tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return .Insert
}
func tableController(tableController : TableController, tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let section = tableController.sectionAtIndex(indexPath.section)
switch editingStyle {
case .None: break
case .Insert:
let newIndexPath = NSIndexPath(forItem: indexPath.item + 1, inSection: indexPath.section)
let item = TableItem(text: "Inserted at row \(newIndexPath.item)")
item.editingStyle = .Delete
section.insertItem(item, atIndex: newIndexPath.item)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Automatic)
break
case .Delete:
section.removeItemAtIndex(indexPath.item)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
break
}
}
func tableController(tableController : TableController, tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
}
| gpl-3.0 | b61dffaab30770f5a81cc613339da1af | 31.012658 | 189 | 0.625148 | 6.3225 | false | false | false | false |
CodySchrank/HackingWithSwift | project33/Project33/AppDelegate.swift | 25 | 2904 | //
// AppDelegate.swift
// Project33
//
// Created by Hudzilla on 19/09/2015.
// Copyright © 2015 Paul Hudson. All rights reserved.
//
import CloudKit
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
UIApplication.sharedApplication().registerForRemoteNotifications()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
if let pushInfo = userInfo as? [String: NSObject] {
let notification = CKNotification(fromRemoteNotificationDictionary: pushInfo)
let ac = UIAlertController(title: "What's that Whistle?", message: notification.alertBody, preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
if let nc = window?.rootViewController as? UINavigationController {
if let vc = nc.visibleViewController {
vc.presentViewController(ac, animated: true, completion: nil)
}
}
}
}
}
| unlicense | df8edba9033765a6ddf07040528b8f3b | 45.079365 | 279 | 0.784361 | 4.987973 | false | false | false | false |
liyanhuadev/ObjectMapper-Plugin | Pods/ObjectMapper/Sources/HexColorTransform.swift | 15 | 3339 | //
// HexColorTransform.swift
// ObjectMapper
//
// Created by Vitaliy Kuzmenko on 10/10/16.
// Copyright © 2016 hearst. All rights reserved.
//
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
#if os(iOS) || os(tvOS) || os(watchOS) || os(macOS)
open class HexColorTransform: TransformType {
#if os(iOS) || os(tvOS) || os(watchOS)
public typealias Object = UIColor
#else
public typealias Object = NSColor
#endif
public typealias JSON = String
var prefix: Bool = false
var alpha: Bool = false
public init(prefixToJSON: Bool = false, alphaToJSON: Bool = false) {
alpha = alphaToJSON
prefix = prefixToJSON
}
open func transformFromJSON(_ value: Any?) -> Object? {
if let rgba = value as? String {
if rgba.hasPrefix("#") {
let index = rgba.index(rgba.startIndex, offsetBy: 1)
let hex = String(rgba[index...])
return getColor(hex: hex)
} else {
return getColor(hex: rgba)
}
}
return nil
}
open func transformToJSON(_ value: Object?) -> JSON? {
if let value = value {
return hexString(color: value)
}
return nil
}
fileprivate func hexString(color: Object) -> String {
let comps = color.cgColor.components!
let compsCount = color.cgColor.numberOfComponents
let r: Int
let g: Int
var b: Int
let a = Int(comps[compsCount - 1] * 255)
if compsCount == 4 { // RGBA
r = Int(comps[0] * 255)
g = Int(comps[1] * 255)
b = Int(comps[2] * 255)
} else { // Grayscale
r = Int(comps[0] * 255)
g = Int(comps[0] * 255)
b = Int(comps[0] * 255)
}
var hexString: String = ""
if prefix {
hexString = "#"
}
hexString += String(format: "%02X%02X%02X", r, g, b)
if alpha {
hexString += String(format: "%02X", a)
}
return hexString
}
fileprivate func getColor(hex: String) -> Object? {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
let scanner = Scanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexInt64(&hexValue) {
switch (hex.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
// Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8
return nil
}
} else {
// "Scan hex error
return nil
}
#if os(iOS) || os(tvOS) || os(watchOS)
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
#else
return NSColor(calibratedRed: red, green: green, blue: blue, alpha: alpha)
#endif
}
}
#endif
| mit | bbabf2c2ee5df431332f33b48754aec9 | 25.492063 | 87 | 0.605452 | 2.980357 | false | false | false | false |
loudnate/Loop | Loop/View Controllers/StatusTableViewController.swift | 1 | 60388 | //
// StatusTableViewController.swift
// Naterade
//
// Created by Nathan Racklyeft on 9/6/15.
// Copyright © 2015 Nathan Racklyeft. All rights reserved.
//
import UIKit
import HealthKit
import Intents
import LoopCore
import LoopKit
import LoopKitUI
import LoopUI
import SwiftCharts
import os.log
private extension RefreshContext {
static let all: Set<RefreshContext> = [.status, .glucose, .insulin, .carbs, .targets]
}
final class StatusTableViewController: ChartsTableViewController {
private let log = OSLog(category: "StatusTableViewController")
lazy var quantityFormatter: QuantityFormatter = QuantityFormatter()
override func viewDidLoad() {
super.viewDidLoad()
statusCharts.glucose.glucoseDisplayRange = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 100)...HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 175)
registerPumpManager()
let notificationCenter = NotificationCenter.default
notificationObservers += [
notificationCenter.addObserver(forName: .LoopDataUpdated, object: deviceManager.loopManager, queue: nil) { [weak self] note in
let rawContext = note.userInfo?[LoopDataManager.LoopUpdateContextKey] as! LoopDataManager.LoopUpdateContext.RawValue
let context = LoopDataManager.LoopUpdateContext(rawValue: rawContext)
DispatchQueue.main.async {
switch context {
case .none, .bolus?:
self?.refreshContext.formUnion([.status, .insulin])
case .preferences?:
self?.refreshContext.formUnion([.status, .targets])
case .carbs?:
self?.refreshContext.update(with: .carbs)
case .glucose?:
self?.refreshContext.formUnion([.glucose, .carbs])
case .tempBasal?:
self?.refreshContext.update(with: .insulin)
}
self?.hudView?.loopCompletionHUD.loopInProgress = false
self?.log.debug("[reloadData] from notification with context %{public}@", String(describing: context))
self?.reloadData(animated: true)
}
},
notificationCenter.addObserver(forName: .LoopRunning, object: deviceManager.loopManager, queue: nil) { [weak self] _ in
DispatchQueue.main.async {
self?.hudView?.loopCompletionHUD.loopInProgress = true
}
},
notificationCenter.addObserver(forName: .PumpManagerChanged, object: deviceManager, queue: nil) { [weak self] (notification: Notification) in
DispatchQueue.main.async {
self?.registerPumpManager()
self?.configurePumpManagerHUDViews()
}
},
notificationCenter.addObserver(forName: .PumpEventsAdded, object: deviceManager, queue: nil) { [weak self] (notification: Notification) in
DispatchQueue.main.async {
self?.refreshContext.update(with: .insulin)
self?.reloadData(animated: true)
}
}
]
if let gestureRecognizer = charts.gestureRecognizer {
tableView.addGestureRecognizer(gestureRecognizer)
}
tableView.estimatedRowHeight = 70
// Estimate an initial value
landscapeMode = UIScreen.main.bounds.size.width > UIScreen.main.bounds.size.height
// Toolbar
toolbarItems![0].accessibilityLabel = NSLocalizedString("Add Meal", comment: "The label of the carb entry button")
toolbarItems![0].tintColor = UIColor.COBTintColor
toolbarItems![4].accessibilityLabel = NSLocalizedString("Bolus", comment: "The label of the bolus entry button")
toolbarItems![4].tintColor = UIColor.doseTintColor
if #available(iOS 13.0, *) {
toolbarItems![8].image = UIImage(systemName: "gear")
}
toolbarItems![8].accessibilityLabel = NSLocalizedString("Settings", comment: "The label of the settings button")
toolbarItems![8].tintColor = UIColor.secondaryLabelColor
tableView.register(BolusProgressTableViewCell.nib(), forCellReuseIdentifier: BolusProgressTableViewCell.className)
addScenarioStepGestureRecognizers()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
if !visible {
refreshContext.formUnion(RefreshContext.all)
}
}
private var appearedOnce = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
updateBolusProgress()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !appearedOnce {
appearedOnce = true
if deviceManager.loopManager.authorizationRequired {
deviceManager.loopManager.authorize {
DispatchQueue.main.async {
self.log.debug("[reloadData] after HealthKit authorization")
self.reloadData()
}
}
}
}
onscreen = true
AnalyticsManager.shared.didDisplayStatusScreen()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
onscreen = false
if presentedViewController == nil {
navigationController?.setNavigationBarHidden(false, animated: animated)
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
refreshContext.update(with: .size(size))
super.viewWillTransition(to: size, with: coordinator)
}
// MARK: - State
override var active: Bool {
didSet {
hudView?.loopCompletionHUD.assertTimer(active)
updateHUDActive()
}
}
// This is similar to the visible property, but is set later, on viewDidAppear, to be
// suitable for animations that should be seen in their entirety.
var onscreen: Bool = false {
didSet {
updateHUDActive()
}
}
private var bolusState = PumpManagerStatus.BolusState.none {
didSet {
if oldValue != bolusState {
// Bolus starting
if case .inProgress = bolusState {
self.bolusProgressReporter = self.deviceManager.pumpManager?.createBolusProgressReporter(reportingOn: DispatchQueue.main)
}
refreshContext.update(with: .status)
self.reloadData(animated: true)
}
}
}
private var bolusProgressReporter: DoseProgressReporter?
private func updateBolusProgress() {
if let cell = tableView.cellForRow(at: IndexPath(row: StatusRow.status.rawValue, section: Section.status.rawValue)) as? BolusProgressTableViewCell {
cell.deliveredUnits = bolusProgressReporter?.progress.deliveredUnits
}
}
private func updateHUDActive() {
deviceManager.pumpManagerHUDProvider?.visible = active && onscreen
}
public var basalDeliveryState: PumpManagerStatus.BasalDeliveryState = .active(Date()) {
didSet {
if oldValue != basalDeliveryState {
log.debug("New basalDeliveryState: %@", String(describing: basalDeliveryState))
refreshContext.update(with: .status)
self.reloadData(animated: true)
}
}
}
// Toggles the display mode based on the screen aspect ratio. Should not be updated outside of reloadData().
private var landscapeMode = false
private var lastLoopError: Error?
private var reloading = false
private var refreshContext = RefreshContext.all
private var shouldShowHUD: Bool {
return !landscapeMode
}
private var shouldShowStatus: Bool {
return !landscapeMode && statusRowMode.hasRow
}
override func glucoseUnitDidChange() {
refreshContext = RefreshContext.all
}
private func registerPumpManager() {
if let pumpManager = deviceManager.pumpManager {
self.basalDeliveryState = pumpManager.status.basalDeliveryState
pumpManager.removeStatusObserver(self)
pumpManager.addStatusObserver(self, queue: .main)
}
}
private lazy var statusCharts = StatusChartsManager(colors: .default, settings: .default, traitCollection: self.traitCollection)
override func createChartsManager() -> ChartsManager {
return statusCharts
}
private func updateChartDateRange() {
let settings = deviceManager.loopManager.settings
// How far back should we show data? Use the screen size as a guide.
let availableWidth = (refreshContext.newSize ?? self.tableView.bounds.size).width - self.charts.fixedHorizontalMargin
let totalHours = floor(Double(availableWidth / settings.minimumChartWidthPerHour))
let futureHours = ceil((deviceManager.loopManager.insulinModelSettings?.model.effectDuration ?? .hours(4)).hours)
let historyHours = max(settings.statusChartMinimumHistoryDisplay.hours, totalHours - futureHours)
let date = Date(timeIntervalSinceNow: -TimeInterval(hours: historyHours))
let chartStartDate = Calendar.current.nextDate(after: date, matching: DateComponents(minute: 0), matchingPolicy: .strict, direction: .backward) ?? date
if charts.startDate != chartStartDate {
refreshContext.formUnion(RefreshContext.all)
}
charts.startDate = chartStartDate
charts.maxEndDate = chartStartDate.addingTimeInterval(.hours(totalHours))
charts.updateEndDate(charts.maxEndDate)
}
override func reloadData(animated: Bool = false) {
// This should be kept up to date immediately
hudView?.loopCompletionHUD.lastLoopCompleted = deviceManager.loopManager.lastLoopCompleted
guard !reloading && !deviceManager.loopManager.authorizationRequired else {
return
}
updateChartDateRange()
redrawCharts()
if case .bolusing = statusRowMode, bolusProgressReporter?.progress.isComplete == true {
refreshContext.update(with: .status)
}
if visible && active {
bolusProgressReporter?.addObserver(self)
} else {
bolusProgressReporter?.removeObserver(self)
}
guard active && visible && !refreshContext.isEmpty else {
return
}
log.debug("Reloading data with context: %@", String(describing: refreshContext))
let currentContext = refreshContext
var retryContext: Set<RefreshContext> = []
self.refreshContext = []
reloading = true
let reloadGroup = DispatchGroup()
var newRecommendedTempBasal: (recommendation: TempBasalRecommendation, date: Date)?
var glucoseValues: [StoredGlucoseSample]?
var predictedGlucoseValues: [GlucoseValue]?
var iobValues: [InsulinValue]?
var doseEntries: [DoseEntry]?
var totalDelivery: Double?
var cobValues: [CarbValue]?
let startDate = charts.startDate
let basalDeliveryState = self.basalDeliveryState
// TODO: Don't always assume currentContext.contains(.status)
reloadGroup.enter()
self.deviceManager.loopManager.getLoopState { (manager, state) -> Void in
predictedGlucoseValues = state.predictedGlucoseIncludingPendingInsulin ?? []
// Retry this refresh again if predicted glucose isn't available
if state.predictedGlucose == nil {
retryContext.update(with: .status)
}
/// Update the status HUDs immediately
let lastLoopCompleted = manager.lastLoopCompleted
let lastLoopError = state.error
// Net basal rate HUD
let netBasal: NetBasal?
if let basalSchedule = manager.basalRateScheduleApplyingOverrideHistory {
netBasal = basalDeliveryState.getNetBasal(basalSchedule: basalSchedule, settings: manager.settings)
} else {
netBasal = nil
}
self.log.debug("Update net basal to %{public}@", String(describing: netBasal))
DispatchQueue.main.async {
self.hudView?.loopCompletionHUD.dosingEnabled = manager.settings.dosingEnabled
self.lastLoopError = lastLoopError
if let netBasal = netBasal {
self.hudView?.basalRateHUD.setNetBasalRate(netBasal.rate, percent: netBasal.percent, at: netBasal.start)
}
}
// Display a recommended basal change only if we haven't completed recently, or we're in open-loop mode
if lastLoopCompleted == nil ||
lastLoopCompleted! < Date(timeIntervalSinceNow: .minutes(-6)) ||
!manager.settings.dosingEnabled
{
newRecommendedTempBasal = state.recommendedTempBasal
}
if currentContext.contains(.carbs) {
reloadGroup.enter()
manager.carbStore.getCarbsOnBoardValues(start: startDate, effectVelocities: manager.settings.dynamicCarbAbsorptionEnabled ? state.insulinCounteractionEffects : nil) { (values) in
DispatchQueue.main.async {
cobValues = values
reloadGroup.leave()
}
}
}
reloadGroup.leave()
}
if currentContext.contains(.glucose) {
reloadGroup.enter()
self.deviceManager.loopManager.glucoseStore.getCachedGlucoseSamples(start: startDate) { (values) -> Void in
DispatchQueue.main.async {
glucoseValues = values
reloadGroup.leave()
}
}
}
if currentContext.contains(.insulin) {
reloadGroup.enter()
deviceManager.loopManager.doseStore.getInsulinOnBoardValues(start: startDate) { (result) -> Void in
DispatchQueue.main.async {
switch result {
case .failure(let error):
self.log.error("DoseStore failed to get insulin on board values: %{public}@", String(describing: error))
retryContext.update(with: .insulin)
iobValues = []
case .success(let values):
iobValues = values
}
reloadGroup.leave()
}
}
reloadGroup.enter()
deviceManager.loopManager.doseStore.getNormalizedDoseEntries(start: startDate) { (result) -> Void in
DispatchQueue.main.async {
switch result {
case .failure(let error):
self.log.error("DoseStore failed to get normalized dose entries: %{public}@", String(describing: error))
retryContext.update(with: .insulin)
doseEntries = []
case .success(let doses):
doseEntries = doses
}
reloadGroup.leave()
}
}
reloadGroup.enter()
deviceManager.loopManager.doseStore.getTotalUnitsDelivered(since: Calendar.current.startOfDay(for: Date())) { (result) in
DispatchQueue.main.async {
switch result {
case .failure:
retryContext.update(with: .insulin)
totalDelivery = nil
case .success(let total):
totalDelivery = total.value
}
reloadGroup.leave()
}
}
}
if deviceManager.loopManager.settings.preMealTargetRange == nil {
preMealMode = nil
} else {
preMealMode = deviceManager.loopManager.settings.preMealTargetEnabled()
}
if !FeatureFlags.sensitivityOverridesEnabled, deviceManager.loopManager.settings.legacyWorkoutTargetRange == nil {
workoutMode = nil
} else {
workoutMode = deviceManager.loopManager.settings.nonPreMealOverrideEnabled()
}
reloadGroup.notify(queue: .main) {
/// Update the chart data
// Glucose
if let glucoseValues = glucoseValues {
self.statusCharts.setGlucoseValues(glucoseValues)
}
if let predictedGlucoseValues = predictedGlucoseValues {
self.statusCharts.setPredictedGlucoseValues(predictedGlucoseValues)
}
if let lastPoint = self.statusCharts.glucose.predictedGlucosePoints.last?.y {
self.eventualGlucoseDescription = String(describing: lastPoint)
} else {
self.eventualGlucoseDescription = nil
}
if currentContext.contains(.targets) {
self.statusCharts.targetGlucoseSchedule = self.deviceManager.loopManager.settings.glucoseTargetRangeSchedule
self.statusCharts.scheduleOverride = self.deviceManager.loopManager.settings.scheduleOverride
}
if self.statusCharts.scheduleOverride?.hasFinished() == true {
self.statusCharts.scheduleOverride = nil
}
let charts = self.statusCharts
// Active Insulin
if let iobValues = iobValues {
charts.setIOBValues(iobValues)
}
// Show the larger of the value either before or after the current date
if let maxValue = charts.iob.iobPoints.allElementsAdjacent(to: Date()).max(by: {
return $0.y.scalar < $1.y.scalar
}) {
self.currentIOBDescription = String(describing: maxValue.y)
} else {
self.currentIOBDescription = nil
}
// Insulin Delivery
if let doseEntries = doseEntries {
charts.setDoseEntries(doseEntries)
}
if let totalDelivery = totalDelivery {
self.totalDelivery = totalDelivery
}
// Active Carbohydrates
if let cobValues = cobValues {
charts.setCOBValues(cobValues)
}
if let index = charts.cob.cobPoints.closestIndex(priorTo: Date()) {
self.currentCOBDescription = String(describing: charts.cob.cobPoints[index].y)
} else {
self.currentCOBDescription = nil
}
self.tableView.beginUpdates()
if let hudView = self.hudView {
// Glucose HUD
if let glucose = self.deviceManager.loopManager.glucoseStore.latestGlucose {
let unit = self.statusCharts.glucose.glucoseUnit
hudView.glucoseHUD.setGlucoseQuantity(glucose.quantity.doubleValue(for: unit),
at: glucose.startDate,
unit: unit,
staleGlucoseAge: self.deviceManager.loopManager.settings.inputDataRecencyInterval,
sensor: self.deviceManager.sensorState
)
}
}
// Show/hide the table view rows
let statusRowMode = self.determineStatusRowMode(recommendedTempBasal: newRecommendedTempBasal)
self.updateHUDandStatusRows(statusRowMode: statusRowMode, newSize: currentContext.newSize, animated: animated)
self.redrawCharts()
self.tableView.endUpdates()
self.reloading = false
let reloadNow = !self.refreshContext.isEmpty
self.refreshContext.formUnion(retryContext)
// Trigger a reload if new context exists.
if reloadNow {
self.log.debug("[reloadData] due to context change during previous reload")
self.reloadData()
}
}
}
private enum Section: Int {
case hud = 0
case status
case charts
static let count = 3
}
// MARK: - Chart Section Data
private enum ChartRow: Int {
case glucose = 0
case iob
case dose
case cob
static let count = 4
}
// MARK: Glucose
private var eventualGlucoseDescription: String?
// MARK: IOB
private var currentIOBDescription: String?
// MARK: Dose
private var totalDelivery: Double?
// MARK: COB
private var currentCOBDescription: String?
// MARK: - Loop Status Section Data
private enum StatusRow: Int {
case status = 0
static let count = 1
}
private enum StatusRowMode {
case hidden
case recommendedTempBasal(tempBasal: TempBasalRecommendation, at: Date, enacting: Bool)
case scheduleOverrideEnabled(TemporaryScheduleOverride)
case enactingBolus
case bolusing(dose: DoseEntry)
case cancelingBolus
case pumpSuspended(resuming: Bool)
var hasRow: Bool {
switch self {
case .hidden:
return false
default:
return true
}
}
}
private var statusRowMode = StatusRowMode.hidden
private func determineStatusRowMode(recommendedTempBasal: (recommendation: TempBasalRecommendation, date: Date)? = nil) -> StatusRowMode {
let statusRowMode: StatusRowMode
if case .initiating = bolusState {
statusRowMode = .enactingBolus
} else if case .canceling = bolusState {
statusRowMode = .cancelingBolus
} else if case .suspended = basalDeliveryState {
statusRowMode = .pumpSuspended(resuming: false)
} else if self.basalDeliveryState == .resuming {
statusRowMode = .pumpSuspended(resuming: true)
} else if case .inProgress(let dose) = bolusState, dose.endDate.timeIntervalSinceNow > 0 {
statusRowMode = .bolusing(dose: dose)
} else if let (recommendation: tempBasal, date: date) = recommendedTempBasal {
statusRowMode = .recommendedTempBasal(tempBasal: tempBasal, at: date, enacting: false)
} else if let scheduleOverride = deviceManager.loopManager.settings.scheduleOverride,
scheduleOverride.context != .preMeal && scheduleOverride.context != .legacyWorkout,
!scheduleOverride.hasFinished()
{
statusRowMode = .scheduleOverrideEnabled(scheduleOverride)
} else {
statusRowMode = .hidden
}
return statusRowMode
}
private func updateHUDandStatusRows(statusRowMode: StatusRowMode, newSize: CGSize?, animated: Bool) {
let hudWasVisible = self.shouldShowHUD
let statusWasVisible = self.shouldShowStatus
let oldStatusRowMode = self.statusRowMode
self.statusRowMode = statusRowMode
if let newSize = newSize {
self.landscapeMode = newSize.width > newSize.height
}
let hudIsVisible = self.shouldShowHUD
let statusIsVisible = self.shouldShowStatus
tableView.beginUpdates()
switch (hudWasVisible, hudIsVisible) {
case (false, true):
self.tableView.insertRows(at: [IndexPath(row: 0, section: Section.hud.rawValue)], with: animated ? .top : .none)
case (true, false):
self.tableView.deleteRows(at: [IndexPath(row: 0, section: Section.hud.rawValue)], with: animated ? .top : .none)
default:
break
}
let statusIndexPath = IndexPath(row: StatusRow.status.rawValue, section: Section.status.rawValue)
switch (statusWasVisible, statusIsVisible) {
case (true, true):
switch (oldStatusRowMode, self.statusRowMode) {
case (.recommendedTempBasal(tempBasal: let oldTempBasal, at: let oldDate, enacting: let wasEnacting),
.recommendedTempBasal(tempBasal: let newTempBasal, at: let newDate, enacting: let isEnacting)):
// Ensure we have a change
guard oldTempBasal != newTempBasal || oldDate != newDate || wasEnacting != isEnacting else {
break
}
// If the rate or date change, reload the row
if oldTempBasal != newTempBasal || oldDate != newDate {
self.tableView.reloadRows(at: [statusIndexPath], with: animated ? .fade : .none)
} else if let cell = tableView.cellForRow(at: statusIndexPath) {
// If only the enacting state changed, update the activity indicator
if isEnacting {
let indicatorView = UIActivityIndicatorView(style: .default)
indicatorView.startAnimating()
cell.accessoryView = indicatorView
} else {
cell.accessoryView = nil
}
}
case (.enactingBolus, .enactingBolus):
break
case (.bolusing(let oldDose), .bolusing(let newDose)):
if oldDose != newDose {
self.tableView.reloadRows(at: [statusIndexPath], with: animated ? .fade : .none)
}
case (.pumpSuspended(resuming: let wasResuming), .pumpSuspended(resuming: let isResuming)):
if isResuming != wasResuming {
self.tableView.reloadRows(at: [statusIndexPath], with: animated ? .fade : .none)
}
default:
self.tableView.reloadRows(at: [statusIndexPath], with: animated ? .fade : .none)
}
case (false, true):
self.tableView.insertRows(at: [statusIndexPath], with: animated ? .top : .none)
case (true, false):
self.tableView.deleteRows(at: [statusIndexPath], with: animated ? .top : .none)
default:
break
}
tableView.endUpdates()
}
private func redrawCharts() {
tableView.beginUpdates()
self.charts.prerender()
for case let cell as ChartTableViewCell in self.tableView.visibleCells {
cell.reloadChart()
if let indexPath = self.tableView.indexPath(for: cell) {
self.tableView(self.tableView, updateSubtitleFor: cell, at: indexPath)
}
}
tableView.endUpdates()
}
// MARK: - Toolbar data
private var preMealMode: Bool? = nil {
didSet {
guard oldValue != preMealMode else {
return
}
if let preMealMode = preMealMode {
toolbarItems![2] = createPreMealButtonItem(selected: preMealMode)
} else {
toolbarItems![2].isEnabled = false
}
}
}
private var workoutMode: Bool? = nil {
didSet {
guard oldValue != workoutMode else {
return
}
if let workoutMode = workoutMode {
toolbarItems![6] = createWorkoutButtonItem(selected: workoutMode)
} else {
toolbarItems![6].isEnabled = false
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return Section.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .hud:
return shouldShowHUD ? 1 : 0
case .charts:
return ChartRow.count
case .status:
return shouldShowStatus ? StatusRow.count : 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch Section(rawValue: indexPath.section)! {
case .hud:
let cell = tableView.dequeueReusableCell(withIdentifier: HUDViewTableViewCell.className, for: indexPath) as! HUDViewTableViewCell
self.hudView = cell.hudView
return cell
case .charts:
let cell = tableView.dequeueReusableCell(withIdentifier: ChartTableViewCell.className, for: indexPath) as! ChartTableViewCell
switch ChartRow(rawValue: indexPath.row)! {
case .glucose:
cell.chartContentView.chartGenerator = { [weak self] (frame) in
return self?.statusCharts.glucoseChart(withFrame: frame)?.view
}
cell.titleLabel?.text = NSLocalizedString("Glucose", comment: "The title of the glucose and prediction graph")
case .iob:
cell.chartContentView.chartGenerator = { [weak self] (frame) in
return self?.statusCharts.iobChart(withFrame: frame)?.view
}
cell.titleLabel?.text = NSLocalizedString("Active Insulin", comment: "The title of the Insulin On-Board graph")
case .dose:
cell.chartContentView?.chartGenerator = { [weak self] (frame) in
return self?.statusCharts.doseChart(withFrame: frame)?.view
}
cell.titleLabel?.text = NSLocalizedString("Insulin Delivery", comment: "The title of the insulin delivery graph")
case .cob:
cell.chartContentView?.chartGenerator = { [weak self] (frame) in
return self?.statusCharts.cobChart(withFrame: frame)?.view
}
cell.titleLabel?.text = NSLocalizedString("Active Carbohydrates", comment: "The title of the Carbs On-Board graph")
}
self.tableView(tableView, updateSubtitleFor: cell, at: indexPath)
let alpha: CGFloat = charts.gestureRecognizer?.state == .possible ? 1 : 0
cell.titleLabel?.alpha = alpha
cell.subtitleLabel?.alpha = alpha
cell.subtitleLabel?.textColor = UIColor.secondaryLabelColor
return cell
case .status:
func getTitleSubtitleCell() -> TitleSubtitleTableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TitleSubtitleTableViewCell.className, for: indexPath) as! TitleSubtitleTableViewCell
cell.selectionStyle = .none
return cell
}
switch StatusRow(rawValue: indexPath.row)! {
case .status:
switch statusRowMode {
case .hidden:
let cell = getTitleSubtitleCell()
cell.titleLabel.text = nil
cell.subtitleLabel?.text = nil
cell.accessoryView = nil
return cell
case .recommendedTempBasal(tempBasal: let tempBasal, at: let date, enacting: let enacting):
let cell = getTitleSubtitleCell()
let timeFormatter = DateFormatter()
timeFormatter.dateStyle = .none
timeFormatter.timeStyle = .short
cell.titleLabel.text = NSLocalizedString("Recommended Basal", comment: "The title of the cell displaying a recommended temp basal value")
cell.subtitleLabel?.text = String(format: NSLocalizedString("%1$@ U/hour @ %2$@", comment: "The format for recommended temp basal rate and time. (1: localized rate number)(2: localized time)"), NumberFormatter.localizedString(from: NSNumber(value: tempBasal.unitsPerHour), number: .decimal), timeFormatter.string(from: date))
cell.selectionStyle = .default
if enacting {
let indicatorView = UIActivityIndicatorView(style: .default)
indicatorView.startAnimating()
cell.accessoryView = indicatorView
} else {
cell.accessoryView = nil
}
return cell
case .scheduleOverrideEnabled(let override):
let cell = getTitleSubtitleCell()
switch override.context {
case .preMeal, .legacyWorkout:
assertionFailure("Pre-meal and legacy workout modes should not produce status rows")
case .preset(let preset):
cell.titleLabel.text = String(format: NSLocalizedString("%@ %@", comment: "The format for an active override preset. (1: preset symbol)(2: preset name)"), preset.symbol, preset.name)
case .custom:
cell.titleLabel.text = NSLocalizedString("Custom Override", comment: "The title of the cell indicating a generic temporary override is enabled")
}
if override.isActive() {
switch override.duration {
case .finite:
let endTimeText = DateFormatter.localizedString(from: override.activeInterval.end, dateStyle: .none, timeStyle: .short)
cell.subtitleLabel.text = String(format: NSLocalizedString("until %@", comment: "The format for the description of a temporary override end date"), endTimeText)
case .indefinite:
cell.subtitleLabel.text = nil
}
} else {
let startTimeText = DateFormatter.localizedString(from: override.startDate, dateStyle: .none, timeStyle: .short)
cell.subtitleLabel.text = String(format: NSLocalizedString("starting at %@", comment: "The format for the description of a temporary override start date"), startTimeText)
}
cell.accessoryView = nil
return cell
case .enactingBolus:
let cell = getTitleSubtitleCell()
cell.titleLabel.text = NSLocalizedString("Starting Bolus", comment: "The title of the cell indicating a bolus is being sent")
cell.subtitleLabel.text = nil
let indicatorView = UIActivityIndicatorView(style: .default)
indicatorView.startAnimating()
cell.accessoryView = indicatorView
return cell
case .bolusing(let dose):
let progressCell = tableView.dequeueReusableCell(withIdentifier: BolusProgressTableViewCell.className, for: indexPath) as! BolusProgressTableViewCell
progressCell.selectionStyle = .none
progressCell.totalUnits = dose.programmedUnits
progressCell.tintColor = .doseTintColor
progressCell.unit = HKUnit.internationalUnit()
progressCell.deliveredUnits = bolusProgressReporter?.progress.deliveredUnits
return progressCell
case .cancelingBolus:
let cell = getTitleSubtitleCell()
cell.titleLabel.text = NSLocalizedString("Canceling Bolus", comment: "The title of the cell indicating a bolus is being canceled")
cell.subtitleLabel.text = nil
let indicatorView = UIActivityIndicatorView(style: .default)
indicatorView.startAnimating()
cell.accessoryView = indicatorView
return cell
case .pumpSuspended(let resuming):
let cell = getTitleSubtitleCell()
cell.titleLabel.text = NSLocalizedString("Pump Suspended", comment: "The title of the cell indicating the pump is suspended")
if resuming {
let indicatorView = UIActivityIndicatorView(style: .default)
indicatorView.startAnimating()
cell.accessoryView = indicatorView
cell.subtitleLabel.text = nil
} else {
cell.accessoryView = nil
cell.subtitleLabel.text = NSLocalizedString("Tap to Resume", comment: "The subtitle of the cell displaying an action to resume insulin delivery")
}
cell.selectionStyle = .default
return cell
}
}
}
}
private func tableView(_ tableView: UITableView, updateSubtitleFor cell: ChartTableViewCell, at indexPath: IndexPath) {
switch Section(rawValue: indexPath.section)! {
case .charts:
switch ChartRow(rawValue: indexPath.row)! {
case .glucose:
if let eventualGlucose = eventualGlucoseDescription {
cell.subtitleLabel?.text = String(format: NSLocalizedString("Eventually %@", comment: "The subtitle format describing eventual glucose. (1: localized glucose value description)"), eventualGlucose)
} else {
cell.subtitleLabel?.text = nil
}
case .iob:
if let currentIOB = currentIOBDescription {
cell.subtitleLabel?.text = currentIOB
} else {
cell.subtitleLabel?.text = nil
}
case .dose:
let integerFormatter = NumberFormatter()
integerFormatter.maximumFractionDigits = 0
if let total = totalDelivery,
let totalString = integerFormatter.string(from: total) {
cell.subtitleLabel?.text = String(format: NSLocalizedString("%@ U Total", comment: "The subtitle format describing total insulin. (1: localized insulin total)"), totalString)
} else {
cell.subtitleLabel?.text = nil
}
case .cob:
if let currentCOB = currentCOBDescription {
cell.subtitleLabel?.text = currentCOB
} else {
cell.subtitleLabel?.text = nil
}
}
case .hud, .status:
break
}
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch Section(rawValue: indexPath.section)! {
case .charts:
// Compute the height of the HUD, defaulting to 70
let hudHeight = ceil(hudView?.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height ?? 70)
var availableSize = max(tableView.bounds.width, tableView.bounds.height)
if #available(iOS 11.0, *) {
availableSize -= (tableView.safeAreaInsets.top + tableView.safeAreaInsets.bottom + hudHeight)
} else {
// 20: Status bar
// 44: Toolbar
availableSize -= hudHeight + 20 + 44
}
switch ChartRow(rawValue: indexPath.row)! {
case .glucose:
return max(106, 0.37 * availableSize)
case .iob, .dose, .cob:
return max(106, 0.21 * availableSize)
}
case .hud, .status:
return UITableView.automaticDimension
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch Section(rawValue: indexPath.section)! {
case .charts:
switch ChartRow(rawValue: indexPath.row)! {
case .glucose:
performSegue(withIdentifier: PredictionTableViewController.className, sender: indexPath)
case .iob, .dose:
performSegue(withIdentifier: InsulinDeliveryTableViewController.className, sender: indexPath)
case .cob:
performSegue(withIdentifier: CarbAbsorptionViewController.className, sender: indexPath)
}
case .status:
switch StatusRow(rawValue: indexPath.row)! {
case .status:
tableView.deselectRow(at: indexPath, animated: true)
switch statusRowMode {
case .recommendedTempBasal(tempBasal: let tempBasal, at: let date, enacting: let enacting) where !enacting:
self.updateHUDandStatusRows(statusRowMode: .recommendedTempBasal(tempBasal: tempBasal, at: date, enacting: true), newSize: nil, animated: true)
self.deviceManager.loopManager.enactRecommendedTempBasal { (error) in
DispatchQueue.main.async {
self.updateHUDandStatusRows(statusRowMode: .hidden, newSize: nil, animated: true)
if let error = error {
self.log.error("Failed to enact recommended temp basal: %{public}@", String(describing: error))
self.present(UIAlertController(with: error), animated: true)
} else {
self.refreshContext.update(with: .status)
self.log.debug("[reloadData] after manually enacting temp basal")
self.reloadData()
}
}
}
case .pumpSuspended(let resuming) where !resuming:
self.updateHUDandStatusRows(statusRowMode: .pumpSuspended(resuming: true) , newSize: nil, animated: true)
self.deviceManager.pumpManager?.resumeDelivery() { (error) in
DispatchQueue.main.async {
if let error = error {
let alert = UIAlertController(with: error, title: NSLocalizedString("Error Resuming", comment: "The alert title for a resume error"))
self.present(alert, animated: true, completion: nil)
if case .suspended = self.basalDeliveryState {
self.updateHUDandStatusRows(statusRowMode: .pumpSuspended(resuming: false), newSize: nil, animated: true)
}
} else {
self.updateHUDandStatusRows(statusRowMode: self.determineStatusRowMode(), newSize: nil, animated: true)
self.refreshContext.update(with: .insulin)
self.log.debug("[reloadData] after manually resuming suspend")
self.reloadData()
}
}
}
case .scheduleOverrideEnabled(let override):
let vc = AddEditOverrideTableViewController(glucoseUnit: statusCharts.glucose.glucoseUnit)
vc.inputMode = .editOverride(override)
vc.delegate = self
show(vc, sender: tableView.cellForRow(at: indexPath))
case .bolusing:
self.updateHUDandStatusRows(statusRowMode: .cancelingBolus, newSize: nil, animated: true)
self.deviceManager.pumpManager?.cancelBolus() { (result) in
DispatchQueue.main.async {
switch result {
case .success:
// show user confirmation and actual delivery amount?
break
case .failure(let error):
let alert = UIAlertController(with: error, title: NSLocalizedString("Error Canceling Bolus", comment: "The alert title for an error while canceling a bolus"))
self.present(alert, animated: true, completion: nil)
if case .inProgress(let dose) = self.bolusState {
self.updateHUDandStatusRows(statusRowMode: .bolusing(dose: dose), newSize: nil, animated: true)
} else {
self.updateHUDandStatusRows(statusRowMode: .hidden, newSize: nil, animated: true)
}
}
}
}
default:
break
}
}
case .hud:
break
}
}
// MARK: - Actions
override func restoreUserActivityState(_ activity: NSUserActivity) {
switch activity.activityType {
case NSUserActivity.newCarbEntryActivityType:
performSegue(withIdentifier: CarbEntryViewController.className, sender: activity)
default:
break
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
var targetViewController = segue.destination
if let navVC = targetViewController as? UINavigationController, let topViewController = navVC.topViewController {
targetViewController = topViewController
}
switch targetViewController {
case let vc as CarbAbsorptionViewController:
vc.deviceManager = deviceManager
vc.hidesBottomBarWhenPushed = true
case let vc as CarbEntryViewController:
vc.deviceManager = deviceManager
vc.glucoseUnit = statusCharts.glucose.glucoseUnit
vc.defaultAbsorptionTimes = deviceManager.loopManager.carbStore.defaultAbsorptionTimes
vc.preferredUnit = deviceManager.loopManager.carbStore.preferredUnit
if let activity = sender as? NSUserActivity {
vc.restoreUserActivityState(activity)
}
case let vc as InsulinDeliveryTableViewController:
vc.doseStore = deviceManager.loopManager.doseStore
vc.hidesBottomBarWhenPushed = true
case let vc as BolusViewController:
vc.deviceManager = deviceManager
vc.glucoseUnit = statusCharts.glucose.glucoseUnit
vc.configuration = .manualCorrection
AnalyticsManager.shared.didDisplayBolusScreen()
case let vc as OverrideSelectionViewController:
if deviceManager.loopManager.settings.futureOverrideEnabled() {
vc.scheduledOverride = deviceManager.loopManager.settings.scheduleOverride
}
vc.presets = deviceManager.loopManager.settings.overridePresets
vc.glucoseUnit = statusCharts.glucose.glucoseUnit
vc.delegate = self
case let vc as PredictionTableViewController:
vc.deviceManager = deviceManager
case let vc as SettingsTableViewController:
vc.dataManager = deviceManager
default:
break
}
}
@IBAction func unwindFromEditing(_ segue: UIStoryboardSegue) {}
@IBAction func unwindFromBolusViewController(_ segue: UIStoryboardSegue) {
guard let bolusViewController = segue.source as? BolusViewController else {
return
}
if let carbEntry = bolusViewController.updatedCarbEntry {
if #available(iOS 12.0, *) {
let interaction = INInteraction(intent: NewCarbEntryIntent(), response: nil)
interaction.donate { [weak self] (error) in
if let error = error {
self?.log.error("Failed to donate intent: %{public}@", String(describing: error))
}
}
}
deviceManager.loopManager.addCarbEntryAndRecommendBolus(carbEntry) { result in
DispatchQueue.main.async {
switch result {
case .success:
// Enact the user-entered bolus
if let bolus = bolusViewController.bolus, bolus > 0 {
self.deviceManager.enactBolus(units: bolus) { _ in }
}
case .failure(let error):
// Ignore bolus wizard errors
if error is CarbStore.CarbStoreError {
self.present(UIAlertController(with: error), animated: true)
} else {
self.log.error("Failed to add carb entry: %{public}@", String(describing: error))
}
}
}
}
} else if let bolus = bolusViewController.bolus, bolus > 0 {
self.deviceManager.enactBolus(units: bolus) { _ in }
}
}
@IBAction func unwindFromSettings(_ segue: UIStoryboardSegue) {
}
private func createPreMealButtonItem(selected: Bool) -> UIBarButtonItem {
let item = UIBarButtonItem(image: UIImage.preMealImage(selected: selected), style: .plain, target: self, action: #selector(togglePreMealMode(_:)))
item.accessibilityLabel = NSLocalizedString("Pre-Meal Targets", comment: "The label of the pre-meal mode toggle button")
if selected {
item.accessibilityTraits.insert(.selected)
item.accessibilityHint = NSLocalizedString("Disables", comment: "The action hint of the workout mode toggle button when enabled")
} else {
item.accessibilityHint = NSLocalizedString("Enables", comment: "The action hint of the workout mode toggle button when disabled")
}
item.tintColor = UIColor.COBTintColor
return item
}
private func createWorkoutButtonItem(selected: Bool) -> UIBarButtonItem {
let item = UIBarButtonItem(image: UIImage.workoutImage(selected: selected), style: .plain, target: self, action: #selector(toggleWorkoutMode(_:)))
item.accessibilityLabel = NSLocalizedString("Workout Targets", comment: "The label of the workout mode toggle button")
if selected {
item.accessibilityTraits.insert(.selected)
item.accessibilityHint = NSLocalizedString("Disables", comment: "The action hint of the workout mode toggle button when enabled")
} else {
item.accessibilityHint = NSLocalizedString("Enables", comment: "The action hint of the workout mode toggle button when disabled")
}
item.tintColor = UIColor.glucoseTintColor
return item
}
@IBAction func togglePreMealMode(_ sender: UIBarButtonItem) {
if preMealMode == true {
deviceManager.loopManager.settings.clearOverride(matching: .preMeal)
} else {
deviceManager.loopManager.settings.enablePreMealOverride(for: .hours(1))
}
}
@IBAction func toggleWorkoutMode(_ sender: UIBarButtonItem) {
if workoutMode == true {
deviceManager.loopManager.settings.clearOverride()
} else {
if FeatureFlags.sensitivityOverridesEnabled {
performSegue(withIdentifier: OverrideSelectionViewController.className, sender: toolbarItems![6])
} else {
let vc = UIAlertController(workoutDurationSelectionHandler: { duration in
let startDate = Date()
self.deviceManager.loopManager.settings.enableLegacyWorkoutOverride(at: startDate, for: duration)
})
present(vc, animated: true, completion: nil)
}
}
}
// MARK: - HUDs
@IBOutlet var hudView: HUDView? {
didSet {
guard let hudView = hudView, hudView != oldValue else {
return
}
let statusTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showLastError(_:)))
hudView.loopCompletionHUD.addGestureRecognizer(statusTapGestureRecognizer)
hudView.loopCompletionHUD.accessibilityHint = NSLocalizedString("Shows last loop error", comment: "Loop Completion HUD accessibility hint")
let glucoseTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(openCGMApp(_:)))
hudView.glucoseHUD.addGestureRecognizer(glucoseTapGestureRecognizer)
if deviceManager.cgmManager?.appURL != nil {
hudView.glucoseHUD.accessibilityHint = NSLocalizedString("Launches CGM app", comment: "Glucose HUD accessibility hint")
}
configurePumpManagerHUDViews()
hudView.loopCompletionHUD.stateColors = .loopStatus
hudView.glucoseHUD.stateColors = .cgmStatus
hudView.glucoseHUD.tintColor = .glucoseTintColor
hudView.basalRateHUD.tintColor = .doseTintColor
refreshContext.update(with: .status)
self.log.debug("[reloadData] after hudView loaded")
reloadData()
}
}
private func configurePumpManagerHUDViews() {
if let hudView = hudView {
hudView.removePumpManagerProvidedViews()
if let pumpManagerHUDProvider = deviceManager.pumpManagerHUDProvider {
let views = pumpManagerHUDProvider.createHUDViews()
for view in views {
addViewToHUD(view)
}
pumpManagerHUDProvider.visible = active && onscreen
} else {
let reservoirView = ReservoirVolumeHUDView.instantiate()
let batteryView = BatteryLevelHUDView.instantiate()
for view in [reservoirView, batteryView] {
addViewToHUD(view)
}
}
}
}
private func addViewToHUD(_ view: BaseHUDView) {
if let hudView = hudView {
let hudTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(hudViewTapped(_:)))
view.addGestureRecognizer(hudTapGestureRecognizer)
view.stateColors = .pumpStatus
hudView.addHUDView(view)
}
}
@objc private func showLastError(_: Any) {
var error: Error? = nil
// First, check whether we have a device error after the most recent completion date
if let deviceError = deviceManager.lastError,
deviceError.date > (hudView?.loopCompletionHUD.lastLoopCompleted ?? .distantPast)
{
error = deviceError.error
} else if let lastLoopError = lastLoopError {
error = lastLoopError
}
if error != nil {
let alertController = UIAlertController(with: error!)
let manualLoopAction = UIAlertAction(title: NSLocalizedString("Retry", comment: "The button text for attempting a manual loop"), style: .default, handler: { _ in
self.deviceManager.loopManager.loop()
})
alertController.addAction(manualLoopAction)
present(alertController, animated: true)
}
}
@objc private func openCGMApp(_: Any) {
if let url = deviceManager.cgmManager?.appURL, UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
}
}
@objc private func hudViewTapped(_ sender: UIGestureRecognizer) {
if let hudSubView = sender.view as? BaseHUDView,
let pumpManagerHUDProvider = deviceManager.pumpManagerHUDProvider,
let action = pumpManagerHUDProvider.didTapOnHUDView(hudSubView)
{
switch action {
case .presentViewController(let vc):
var completionNotifyingVC = vc
completionNotifyingVC.completionDelegate = self
self.present(vc, animated: true, completion: nil)
case .openAppURL(let url):
UIApplication.shared.open(url)
}
}
}
// MARK: - Testing scenarios
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if let testingScenariosManager = deviceManager.testingScenariosManager, !testingScenariosManager.scenarioURLs.isEmpty {
if motion == .motionShake {
presentScenarioSelector()
}
}
}
private func presentScenarioSelector() {
guard let testingScenariosManager = deviceManager.testingScenariosManager else {
return
}
let vc = TestingScenariosTableViewController(scenariosManager: testingScenariosManager)
present(UINavigationController(rootViewController: vc), animated: true)
}
private func addScenarioStepGestureRecognizers() {
if debugEnabled {
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(stepActiveScenarioForward))
leftSwipe.direction = .left
let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(stepActiveScenarioBackward))
rightSwipe.direction = .right
let toolBar = navigationController!.toolbar!
toolBar.addGestureRecognizer(leftSwipe)
toolBar.addGestureRecognizer(rightSwipe)
}
}
@objc private func stepActiveScenarioForward() {
deviceManager.testingScenariosManager?.stepActiveScenarioForward { _ in }
}
@objc private func stepActiveScenarioBackward() {
deviceManager.testingScenariosManager?.stepActiveScenarioBackward { _ in }
}
}
extension StatusTableViewController: CompletionDelegate {
func completionNotifyingDidComplete(_ object: CompletionNotifying) {
if let vc = object as? UIViewController, presentedViewController === vc {
dismiss(animated: true, completion: nil)
}
}
}
extension StatusTableViewController: PumpManagerStatusObserver {
func pumpManager(_ pumpManager: PumpManager, didUpdate status: PumpManagerStatus, oldStatus: PumpManagerStatus) {
dispatchPrecondition(condition: .onQueue(.main))
log.default("PumpManager:%{public}@ did update status", String(describing: type(of: pumpManager)))
self.basalDeliveryState = status.basalDeliveryState
self.bolusState = status.bolusState
}
}
extension StatusTableViewController: DoseProgressObserver {
func doseProgressReporterDidUpdate(_ doseProgressReporter: DoseProgressReporter) {
updateBolusProgress()
if doseProgressReporter.progress.isComplete {
// Bolus ended
self.bolusProgressReporter = nil
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
self.bolusState = .none
self.reloadData(animated: true)
})
}
}
}
extension StatusTableViewController: OverrideSelectionViewControllerDelegate {
func overrideSelectionViewController(_ vc: OverrideSelectionViewController, didUpdatePresets presets: [TemporaryScheduleOverridePreset]) {
deviceManager.loopManager.settings.overridePresets = presets
}
func overrideSelectionViewController(_ vc: OverrideSelectionViewController, didConfirmOverride override: TemporaryScheduleOverride) {
deviceManager.loopManager.settings.scheduleOverride = override
}
func overrideSelectionViewController(_ vc: OverrideSelectionViewController, didCancelOverride override: TemporaryScheduleOverride) {
deviceManager.loopManager.settings.scheduleOverride = nil
}
}
extension StatusTableViewController: AddEditOverrideTableViewControllerDelegate {
func addEditOverrideTableViewController(_ vc: AddEditOverrideTableViewController, didSaveOverride override: TemporaryScheduleOverride) {
deviceManager.loopManager.settings.scheduleOverride = override
}
func addEditOverrideTableViewController(_ vc: AddEditOverrideTableViewController, didCancelOverride override: TemporaryScheduleOverride) {
deviceManager.loopManager.settings.scheduleOverride = nil
}
}
| apache-2.0 | c7f4b5ebcfe0fae2a8115ab2a587eef7 | 41.797307 | 345 | 0.599864 | 5.852588 | false | false | false | false |
GuiminChu/HishowZone-iOS | HiShow/General/View/ImageViewingController.swift | 1 | 11807 | import UIKit
import Kingfisher
class ImageViewingController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate {
private lazy var scrollView: UIScrollView = {
let view = UIScrollView(frame: self.view.bounds)
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.delegate = self
view.showsHorizontalScrollIndicator = false
view.zoomScale = 1.0
view.maximumZoomScale = 8.0
view.isScrollEnabled = false
return view
}()
private let duration = 0.3
private let zoomScale: CGFloat = 3.0
private let dismissDistance: CGFloat = 100.0
private var image: UIImage!
private var imageView: AnimatedImageView!
private var imageInfo: ImageInfo!
private var startFrame: CGRect!
private var snapshotView: UIView!
private var originalScrollViewCenter: CGPoint = .zero
private var singleTapGestureRecognizer: UITapGestureRecognizer!
private var panGestureRecognizer: UIPanGestureRecognizer!
private var longPressGestureRecognizer: UILongPressGestureRecognizer!
private var doubleTapGestureRecognizer: UITapGestureRecognizer!
init(imageInfo: ImageInfo) {
super.init(nibName: nil, bundle: nil)
self.imageInfo = imageInfo
image = imageInfo.image
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
let referenceFrameCurrentView = imageInfo.referenceView.convert(imageInfo.referenceRect, to: view)
imageView = AnimatedImageView(frame: referenceFrameCurrentView)
imageView.isUserInteractionEnabled = true
imageView.image = image
// imageView.originalData = imageInfo.originalData // used for gif image
imageView.contentMode = .scaleAspectFill // reset content mode
imageView.backgroundColor = .clear
setupGestureRecognizers()
view.backgroundColor = .black
}
func presented(by viewController: UIViewController) {
view.isUserInteractionEnabled = false
snapshotView = snapshotParentmostViewController(of: viewController)
snapshotView.alpha = 0.1
view.insertSubview(snapshotView, at: 0)
let referenceFrameInWindow = imageInfo.referenceView.convert(imageInfo.referenceRect, to: nil)
view.addSubview(imageView) // will move to scroll view after transition finishes
viewController.present(self, animated: false) {
self.imageView.frame = referenceFrameInWindow
self.startFrame = referenceFrameInWindow
UIView.animate(withDuration: self.duration, delay: 0, options: .beginFromCurrentState, animations: {
self.imageView.frame = self.resizedFrame(forImageSize: self.image.size)
self.imageView.center = CGPoint(x: self.view.bounds.width / 2.0, y: self.view.bounds.height / 2.0)
}, completion: { (_) in
self.scrollView.addSubview(self.imageView)
self.updateScrollViewAndImageView()
self.view.isUserInteractionEnabled = true
})
}
}
private func dismiss() {
view.isUserInteractionEnabled = false
let imageFrame = view.convert(imageView.frame, from: scrollView)
imageView.removeFromSuperview()
imageView.frame = imageFrame
view.addSubview(imageView)
scrollView.removeFromSuperview()
UIView.animate(withDuration: duration, delay: 0, options: .beginFromCurrentState, animations: {
self.imageView.frame = self.startFrame
}) { (_) in
self.dismiss(animated: false, completion: nil)
}
}
// MARK: - Private
private func cancelImageDragging() {
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: {
self.imageView.center = CGPoint(x: self.scrollView.contentSize.width / 2.0, y: self.scrollView.contentSize.height / 2.0)
self.updateScrollViewAndImageView()
self.snapshotView.alpha = 0.1
}, completion: nil)
}
private func setupGestureRecognizers() {
doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(doubleTap(_:)))
doubleTapGestureRecognizer.numberOfTapsRequired = 2
doubleTapGestureRecognizer.delegate = self
longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress))
longPressGestureRecognizer.delegate = self
singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(singleTap))
singleTapGestureRecognizer.require(toFail: doubleTapGestureRecognizer)
singleTapGestureRecognizer.require(toFail: longPressGestureRecognizer)
singleTapGestureRecognizer.delegate = self
view.addGestureRecognizer(singleTapGestureRecognizer)
view.addGestureRecognizer(longPressGestureRecognizer)
view.addGestureRecognizer(doubleTapGestureRecognizer)
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(pan(_:)))
panGestureRecognizer.maximumNumberOfTouches = 1
panGestureRecognizer.delegate = self
scrollView.addGestureRecognizer(panGestureRecognizer)
}
private func snapshotParentmostViewController(of viewController: UIViewController) -> UIView {
var snapshot = viewController.view
if var presentingViewController = viewController.view.window!.rootViewController {
while presentingViewController.presentedViewController != nil {
presentingViewController = presentingViewController.presentedViewController!
}
snapshot = presentingViewController.view.snapshotView(afterScreenUpdates: true)
}
return snapshot ?? UIView()
}
private func updateScrollViewAndImageView() {
scrollView.frame = view.bounds
imageView.frame = resizedFrame(forImageSize: image.size)
scrollView.contentSize = imageView.frame.size
scrollView.contentInset = contentInsetForScrollView(withZoomScale: scrollView.zoomScale)
}
private func contentInsetForScrollView(withZoomScale zoomScale: CGFloat) -> UIEdgeInsets {
let boundsWidth = scrollView.bounds.width
let boundsHeight = scrollView.bounds.height
let contentWidth = image.size.width
let contentHeight = image.size.height
var minContentHeight: CGFloat!
var minContentWidth: CGFloat!
if (contentHeight / contentWidth) < (boundsHeight / boundsWidth) {
minContentWidth = boundsWidth
minContentHeight = minContentWidth * (contentHeight / contentWidth)
} else {
minContentHeight = boundsHeight
minContentWidth = minContentHeight * (contentWidth / contentHeight)
}
minContentWidth = minContentWidth * zoomScale
minContentHeight = minContentHeight * zoomScale
let hDiff = max(boundsWidth - minContentWidth, 0)
let vDiff = max(boundsHeight - minContentHeight, 0)
let inset = UIEdgeInsets(top: vDiff / 2.0, left: hDiff / 2.0, bottom: vDiff / 2.0, right: hDiff / 2.0)
return inset
}
private func resizedFrame(forImageSize size: CGSize) -> CGRect {
guard size.width > 0, size.height > 0 else {
return .zero
}
var frame = view.bounds
let nativeWidth = size.width
let nativeHeight = size.height
var targetWidth = frame.width * scrollView.zoomScale
var targetHeight = frame.height * scrollView.zoomScale
if (targetHeight / targetWidth) < (nativeHeight / nativeWidth) {
targetWidth = targetHeight * (nativeWidth / nativeHeight)
} else {
targetHeight = targetWidth * (nativeHeight / nativeWidth)
}
frame = CGRect(x: 0, y: 0, width: targetWidth, height: targetHeight)
return frame
}
// MARK: - Gesture Recognizer Actions
@objc
private func singleTap() {
dismiss()
}
@objc
private func pan(_ sender: UIPanGestureRecognizer) {
let translation = sender.translation(in: sender.view)
let translationDistance = sqrt(pow(translation.x, 2) + pow(translation.y, 2))
switch sender.state {
case .began:
originalScrollViewCenter = scrollView.center
case .changed:
scrollView.center = CGPoint(x: originalScrollViewCenter.x + translation.x, y: originalScrollViewCenter.y + translation.y)
snapshotView.alpha = min(max(translationDistance / dismissDistance * 0.5, 0.1), 0.6)
default:
if translationDistance > dismissDistance {
dismiss()
} else {
cancelImageDragging()
}
}
}
@objc
private func longPress() {
let activityViewController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
present(activityViewController, animated: true, completion: nil)
}
@objc
private func doubleTap(_ sender: UITapGestureRecognizer) {
let rawLocation = sender.location(in: sender.view)
let point = scrollView.convert(rawLocation, from: sender.view)
var targetZoomRect: CGRect
var targetInsets: UIEdgeInsets
if scrollView.zoomScale == 1.0 {
let zoomWidth = view.bounds.width / zoomScale
let zoomHeight = view.bounds.height / zoomScale
targetZoomRect = CGRect(x: point.x - zoomWidth * 0.5, y: point.y - zoomHeight * 0.5, width: zoomWidth, height: zoomHeight)
targetInsets = contentInsetForScrollView(withZoomScale: zoomScale)
} else {
let zoomWidth = view.bounds.width * scrollView.zoomScale
let zoomHeight = view.bounds.height * scrollView.zoomScale
targetZoomRect = CGRect(x: point.x - zoomWidth * 0.5, y: point.y - zoomHeight * 0.5, width: zoomWidth, height: zoomHeight)
targetInsets = contentInsetForScrollView(withZoomScale: 1.0)
}
view.isUserInteractionEnabled = false
CATransaction.begin()
CATransaction.setCompletionBlock {
self.scrollView.contentInset = targetInsets
self.view.isUserInteractionEnabled = true
}
scrollView.zoom(to: targetZoomRect, animated: true)
CATransaction.commit()
}
// MARK: - UIGestureRecognizerDelegate
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gestureRecognizer == panGestureRecognizer, scrollView.zoomScale != 1.0 {
return false
}
return true
}
// MARK: - UIScrollViewDelegate
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
scrollView.contentInset = contentInsetForScrollView(withZoomScale: scrollView.zoomScale)
scrollView.isScrollEnabled = true
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
scrollView.isScrollEnabled = (scale > 1)
scrollView.contentInset = contentInsetForScrollView(withZoomScale: scale)
}
}
struct ImageInfo {
var image: UIImage!
var originalData: Data?
var referenceRect: CGRect!
var referenceView: UIView!
}
| mit | 26b4ad05387287494bcae6a879df9015 | 42.568266 | 183 | 0.672567 | 5.566714 | false | false | false | false |
cacawai/Tap2Read | tap2read/Pods/SugarRecord/SugarRecord/Source/CoreData/Storages/CoreDataDefaultStorage.swift | 1 | 7929 | import Foundation
import CoreData
public class CoreDataDefaultStorage: Storage {
// MARK: - Attributes
internal let store: CoreDataStore
internal var objectModel: NSManagedObjectModel! = nil
internal var persistentStore: NSPersistentStore! = nil
internal var persistentStoreCoordinator: NSPersistentStoreCoordinator! = nil
internal var rootSavingContext: NSManagedObjectContext! = nil
// MARK: - Storage conformance
public var description: String {
get {
return "CoreDataDefaultStorage"
}
}
public var type: StorageType = .coreData
public var mainContext: Context!
private var _saveContext: Context!
public var saveContext: Context! {
if let context = self._saveContext {
return context
}
let _context = cdContext(withParent: .context(self.rootSavingContext), concurrencyType: .privateQueueConcurrencyType, inMemory: false)
_context.observe(inMainThread: true) { [weak self] (notification) -> Void in
(self?.mainContext as? NSManagedObjectContext)?.mergeChanges(fromContextDidSave: notification as Notification)
}
self._saveContext = _context
return _context
}
public var memoryContext: Context! {
let _context = cdContext(withParent: .context(self.rootSavingContext), concurrencyType: .privateQueueConcurrencyType, inMemory: true)
return _context
}
public func operation<T>(_ operation: @escaping (_ context: Context, _ save: @escaping () -> Void) throws -> T) throws -> T {
let context: NSManagedObjectContext = self.saveContext as! NSManagedObjectContext
var _error: Error!
var returnedObject: T!
context.performAndWait {
do {
returnedObject = try operation(context, { () -> Void in
do {
try context.save()
}
catch {
_error = error
}
self.rootSavingContext.performAndWait({
if self.rootSavingContext.hasChanges {
do {
try self.rootSavingContext.save()
}
catch {
_error = error
}
}
})
})
} catch {
_error = error
}
}
if let error = _error {
throw error
}
return returnedObject
}
public func removeStore() throws {
try FileManager.default.removeItem(at: store.path() as URL)
_ = try? FileManager.default.removeItem(atPath: "\(store.path().absoluteString)-shm")
_ = try? FileManager.default.removeItem(atPath: "\(store.path().absoluteString)-wal")
}
// MARK: - Init
public convenience init(store: CoreDataStore, model: CoreDataObjectModel, migrate: Bool = true) throws {
try self.init(store: store, model: model, migrate: migrate, versionController: VersionController())
}
internal init(store: CoreDataStore, model: CoreDataObjectModel, migrate: Bool = true, versionController: VersionController) throws {
self.store = store
self.objectModel = model.model()!
self.persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: objectModel)
self.persistentStore = try cdInitializeStore(store: store, storeCoordinator: persistentStoreCoordinator, migrate: migrate)
self.rootSavingContext = cdContext(withParent: .coordinator(self.persistentStoreCoordinator), concurrencyType: .privateQueueConcurrencyType, inMemory: false)
self.mainContext = cdContext(withParent: .context(self.rootSavingContext), concurrencyType: .mainQueueConcurrencyType, inMemory: false)
#if DEBUG
versionController.check()
#endif
}
// MARK: - Public
#if os(iOS) || os(tvOS) || os(watchOS)
public func observable<T: NSManagedObject>(request: FetchRequest<T>) -> RequestObservable<T> where T:Equatable {
return CoreDataObservable(request: request, context: self.mainContext as! NSManagedObjectContext)
}
#endif
}
// MARK: - Internal
internal func cdContext(withParent parent: CoreDataContextParent?, concurrencyType: NSManagedObjectContextConcurrencyType, inMemory: Bool) -> NSManagedObjectContext {
var context: NSManagedObjectContext?
if inMemory {
context = NSManagedObjectMemoryContext(concurrencyType: concurrencyType)
}
else {
context = NSManagedObjectContext(concurrencyType: concurrencyType)
}
if let parent = parent {
switch parent {
case .context(let parentContext):
context!.parent = parentContext
case .coordinator(let storeCoordinator):
context!.persistentStoreCoordinator = storeCoordinator
}
}
context!.observeToGetPermanentIDsBeforeSaving()
return context!
}
internal func cdInitializeStore(store: CoreDataStore, storeCoordinator: NSPersistentStoreCoordinator, migrate: Bool) throws -> NSPersistentStore {
try cdCreateStoreParentPathIfNeeded(store: store)
let options = migrate ? CoreDataOptions.migration : CoreDataOptions.basic
return try cdAddPersistentStore(store: store, storeCoordinator: storeCoordinator, options: options.dict())
}
internal func cdCreateStoreParentPathIfNeeded(store: CoreDataStore) throws {
let databaseParentPath = store.path().deletingLastPathComponent()
try FileManager.default.createDirectory(at: databaseParentPath, withIntermediateDirectories: true, attributes: nil)
}
internal func cdAddPersistentStore(store: CoreDataStore, storeCoordinator: NSPersistentStoreCoordinator, options: [String: AnyObject]) throws -> NSPersistentStore {
var addStore: ((_ store: CoreDataStore, _ storeCoordinator: NSPersistentStoreCoordinator, _ options: [String: AnyObject], _ cleanAndRetryIfMigrationFails: Bool) throws -> NSPersistentStore)?
addStore = { (store: CoreDataStore, coordinator: NSPersistentStoreCoordinator, options: [String: AnyObject], retry: Bool) throws -> NSPersistentStore in
var persistentStore: NSPersistentStore?
var error: NSError?
coordinator.performAndWait({ () -> Void in
do {
persistentStore = try storeCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: store.path() as URL, options: options)
}
catch let _error as NSError {
error = _error
}
})
if let error = error {
let isMigrationError = error.code == NSPersistentStoreIncompatibleVersionHashError || error.code == NSMigrationMissingSourceModelError
if isMigrationError && retry {
_ = try? cdCleanStoreFilesAfterFailedMigration(store: store)
return try addStore!(store, coordinator, options, false)
}
else {
throw error
}
}
else if let persistentStore = persistentStore {
return persistentStore
}
throw CoreDataError.persistenceStoreInitialization
}
return try addStore!(store, storeCoordinator, options, true)
}
internal func cdCleanStoreFilesAfterFailedMigration(store: CoreDataStore) throws {
let rawUrl: String = store.path().absoluteString
let shmSidecar: NSURL = NSURL(string: rawUrl.appending("-shm"))!
let walSidecar: NSURL = NSURL(string: rawUrl.appending("-wal"))!
try FileManager.default.removeItem(at: store.path() as URL)
try FileManager.default.removeItem(at: shmSidecar as URL)
try FileManager.default.removeItem(at: walSidecar as URL)
}
| mit | ef1cebfabf9416538f4fc04822dfac57 | 41.175532 | 195 | 0.652037 | 5.611465 | false | false | false | false |
sachin004/firefox-ios | Client/Frontend/Settings/SettingsTableViewController.swift | 1 | 42628 | /* 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 Account
import Base32
import Shared
import UIKit
import XCGLogger
private var ShowDebugSettings: Bool = false
private var DebugSettingsClickCount: Int = 0
// The following are only here because we use master for L10N and otherwise these strings would disappear from the v1.0 release
private let Bug1204635_S1 = NSLocalizedString("Clear Everything", tableName: "ClearPrivateData", comment: "Title of the Clear private data dialog.")
private let Bug1204635_S2 = NSLocalizedString("Are you sure you want to clear all of your data? This will also close all open tabs.", tableName: "ClearPrivateData", comment: "Message shown in the dialog prompting users if they want to clear everything")
private let Bug1204635_S3 = NSLocalizedString("Clear", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to Clear private data dialog")
private let Bug1204635_S4 = NSLocalizedString("Cancel", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to cancel clear private data dialog")
// A base TableViewCell, to help minimize initialization and allow recycling.
class SettingsTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
indentationWidth = 0
layoutMargins = UIEdgeInsetsZero
// So that the seperator line goes all the way to the left edge.
separatorInset = UIEdgeInsetsZero
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// A base setting class that shows a title. You probably want to subclass this, not use it directly.
class Setting {
private var _title: NSAttributedString?
// The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy.
var url: NSURL? { return nil }
// The title shown on the pref.
var title: NSAttributedString? { return _title }
// An optional second line of text shown on the pref.
var status: NSAttributedString? { return nil }
// Whether or not to show this pref.
var hidden: Bool { return false }
var style: UITableViewCellStyle { return .Subtitle }
var accessoryType: UITableViewCellAccessoryType { return .None }
// Called when the cell is setup. Call if you need the default behaviour.
func onConfigureCell(cell: UITableViewCell) {
cell.detailTextLabel?.attributedText = status
cell.textLabel?.attributedText = title
cell.accessoryType = accessoryType
cell.accessoryView = nil
}
// Called when the pref is tapped.
func onClick(navigationController: UINavigationController?) { return }
// Helper method to set up and push a SettingsContentViewController
func setUpAndPushSettingsContentViewController(navigationController: UINavigationController?) {
if let url = self.url {
let viewController = SettingsContentViewController()
viewController.settingsTitle = self.title
viewController.url = url
navigationController?.pushViewController(viewController, animated: true)
}
}
init(title: NSAttributedString? = nil) {
self._title = title
}
}
// A setting in the sections panel. Contains a sublist of Settings
class SettingSection : Setting {
private let children: [Setting]
init(title: NSAttributedString? = nil, children: [Setting]) {
self.children = children
super.init(title: title)
}
var count: Int {
var count = 0
for setting in children {
if !setting.hidden {
count++
}
}
return count
}
subscript(val: Int) -> Setting? {
var i = 0
for setting in children {
if !setting.hidden {
if i == val {
return setting
}
i++
}
}
return nil
}
}
// A helper class for settings with a UISwitch.
// Takes and optional settingsDidChange callback and status text.
class BoolSetting: Setting {
private let prefKey: String
private let prefs: Prefs
private let defaultValue: Bool
private let settingDidChange: ((Bool) -> Void)?
private let statusText: String?
init(prefs: Prefs, prefKey: String, defaultValue: Bool, titleText: String, statusText: String? = nil, settingDidChange: ((Bool) -> Void)? = nil) {
self.prefs = prefs
self.prefKey = prefKey
self.defaultValue = defaultValue
self.settingDidChange = settingDidChange
self.statusText = statusText
super.init(title: NSAttributedString(string: titleText, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override var status: NSAttributedString? {
if let text = statusText {
return NSAttributedString(string: text, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewHeaderTextColor])
} else {
return nil
}
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = prefs.boolForKey(prefKey) ?? defaultValue
cell.accessoryView = control
}
@objc func switchValueChanged(control: UISwitch) {
prefs.setBool(control.on, forKey: prefKey)
settingDidChange?(control.on)
}
}
// A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to
// the fxAccount happen.
private class AccountSetting: Setting, FxAContentViewControllerDelegate {
unowned var settings: SettingsTableViewController
var profile: Profile {
return settings.profile
}
override var title: NSAttributedString? { return nil }
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
private override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
if settings.profile.getAccount() != nil {
cell.selectionStyle = .None
}
}
override var accessoryType: UITableViewCellAccessoryType { return .None }
func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void {
if data["keyFetchToken"].asString == nil || data["unwrapBKey"].asString == nil {
// The /settings endpoint sends a partial "login"; ignore it entirely.
NSLog("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.")
return
}
// TODO: Error handling.
let account = FirefoxAccount.fromConfigurationAndJSON(profile.accountConfiguration, data: data)!
settings.profile.setAccount(account)
// Reload the data to reflect the new Account immediately.
settings.tableView.reloadData()
// And start advancing the Account state in the background as well.
settings.SELrefresh()
settings.navigationController?.popToRootViewControllerAnimated(true)
}
func contentViewControllerDidCancel(viewController: FxAContentViewController) {
NSLog("didCancel")
settings.navigationController?.popToRootViewControllerAnimated(true)
}
}
private class WithAccountSetting: AccountSetting {
override var hidden: Bool { return !profile.hasAccount() }
}
private class WithoutAccountSetting: AccountSetting {
override var hidden: Bool { return profile.hasAccount() }
}
// Sync setting for connecting a Firefox Account. Shown when we don't have an account.
private class ConnectSetting: WithoutAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Sign In", comment: "Text message / button in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
let viewController = FxAContentViewController()
viewController.delegate = self
viewController.url = settings.profile.accountConfiguration.signInURL
navigationController?.pushViewController(viewController, animated: true)
}
}
// Sync setting for disconnecting a Firefox Account. Shown when we have an account.
private class DisconnectSetting: WithAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .None }
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Log Out", comment: "Button in settings screen to disconnect from your account"), attributes: [NSForegroundColorAttributeName: UIConstants.DestructiveRed])
}
override func onClick(navigationController: UINavigationController?) {
let alertController = UIAlertController(
title: NSLocalizedString("Log Out?", comment: "Title of the 'log out firefox account' alert"),
message: NSLocalizedString("Firefox will stop syncing with your account, but won’t delete any of your browsing data on this device.", comment: "Text of the 'log out firefox account' alert"),
preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(
UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel button in the 'log out firefox account' alert"), style: .Cancel) { (action) in
// Do nothing.
})
alertController.addAction(
UIAlertAction(title: NSLocalizedString("Log Out", comment: "Disconnect button in the 'log out firefox account' alert"), style: .Destructive) { (action) in
self.settings.profile.removeAccount()
// Refresh, to show that we no longer have an Account immediately.
self.settings.SELrefresh()
})
navigationController?.presentViewController(alertController, animated: true, completion: nil)
}
}
private class SyncNowSetting: WithAccountSetting {
private let syncNowTitle = NSAttributedString(string: NSLocalizedString("Sync Now", comment: "Sync Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIConstants.DefaultStandardFont])
private let syncingTitle = NSAttributedString(string: NSLocalizedString("Syncing…", comment: "Syncing Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(UIConstants.DefaultStandardFontSize, weight: UIFontWeightRegular)])
override var accessoryType: UITableViewCellAccessoryType { return .None }
override var style: UITableViewCellStyle { return .Value1 }
override var title: NSAttributedString? {
return profile.syncManager.isSyncing ? syncingTitle : syncNowTitle
}
override var status: NSAttributedString? {
if let timestamp = profile.prefs.timestampForKey(PrefsKeys.KeyLastSyncFinishTime) {
let label = NSLocalizedString("Last synced: %@", comment: "Last synced time label beside Sync Now setting option. Argument is the relative date string.")
let formattedLabel = String(format: label, NSDate.fromTimestamp(timestamp).toRelativeTimeString())
let attributedString = NSMutableAttributedString(string: formattedLabel)
let attributes = [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(12, weight: UIFontWeightRegular)]
let range = NSMakeRange(0, attributedString.length)
attributedString.setAttributes(attributes, range: range)
return attributedString
}
return nil
}
override func onConfigureCell(cell: UITableViewCell) {
cell.textLabel?.attributedText = title
cell.detailTextLabel?.attributedText = status
cell.accessoryType = accessoryType
cell.accessoryView = nil
cell.userInteractionEnabled = !profile.syncManager.isSyncing
}
override func onClick(navigationController: UINavigationController?) {
profile.syncManager.syncEverything()
}
}
// Sync setting that shows the current Firefox Account status.
private class AccountStatusSetting: WithAccountSetting {
override var accessoryType: UITableViewCellAccessoryType {
if let account = profile.getAccount() {
switch account.actionNeeded {
case .NeedsVerification:
// We link to the resend verification email page.
return .DisclosureIndicator
case .NeedsPassword:
// We link to the re-enter password page.
return .DisclosureIndicator
case .None, .NeedsUpgrade:
// In future, we'll want to link to /settings and an upgrade page, respectively.
return .None
}
}
return .DisclosureIndicator
}
override var title: NSAttributedString? {
if let account = profile.getAccount() {
return NSAttributedString(string: account.email, attributes: [NSFontAttributeName: UIConstants.DefaultStandardFontBold, NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
return nil
}
override var status: NSAttributedString? {
if let account = profile.getAccount() {
switch account.actionNeeded {
case .None:
return nil
case .NeedsVerification:
return NSAttributedString(string: NSLocalizedString("Verify your email address.", comment: "Text message in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
case .NeedsPassword:
let string = NSLocalizedString("Enter your password to connect.", comment: "Text message in the settings table view")
let range = NSRange(location: 0, length: string.characters.count)
let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1)
let attrs = [NSForegroundColorAttributeName : orange]
let res = NSMutableAttributedString(string: string)
res.setAttributes(attrs, range: range)
return res
case .NeedsUpgrade:
let string = NSLocalizedString("Upgrade Firefox to connect.", comment: "Text message in the settings table view")
let range = NSRange(location: 0, length: string.characters.count)
let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1)
let attrs = [NSForegroundColorAttributeName : orange]
let res = NSMutableAttributedString(string: string)
res.setAttributes(attrs, range: range)
return res
}
}
return nil
}
override func onClick(navigationController: UINavigationController?) {
let viewController = FxAContentViewController()
viewController.delegate = self
if let account = profile.getAccount() {
switch account.actionNeeded {
case .NeedsVerification:
let cs = NSURLComponents(URL: account.configuration.settingsURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs?.URL
case .NeedsPassword:
let cs = NSURLComponents(URL: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs?.URL
case .None, .NeedsUpgrade:
// In future, we'll want to link to /settings and an upgrade page, respectively.
return
}
}
navigationController?.pushViewController(viewController, animated: true)
}
}
// For great debugging!
private class RequirePasswordDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsPassword {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.makeSeparated()
settings.tableView.reloadData()
}
}
// For great debugging!
private class RequireUpgradeDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsUpgrade {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.makeDoghouse()
settings.tableView.reloadData()
}
}
// For great debugging!
private class ForgetSyncAuthStateDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let _ = profile.getAccount() {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.syncAuthState.invalidate()
settings.tableView.reloadData()
}
}
// For great debugging!
private class HiddenSetting: Setting {
let settings: SettingsTableViewController
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var hidden: Bool {
return !ShowDebugSettings
}
}
extension NSFileManager {
public func removeItemInDirectory(directory: String, named: String) throws {
if let file = NSURL.fileURLWithPath(directory).URLByAppendingPathComponent(named).path {
try self.removeItemAtPath(file)
}
}
}
private class DeleteExportedDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
do {
try NSFileManager.defaultManager().removeItemInDirectory(documentsPath, named: "browser.db")
} catch {
print("Couldn't delete exported data: \(error).")
}
}
}
private class ExportBrowserDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
if let browserDB = NSURL.fileURLWithPath(documentsPath).URLByAppendingPathComponent("browser.db").path {
do {
try self.settings.profile.files.copy("browser.db", toAbsolutePath: browserDB)
} catch {
print("Couldn't export browser data: \(error).")
}
}
}
}
// Show the current version of Firefox
private class VersionSetting : Setting {
let settings: SettingsTableViewController
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var title: NSAttributedString? {
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as! String
return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
private override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.selectionStyle = .None
}
override func onClick(navigationController: UINavigationController?) {
if AppConstants.BuildChannel != .Aurora {
DebugSettingsClickCount += 1
if DebugSettingsClickCount >= 5 {
DebugSettingsClickCount = 0
ShowDebugSettings = !ShowDebugSettings
settings.tableView.reloadData()
}
}
}
}
// Opens the the license page in a new tab
private class LicenseAndAcknowledgementsSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
return NSURL(string: WebServer.sharedInstance.URLForResource("license", module: "about"))
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens about:rights page in the content view controller
private class YourRightsSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Your Rights", comment: "Your Rights settings section title"), attributes:
[NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
return NSURL(string: "https://www.mozilla.org/about/legal/terms/firefox/")
}
private override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens the on-boarding screen again
private class ShowIntroductionSetting: Setting {
let profile: Profile
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
navigationController?.dismissViewControllerAnimated(true, completion: {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
appDelegate.browserViewController.presentIntroViewController(true)
}
})
}
}
private class SendFeedbackSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Show an input.mozilla.org page where people can submit feedback"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
return NSURL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)")
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens the the SUMO page in a new tab
private class OpenSupportPageSetting: Setting {
init() {
super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
navigationController?.dismissViewControllerAnimated(true, completion: {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
let rootNavigationController = appDelegate.rootViewController
rootNavigationController.popViewControllerAnimated(true)
if let url = NSURL(string: "https://support.mozilla.org/products/ios") {
appDelegate.browserViewController.openURLInNewTab(url)
}
}
})
}
}
// Opens the search settings pane
private class SearchSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
override var style: UITableViewCellStyle { return .Value1 }
override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
let viewController = SearchSettingsTableViewController()
viewController.model = profile.searchEngines
navigationController?.pushViewController(viewController, animated: true)
}
}
private class LoginsSetting: Setting {
let profile: Profile
var tabManager: TabManager!
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
self.tabManager = settings.tabManager
let loginsTitle = NSLocalizedString("Logins", comment: "Label used as an item in Settings. When touched, the user will be navigated to the Logins/Password manager.")
super.init(title: NSAttributedString(string: loginsTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
}
}
private class ClearPrivateDataSetting: Setting {
let profile: Profile
var tabManager: TabManager!
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
self.tabManager = settings.tabManager
let clearTitle = NSLocalizedString("Clear Private Data", comment: "Label used as an item in Settings. When touched it will open a dialog prompting the user to make sure they want to clear all of their private data.")
super.init(title: NSAttributedString(string: clearTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
let viewController = ClearPrivateDataTableViewController()
viewController.profile = profile
viewController.tabManager = tabManager
navigationController?.pushViewController(viewController, animated: true)
}
}
private class PrivacyPolicySetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
return NSURL(string: "https://www.mozilla.org/privacy/firefox/")
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// The base settings view controller.
class SettingsTableViewController: UITableViewController {
private let Identifier = "CellIdentifier"
private let SectionHeaderIdentifier = "SectionHeaderIdentifier"
private var settings = [SettingSection]()
var profile: Profile!
var tabManager: TabManager!
override func viewDidLoad() {
super.viewDidLoad()
let privacyTitle = NSLocalizedString("Privacy", comment: "Privacy section title")
let accountDebugSettings: [Setting]
if AppConstants.BuildChannel != .Aurora {
accountDebugSettings = [
// Debug settings:
RequirePasswordDebugSetting(settings: self),
RequireUpgradeDebugSetting(settings: self),
ForgetSyncAuthStateDebugSetting(settings: self),
]
} else {
accountDebugSettings = []
}
let prefs = profile.prefs
var generalSettings = [
SearchSetting(settings: self),
BoolSetting(prefs: prefs, prefKey: "blockPopups", defaultValue: true,
titleText: NSLocalizedString("Block Pop-up Windows", comment: "Block pop-up windows setting")),
BoolSetting(prefs: prefs, prefKey: "saveLogins", defaultValue: true,
titleText: NSLocalizedString("Save Logins", comment: "Setting to enable the built-in password manager")),
]
// There is nothing to show in the Customize section if we don't include the compact tab layout
// setting on iPad. When more options are added that work on both device types, this logic can
// be changed.
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
generalSettings += [
BoolSetting(prefs: prefs, prefKey: "CompactTabLayout", defaultValue: true,
titleText: NSLocalizedString("Use Compact Tabs", comment: "Setting to enable compact tabs in the tab overview"))
]
}
settings += [
SettingSection(title: nil, children: [
// Without a Firefox Account:
ConnectSetting(settings: self),
// With a Firefox Account:
AccountStatusSetting(settings: self),
SyncNowSetting(settings: self)
] + accountDebugSettings),
SettingSection(title: NSAttributedString(string: NSLocalizedString("General", comment: "General settings section title")), children: generalSettings)
]
var privacySettings: [Setting] = [LoginsSetting(settings: self), ClearPrivateDataSetting(settings: self)]
if #available(iOS 9, *) {
privacySettings += [
BoolSetting(prefs: prefs,
prefKey: "settings.closePrivateTabs",
defaultValue: false,
titleText: NSLocalizedString("Close Private Tabs", tableName: "PrivateBrowsing", comment: "Setting for closing private tabs"),
statusText: NSLocalizedString("When Leaving Private Browsing", tableName: "PrivateBrowsing", comment: "Will be displayed in Settings under 'Close Private Tabs'"))
]
}
privacySettings += [
BoolSetting(prefs: prefs, prefKey: "crashreports.send.always", defaultValue: false,
titleText: NSLocalizedString("Send Crash Reports", comment: "Setting to enable the sending of crash reports"),
settingDidChange: { configureActiveCrashReporter($0) }),
PrivacyPolicySetting()
]
settings += [
SettingSection(title: NSAttributedString(string: privacyTitle), children: privacySettings),
SettingSection(title: NSAttributedString(string: NSLocalizedString("Support", comment: "Support section title")), children: [
ShowIntroductionSetting(settings: self),
SendFeedbackSetting(),
OpenSupportPageSetting()
]),
SettingSection(title: NSAttributedString(string: NSLocalizedString("About", comment: "About settings section title")), children: [
VersionSetting(settings: self),
LicenseAndAcknowledgementsSetting(),
YourRightsSetting(),
DisconnectSetting(settings: self),
ExportBrowserDataSetting(settings: self),
DeleteExportedDataSetting(settings: self),
])
]
navigationItem.title = NSLocalizedString("Settings", comment: "Settings")
navigationItem.leftBarButtonItem = UIBarButtonItem(
title: NSLocalizedString("Done", comment: "Done button on left side of the Settings view controller title bar"),
style: UIBarButtonItemStyle.Done,
target: navigationController, action: "SELdone")
tableView.registerClass(SettingsTableViewCell.self, forCellReuseIdentifier: Identifier)
tableView.registerClass(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
tableView.tableFooterView = SettingsTableFooterView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 128))
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELsyncDidChangeState", name: ProfileDidStartSyncingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELsyncDidChangeState", name: ProfileDidFinishSyncingNotification, object: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
SELrefresh()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: ProfileDidStartSyncingNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: ProfileDidFinishSyncingNotification, object: nil)
}
@objc private func SELsyncDidChangeState() {
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
@objc private func SELrefresh() {
// Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app.
if let account = self.profile.getAccount() {
account.advance().upon { _ in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.tableView.reloadData()
}
}
} else {
self.tableView.reloadData()
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
var cell: UITableViewCell!
if let _ = setting.status {
// Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell.
// I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account.
// Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it.
cell = SettingsTableViewCell(style: setting.style, reuseIdentifier: nil)
} else {
cell = tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath)
}
setting.onConfigureCell(cell)
return cell
}
return tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return settings.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = settings[section]
return section.count
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView
let sectionSetting = settings[section]
if let sectionTitle = sectionSetting.title?.string {
headerView.titleLabel.text = sectionTitle
}
// Hide the top border for the top section to avoid having a double line at the top
if section == 0 {
headerView.showTopBorder = false
} else {
headerView.showTopBorder = true
}
return headerView
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// empty headers should be 13px high, but headers with text should be 44
var height: CGFloat = 13
let section = settings[section]
if let sectionTitle = section.title {
if sectionTitle.length > 0 {
height = 44
}
}
return height
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
setting.onClick(navigationController)
}
return nil
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//make account/sign-in and close private tabs rows taller, as per design specs
if indexPath.section == 0 && indexPath.row == 0 {
return 64
}
if #available(iOS 9, *) {
if indexPath.section == 2 && indexPath.row == 2 {
return 64
}
}
return 44
}
}
class SettingsTableFooterView: UIView {
var logo: UIImageView = {
var image = UIImageView(image: UIImage(named: "settingsFlatfox"))
image.contentMode = UIViewContentMode.Center
return image
}()
private lazy var topBorder: CALayer = {
let topBorder = CALayer()
topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
return topBorder
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIConstants.TableViewHeaderBackgroundColor
layer.addSublayer(topBorder)
addSubview(logo)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
topBorder.frame = CGRectMake(0.0, 0.0, frame.size.width, 0.5)
logo.center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
}
}
class SettingsTableSectionHeaderFooterView: UITableViewHeaderFooterView {
var showTopBorder: Bool = true {
didSet {
topBorder.hidden = !showTopBorder
}
}
var showBottomBorder: Bool = true {
didSet {
bottomBorder.hidden = !showBottomBorder
}
}
var titleLabel: UILabel = {
var headerLabel = UILabel()
var frame = headerLabel.frame
frame.origin.x = 15
frame.origin.y = 25
headerLabel.frame = frame
headerLabel.textColor = UIConstants.TableViewHeaderTextColor
headerLabel.font = UIFont.systemFontOfSize(12.0, weight: UIFontWeightRegular)
return headerLabel
}()
private lazy var topBorder: CALayer = {
let topBorder = CALayer()
topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
return topBorder
}()
private lazy var bottomBorder: CALayer = {
let bottomBorder = CALayer()
bottomBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
return bottomBorder
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
addSubview(titleLabel)
clipsToBounds = true
layer.addSublayer(topBorder)
layer.addSublayer(bottomBorder)
}
override func prepareForReuse() {
super.prepareForReuse()
showTopBorder = true
showBottomBorder = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
bottomBorder.frame = CGRectMake(0.0, frame.size.height - 0.5, frame.size.width, 0.5)
topBorder.frame = CGRectMake(0.0, 0.0, frame.size.width, 0.5)
titleLabel.sizeToFit()
}
}
| mpl-2.0 | 7d999d68f58cc9c234efc3b3214e13a3 | 41.666667 | 303 | 0.686163 | 5.757666 | false | false | false | false |
odemolliens/blockchain-ios-sdk | SDK_SWIFT/ODBlockChainWallet/ODBlockChainWallet/Services/User/ODBCWalletService.swift | 1 | 23369 | //
//Copyright 2014 Olivier Demolliens - @odemolliens
//
//Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
//
//file except in compliance with the License. You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software distributed under
//
//the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
//
//ANY KIND, either express or implied. See the License for the specific language governing
//
//permissions and limitations under the License.
//
//
import Foundation
class ODBCWalletService
{
/*
* Encode all char
*/
class func encode(toEncode : NSString) -> NSString {
return CFURLCreateStringByAddingPercentEscapes(
nil,
toEncode,
nil,
"!*'();:@&=+$,/?%#[]",
CFStringBuiltInEncodings.UTF8.toRaw()
)
}
/*
Create Wallet Service
-> Email & Name : parameters are optionnal
Return an ODWallet object with identifier if successfull
Knowed Errors
case Unknow
case PasswordLength
case ApiKey
case Email
case AlphaNumericOnly
*/
class func createWallet(name : NSString, apiKey : NSString, password : NSString, email : NSString, success :(ODWallet) -> Void = {response in /* ... */},failure: (ODBlockChainError) -> Void = {error in /* ... */}) -> Void
{
var url : NSURL;
var request : NSMutableURLRequest;
var postKeys : NSMutableString = NSMutableString();
var firstCharKeys : NSString = "?";
//Parameters
postKeys.appendFormat("%@api_code=%@", firstCharKeys, apiKey);
firstCharKeys = "&";
postKeys.appendFormat("%@password=%@", firstCharKeys, encode(password));
//Optionnal keys
if(email.length>0){
postKeys.appendFormat("%@email=%@", firstCharKeys, email);
}
if(name.length>0){
postKeys.appendFormat("%@label=%@", firstCharKeys ,name);
}
url = NSURL.URLWithString(NSString(format : "%@%@",kBCUrlCreateWallet,postKeys.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!));
request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval:NSTimeInterval(kBCTimeout));
ODBlockChainService.manageRequest(request,
success:{(object : AnyObject) -> Void in
if(object.isKindOfClass(NSDictionary)){
var dic : NSDictionary = object as NSDictionary;
success(ODWallet.instantiateWithDictionnary(dic));
}else{
failure(ODBlockChainError.parseError(NSDictionary.description(),result:object.description));
}
},failure:{(error : ODBlockChainError) -> Void in
failure(error);
});
}
/*
//TODO : untested
Making Outgoing Payments
Send bitcoin from your wallet to another bitcoin address. All transactions include a 0.0001 BTC miners fee.
-> mainPassword : Your Main My wallet password
-> secondPassword : Your second My Wallet password if double encryption is enabled (Optional).
-> to : Recipient Bitcoin Address.
-> amount : Amount to send in satoshi.
-> from : Send from a specific Bitcoin Address (Optional)
shared "true" or "false" indicating whether the transaction should be sent through a shared wallet. Fees apply. (Optional)
-> fee : Transaction fee value in satoshi (Must be greater than default fee) (Optional)
-> note : A public note to include with the transaction (Optional)
Knowed Errors
case Unknow
*/
class func makePayment(walletIdentifier : NSString, apiKey : NSString, mainPassword : NSString, secondPassword : NSString, amount : NSNumber, to : NSString,from : NSString,shared : NSNumber,fee : NSNumber,note : NSString, success :(ODPaymentResults) -> Void = {response in /* ... */},failure: (ODBlockChainError) -> Void = {error in /* ... */}) -> Void
{
var url : NSURL;
var request : NSMutableURLRequest;
var postKeys : NSMutableString = NSMutableString();
var firstCharKeys : NSString = "?";
//Parameters
postKeys.appendFormat("%@/payment", walletIdentifier);
postKeys.appendFormat("%@password=%@", firstCharKeys, encode(mainPassword));
firstCharKeys = "&";
postKeys.appendFormat("%@api_code=%@", firstCharKeys ,apiKey);
postKeys.appendFormat("%@second_password=%@", firstCharKeys, encode(secondPassword));
postKeys.appendFormat("%@amount=%f", firstCharKeys, (amount.floatValue*kBCWalletSatoshi.floatValue));
postKeys.appendFormat("%@to=%@", firstCharKeys, to);
if(from.length>0){
postKeys.appendFormat("%@from=%@", firstCharKeys ,from);
}
if(!(shared.floatValue==(-1.0))){
postKeys.appendFormat("%@shared=%f", firstCharKeys ,shared);
}
if(fee.floatValue>0){
postKeys.appendFormat("%@fee=%f", firstCharKeys ,(fee.floatValue*kBCWalletSatoshi.floatValue));
}
if(note.length>0){
postKeys.appendFormat("%@note=%@", firstCharKeys ,note);
}
url = NSURL.URLWithString(NSString(format : "%@%@",kBCUrlWalletMerchant,postKeys.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!));
request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval:NSTimeInterval(kBCTimeout));
ODBlockChainService.manageRequest(request,
success:{(object : AnyObject) -> Void in
if(object.isKindOfClass(NSDictionary)){
var dic : NSDictionary = object as NSDictionary;
success(ODPaymentResults.instantiateWithDictionnary(dic));
}else{
failure(ODBlockChainError.parseError(NSDictionary.description(),result:object.description));
}
},failure:{(error : ODBlockChainError) -> Void in
failure(error);
});
}
/*
//TODO : untested
Send Many Transactions
Send a transaction to multiple recipients in the same transaction.. All transactions include a 0.0001 BTC miners fee.
-> walletIdentifier : Your Wallet identifier
-> mainPassword : Your Main My wallet password
-> secondPassword : Your second My Wallet password if double encryption is enabled (Optional).
-> from : Send from a specific Bitcoin Address (Optional)
-> to : Send an NSDictionnary like this
{
"1JzSZFs2DQke2B3S4pBxaNaMzzVZaG4Cqh": 100000000,
"12Cf6nCcRtKERh9cQm3Z29c9MWvQuFSxvT": 1500000000,
"1dice6YgEVBf88erBFra9BHf6ZMoyvG88": 200000000
}
shared "true" or "false" indicating whether the transaction should be sent through a shared wallet. Fees apply. (Optional)
-> fee : Transaction fee value in satoshi (Must be greater than default fee) (Optional)
-> note : A public note to include with the transaction (Optional)
Knowed Errors
case Unknow
*/
class func makeManyPayments(walletIdentifier : NSString,apiKey : NSString, mainPassword : NSString, secondPassword : NSString, to : NSDictionary,from : NSString,shared : NSNumber,fee : NSNumber,note : NSString, success :(ODPaymentResults) -> Void = {response in /* ... */},failure: (ODBlockChainError) -> Void = {error in /* ... */}) -> Void
{
var url : NSURL;
var request : NSMutableURLRequest;
var postKeys : NSMutableString = NSMutableString();
var firstCharKeys : NSString = "?";
//Parameters
postKeys.appendFormat("%@/payment", walletIdentifier);
postKeys.appendFormat("%@password=%@", firstCharKeys, encode(mainPassword));
firstCharKeys = "&";
postKeys.appendFormat("%@api_code=%@", firstCharKeys ,apiKey);
postKeys.appendFormat("%@second_password=%@", firstCharKeys, encode(secondPassword));
var error : NSError?;
var data : NSData;
data = NSJSONSerialization.dataWithJSONObject(to, options: NSJSONWritingOptions.PrettyPrinted, error: &error)!;
// TODO : can be optimized
if((error) != nil){
failure(ODBlockChainError.parseError("NSDictionnary", result: to.description));
}else{
// TODO : can be optimized
postKeys.appendFormat("%@recipients=%@", firstCharKeys, NSString(data: data,encoding: NSUTF8StringEncoding));
if(from.length>0){
postKeys.appendFormat("%@from=%@", firstCharKeys ,from);
}
if(!(shared.floatValue==(-1.0))){
postKeys.appendFormat("%@shared=%f", firstCharKeys ,shared);
}
if(fee.floatValue>0){
postKeys.appendFormat("%@fee=%f", firstCharKeys ,(fee.floatValue*kBCWalletSatoshi.floatValue));
}
if(note.length>0){
postKeys.appendFormat("%@note=%@", firstCharKeys ,note);
}
url = NSURL.URLWithString(NSString(format : "%@%@",kBCUrlWalletMerchant,postKeys.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!));
request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval:NSTimeInterval(kBCTimeout));
ODBlockChainService.manageRequest(request,
success:{(object : AnyObject) -> Void in
if(object.isKindOfClass(NSDictionary)){
var dic : NSDictionary = object as NSDictionary;
success(ODPaymentResults.instantiateWithDictionnary(dic));
}else{
failure(ODBlockChainError.parseError(NSDictionary.description(),result:object.description));
}
},failure:{(error : ODBlockChainError) -> Void in
failure(error);
});
}
}
/*
Fetching the wallet balance
Fetch the balance of a wallet. This should be used as an estimate only and will include unconfirmed transactions and possibly double spends.
-> walletIdentifier : Your Wallet identifier
-> mainPassword : Your Main My wallet password
Knowed Errors
case Unknow
*/
class func fetchingWalletBalance(walletIdentifier : NSString,apiKey : NSString, mainPassword : NSString, success :(ODBalance) -> Void = {response in /* ... */},failure: (ODBlockChainError) -> Void = {error in /* ... */}) -> Void
{
var url : NSURL;
var request : NSMutableURLRequest;
var postKeys : NSMutableString = NSMutableString();
var firstCharKeys : NSString = "?";
//Parameters
postKeys.appendFormat("%@/balance", walletIdentifier);
postKeys.appendFormat("%@api_code=%@", firstCharKeys ,apiKey);
firstCharKeys = "&";
postKeys.appendFormat("%@password=%@", firstCharKeys, encode(mainPassword));
url = NSURL.URLWithString(NSString(format : "%@%@",kBCUrlWalletMerchant,postKeys.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!));
request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval:NSTimeInterval(kBCTimeout));
ODBlockChainService.manageRequest(request,
success:{(object : AnyObject) -> Void in
if(object.isKindOfClass(NSDictionary)){
var dic : NSDictionary = object as NSDictionary;
success(ODBalance.instantiateWithDictionnary(dic));
}else{
failure(ODBlockChainError.parseError(NSDictionary.description(),result:object.description));
}
},failure:{(error : ODBlockChainError) -> Void in
failure(error);
});
}
/*
Listing Addresses
List all active addresses in a wallet. Also includes a 0 confirmation balance which should be used as an estimate only and will include unconfirmed transactions and possibly double spends.
-> walletIdentifier : Your Wallet identifier
-> mainPassword : Your Main My wallet password
-> confirmations : The minimum number of confirmations transactions must have before being included in balance of addresses (Optional)
Knowed Errors
case Invalid
case DecryptingWallet
case Unknow
case ApiKey
*/
class func listingAddresses(walletIdentifier : NSString,apiKey : NSString,mainPassword : NSString,confirmations : NSNumber, success :(NSArray) -> Void = {response in /* ... */},failure: (ODBlockChainError) -> Void = {error in /* ... */}) -> Void
{
var url : NSURL;
var request : NSMutableURLRequest;
var postKeys : NSMutableString = NSMutableString();
var firstCharKeys : NSString = "?";
//Parameters
postKeys.appendFormat("%@/list", walletIdentifier);
postKeys.appendFormat("%@password=%@", firstCharKeys, encode(mainPassword));
firstCharKeys = "&";
postKeys.appendFormat("%@api_code=%@", firstCharKeys ,apiKey);
if(!(confirmations.floatValue==(-1.0))){
postKeys.appendFormat("%@confirmations=%i", firstCharKeys ,confirmations.integerValue);
}
url = NSURL.URLWithString(NSString(format : "%@%@",kBCUrlWalletMerchant,postKeys.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!));
request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval:NSTimeInterval(kBCTimeout));
ODBlockChainService.manageRequest(request,
success:{(object : AnyObject) -> Void in
if(object.isKindOfClass(NSDictionary)){
var dic : NSDictionary = object as NSDictionary;
//if(dic.valueForKey("addresses").isKindOfClass(NSArray)){
var resultArray : NSArray = dic.valueForKey("addresses") as NSArray;
var mArray : NSMutableArray = NSMutableArray();
for(var i = 0; i < resultArray.count;i++){
var dicAddress : NSDictionary = resultArray.objectAtIndex(i) as NSDictionary;
mArray.addObject(ODBalanceDetails.instantiateWithDictionnary(dicAddress));
}
success(mArray);
/*}else{
failure(ODBlockChainError.parseError(NSArray.description(),result:dic.description));
}*/
}else{
failure(ODBlockChainError.parseError(NSDictionary.description(),result:object.description));
}
},failure:{(error : ODBlockChainError) -> Void in
failure(error);
});
}
/*
//TODO : untested
Getting the balance of an address
Retrieve the balance of a bitcoin address. Querying the balance of an address by label is depreciated.
-> walletIdentifier : Your Wallet identifier
-> mainPassword : Your Main My wallet password
-> confirmations : The minimum number of confirmations transactions must have before being included in balance of addresses (Optional)
-> address : The bitcoin address to lookup
Knowed Errors
case Invalid
case Unknow
*/
//#define kBCWalletMyAdress
class func myAddress(walletIdentifier : NSString,apiKey : NSString,mainPassword : NSString,address : NSString,confirmations : NSNumber, success :(ODBalanceDetails) -> Void = {response in /* ... */},failure: (ODBlockChainError) -> Void = {error in /* ... */}) -> Void
{
var url : NSURL;
var request : NSMutableURLRequest;
var postKeys : NSMutableString = NSMutableString();
var firstCharKeys : NSString = "?";
//Parameters
postKeys.appendFormat("%@/address_balance", walletIdentifier);
postKeys.appendFormat("%@password=%@", firstCharKeys, encode(mainPassword));
firstCharKeys = "&";
postKeys.appendFormat("%@api_code=%@", firstCharKeys ,apiKey);
postKeys.appendFormat("%@address=%@", firstCharKeys, address);
if(!(confirmations.floatValue==(-1.0))){
postKeys.appendFormat("%@confirmations=%i", firstCharKeys ,confirmations.integerValue);
}
url = NSURL.URLWithString(NSString(format : "%@%@",kBCUrlWalletMerchant,postKeys.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!));
request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval:NSTimeInterval(kBCTimeout));
ODBlockChainService.manageRequest(request,
success:{(object : AnyObject) -> Void in
if(object.isKindOfClass(NSDictionary)){
var dic : NSDictionary = object as NSDictionary;
success(ODBalanceDetails.instantiateWithDictionnary(dic));
}else{
failure(ODBlockChainError.parseError(NSDictionary.description(),result:object.description));
}
},failure:{(error : ODBlockChainError) -> Void in
failure(error);
});
}
/*
Generating a new address
-> walletIdentifier : Your Wallet identifier
-> mainPassword Your Main My wallet password
-> secondPassword : Your second My Wallet password if double encryption is enabled (Optional).
-> label : An optional label to attach to this address. It is recommended this is a human readable string e.g. "Order No : 1234". You May use this as a reference to check balance of an order (documented later)
Knowed Errors
case Unknow
*/
class func createAddress(walletIdentifier : NSString,apiKey : NSString,mainPassword : NSString,secondPassword : NSString,label : NSString, success :(ODBalanceDetails) -> Void = {response in /* ... */},failure: (ODBlockChainError) -> Void = {error in /* ... */}) -> Void
{
var url : NSURL;
var request : NSMutableURLRequest;
var postKeys : NSMutableString = NSMutableString();
var firstCharKeys : NSString = "?";
//Parameters
postKeys.appendFormat("%@/new_address", walletIdentifier);
postKeys.appendFormat("%@password=%@", firstCharKeys, encode(mainPassword));
firstCharKeys = "&";
postKeys.appendFormat("%@api_code=%@", firstCharKeys ,apiKey);
postKeys.appendFormat("%@second_password=%@", firstCharKeys, encode(secondPassword));
postKeys.appendFormat("%@label=%@", firstCharKeys, label);
url = NSURL.URLWithString(NSString(format : "%@%@",kBCUrlWalletMerchant,postKeys.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!));
request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval:NSTimeInterval(kBCTimeout));
ODBlockChainService.manageRequest(request,
success:{(object : AnyObject) -> Void in
if(object.isKindOfClass(NSDictionary)){
var dic : NSDictionary = object as NSDictionary;
success(ODBalanceDetails.instantiateWithDictionnary(dic));
}else{
failure(ODBlockChainError.parseError(NSDictionary.description(),result:object.description));
}
},failure:{(error : ODBlockChainError) -> Void in
failure(error);
});
}
/*
Archiving an address
To improve wallet performance addresses which have not been used recently should be moved to an archived state. They will still be held in the wallet but will no longer be included in the "list" or "list-transactions" calls.
For example if an invoice is generated for a user once that invoice is paid the address should be archived.
Or if a unique bitcoin address is generated for each user, users who have not logged in recently (~30 days) their addresses should be archived.
https://blockchain.info/merchant/$guid/archive_address?password=$main_password&second_password=$second_password&address=$address
$main_password Your Main My wallet password
$second_password Your second My Wallet password if double encryption is enabled.
$address The bitcoin address to archive
Response:
{"archived" : "18fyqiZzndTxdVo7g9ouRogB4uFj86JJiy"}
*/
/*
Unarchive an address
Unarchive an address. Will also restore consolidated addresses (see below).
https://blockchain.info/merchant/$guid/unarchive_address?password=$main_password&second_password=$second_password&address=$address
$main_password Your Main My wallet password
$second_password Your second My Wallet password if double encryption is enabled.
$address The bitcoin address to unarchive
Response:
{"active" : "18fyqiZzndTxdVo7g9ouRogB4uFj86JJiy"}
*/
/*
Consolidating Addresses
Queries to wallets with over 10 thousand addresses will become sluggish especially in the web interface. The auto_consolidate command will remove some inactive archived addresses from the wallet and insert them as forwarding addresses (see receive payments API). You will still receive callback notifications for these addresses however they will no longer be part of the main wallet and will be stored server side.
If generating a lot of addresses it is a recommended to call this method at least every 48 hours. A good value for days is 60 i.e. addresses which have not received transactions in the last 60 days will be consolidated.
https://blockchain.info/merchant/$guid/auto_consolidate?password=$main_password&second_password=$second_password&days=$days
$main_password Your Main My wallet password
$second_password Your second My Wallet password if double encryption is enabled.
$days Addresses which have not received any transactions in at least this many days will be consolidated.
Response:
{ "consolidated" : ["18fyqiZzndTxdVo7g9ouRogB4uFj86JJiy"]}
*/
} | apache-2.0 | 885e6e660cf0f1401a8e8c345e0a2776 | 43.177694 | 419 | 0.628568 | 5.741769 | false | false | false | false |
rymcol/Server-Side-Swift-Benchmarks-Summer-2017 | KituraPress/Sources/main.swift | 1 | 2100 | import Kitura
import SwiftyJSON
#if os(Linux)
import SwiftGlibc
public func arc4random_uniform(_ max: UInt32) -> Int32 {
return (SwiftGlibc.rand() % Int32(max-1)) + 1
}
#endif
// All Web apps need a router to define routes
let router = Router()
router.get("/") { _, response, next in
let header = CommonHandler().getHeader()
let footer = CommonHandler().getFooter()
let body = IndexHandler().loadPageContent()
let homePage = header + body + footer
try response.send(homePage).end()
}
router.get("/blog") { _, response, next in
response.headers["Content-Type"] = "text/html; charset=utf-8"
let header = CommonHandler().getHeader()
let footer = CommonHandler().getFooter()
let body = BlogPageHandler().loadPageContent()
let blogPage = header + body + footer
try response.send(blogPage).end()
}
router.get("/json") { _, response, next in
response.headers["Content-Type"] = "application/json; charset=utf-8"
let json = JSON(JSONCreator().generateJSON())
try response.send(json: json).end()
}
router.get(middleware: StaticFileServer(path: "./public"))
// Handles any errors that get set
router.error { request, response, next in
response.headers["Content-Type"] = "text/plain; charset=utf-8"
let errorDescription: String
if let error = response.error {
errorDescription = "\(error)"
} else {
errorDescription = "Unknown error"
}
try response.send("Caught the error: \(errorDescription)").end()
}
// A custom Not found handler
router.all { request, response, next in
if response.statusCode == .unknown {
// Remove this wrapping if statement, if you want to handle requests to / as well
if request.originalURL != "/" && request.originalURL != "" {
try response.status(.notFound).send("404! - This page does not exits!").end()
}
}
next()
}
// Add HTTP Server to listen on port 8090
Kitura.addHTTPServer(onPort: 8090, with: router)
// start the framework - the servers added until now will start listening
Kitura.run()
| apache-2.0 | f0a00af479c62577c64502213e0220a5 | 30.343284 | 89 | 0.660476 | 3.954802 | false | false | false | false |
a8b/CoreDataStackFromScratch | CoreDataStack/CoreDataStack/CoreDataManager.swift | 1 | 2460 | //
// CoreDataManager.swift
// CoreDataStack
//
// Created by Yakiv Kovalsky on 1/4/17.
// Copyright © 2017 Yakiv Kovalsky. All rights reserved.
//
import Foundation
import CoreData
public class CoreDataManager {
private let modelName: String
init(modelName: String) {
self.modelName = modelName
}
public private(set) lazy var managedObjectContext: NSManagedObjectContext = {
// Initialize Managed Object Context
let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
// Configure Managed Object Context
managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator
return managedObjectContext
}()
private lazy var managedObjectModel: NSManagedObjectModel? = {
// Fetch Model URL
guard let modelURL = Bundle.main.url(forResource: self.modelName, withExtension: "momd") else {
return nil
}
// Initialize Managed Object Model
let managedObjectModel = NSManagedObjectModel(contentsOf: modelURL)
return managedObjectModel
}()
private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
guard let managedObjectModel = self.managedObjectModel else {
return nil
}
// Helper
let persistentStoreURL = self.persistentStoreURL
// Initialize Persistent Store Coordinator
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
do {
let options = [ NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true ]
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: persistentStoreURL, options: options)
} catch {
let addPersistentStoreError = error as NSError
print("Unable to Add Persistent Store")
print("\(addPersistentStoreError.localizedDescription)")
}
return persistentStoreCoordinator
}()
private var persistentStoreURL: URL {
// Helpers
let storeName = "\(modelName).sqlite"
let fileManager = FileManager.default
let documentsDirectoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
return documentsDirectoryURL.appendingPathComponent(storeName)
}
}
| mit | 79355288db2f0e51eb552e9595e894b8 | 31.786667 | 154 | 0.697438 | 6.454068 | false | false | false | false |
6ag/AppScreenshots | AppScreenshots/Classes/Module/Home/Model/JFPasterGroup.swift | 1 | 2261 | //
// JFPasterGroup.swift
// AppScreenshots
//
// Created by zhoujianfeng on 2017/2/12.
// Copyright © 2017年 zhoujianfeng. All rights reserved.
//
import UIKit
class JFPasterGroup: NSObject {
/// 贴纸组名
var groupName: String
/// 贴纸组icon名
var iconName: String
/// 贴纸组里的贴纸集合
var pasterList: [JFPaster]
/// 初始化贴图组模型
///
/// - Parameters:
/// - groupName: 组名
/// - prefix: 前缀
/// - count: 数量
init(groupName: String, prefix: String, count: Int) {
self.groupName = groupName
self.iconName = "\(prefix)_icon.png"
var pasterList = [JFPaster]()
for index in 1...count {
let paster = JFPaster(iconName: "\(prefix)_compress_\(index).png")
pasterList.append(paster)
}
self.pasterList = pasterList
super.init()
}
/// 获取所有贴纸组
///
/// - Returns: 贴纸组模型集合
class func getPasterGroupList() -> [JFPasterGroup] {
var pasterGroupList = [JFPasterGroup]()
let shenjjm = JFPasterGroup(groupName: "神经猫", prefix: "shenjjm", count: 110)
let HK = JFPasterGroup(groupName: "hello kitty", prefix: "HK", count: 95)
let SC = JFPasterGroup(groupName: "蜡笔小新", prefix: "SC", count: 102)
let DA = JFPasterGroup(groupName: "多啦A梦", prefix: "DA", count: 123)
let Maruko = JFPasterGroup(groupName: "小丸子", prefix: "Maruko", count: 102)
let cheesecat = JFPasterGroup(groupName: "奶酪猫", prefix: "cheesecat", count: 36)
let COCO = JFPasterGroup(groupName: "小女人", prefix: "COCO", count: 77)
let mengmengxiong_christmas = JFPasterGroup(groupName: "萌萌熊", prefix: "mengmengxiong_christmas", count: 32)
pasterGroupList.append(shenjjm)
pasterGroupList.append(HK)
pasterGroupList.append(SC)
pasterGroupList.append(DA)
pasterGroupList.append(Maruko)
pasterGroupList.append(cheesecat)
pasterGroupList.append(COCO)
pasterGroupList.append(mengmengxiong_christmas)
return pasterGroupList
}
}
| mit | 14aab0e080084819843cccfd47b186e6 | 29.342857 | 115 | 0.59887 | 3.759292 | false | false | false | false |
SASAbus/SASAbus-ios | SASAbus/Data/Networking/Model/EcoPoints/Badge.swift | 1 | 1020 | import Foundation
import SwiftyJSON
final class Badge: JSONable, JSONCollection {
let id: String
let title: String
let description: String
let iconUrl: String
let progress: Int
let points: Int
let users: Int
let isNewBadge: Bool
let locked: Bool
required init(parameter: JSON) {
id = parameter["id"].stringValue
title = parameter["title"].stringValue
description = parameter["description"].stringValue
iconUrl = parameter["icon_url"].stringValue
progress = parameter["progress"].intValue
points = parameter["points"].intValue
users = parameter["users"].intValue
isNewBadge = parameter["new"].boolValue
locked = parameter["locked"].boolValue
}
static func collection(parameter: JSON) -> [Badge] {
var items: [Badge] = []
for itemRepresentation in parameter.arrayValue {
items.append(Badge(parameter: itemRepresentation))
}
return items
}
}
| gpl-3.0 | a4b1e9f42e2570da312370e82b9de8ea | 22.181818 | 62 | 0.636275 | 5.049505 | false | false | false | false |
leoru/Brainstorage | Brainstorage-iOS/Vendor/HTMLParser/HTMLNode.swift | 1 | 8934 | /**@file
* @brief Swift-HTML-Parser
* @author _tid_
*/
import Foundation
/**
* HTMLNode
*/
public class HTMLNode {
public enum HTMLNodeType : String {
case HTMLUnkownNode = ""
case HTMLHrefNode = "href"
case HTMLTextNode = "text"
case HTMLCodeNode = "code"
case HTMLSpanNode = "span"
case HTMLPNode = "p"
case HTMLLiNode = "li"
case HTMLUiNode = "ui"
case HTMLImageNode = "image"
case HTMLOlNode = "ol"
case HTMLStrongNode = "strong"
case HTMLPreNode = "pre"
case HTMLBlockQuoteNode = "blockquote"
}
private var doc : htmlDocPtr
private var pointer : xmlNodePtr
private var node : xmlNode?
private var nodeType : HTMLNodeType = HTMLNodeType.HTMLUnkownNode
/**
* 親ノード
*/
private var parent : HTMLNode? {
if let p = self.node?.parent {
return HTMLNode(doc: self.doc, node: p)
}
return nil
}
/**
* 次ノード
*/
private var next : HTMLNode? {
if let n : UnsafeMutablePointer<xmlNode> = node?.next {
if n != nil {
return HTMLNode(doc: doc, node: n)
}
}
return nil
}
/**
* 子ノード
*/
private var child : HTMLNode? {
if let c = node?.children {
if c != nil {
return HTMLNode(doc: doc, node: c)
}
}
return nil
}
/**
* クラス名
*/
public var className : String {
return getAttributeNamed("class")
}
/**
* タグ名
*/
public var tagName : String {
if node != nil {
return ConvXmlCharToString(self.node!.name)
}
return ""
}
/**
* コンテンツ
*/
public var contents : String {
if node != nil {
var n = self.node!.children
if n != nil {
return ConvXmlCharToString(n.memory.content)
}
}
return ""
}
public var rawContents : String {
if node != nil {
return rawContentsOfNode(self.node!, self.pointer)
}
return ""
}
/**
* Initializer
* @param[in] doc xmlDoc
*/
public init(doc: htmlDocPtr = nil) {
self.doc = doc
var node = xmlDocGetRootElement(doc)
self.pointer = node
if node != nil {
self.node = node.memory
}
}
private init(doc: htmlDocPtr, node: UnsafePointer<xmlNode>) {
self.doc = doc
self.node = node.memory
self.pointer = xmlNodePtr(node)
let type = HTMLNodeType(rawValue: tagName)
if let type = HTMLNodeType(rawValue: tagName) {
self.nodeType = type
}
}
/**
* 属性名を取得する
* @param[in] name 属性
* @return 属性名
*/
public func getAttributeNamed(name: String) -> String {
for var attr : xmlAttrPtr = node!.properties; attr != nil; attr = attr.memory.next {
var mem = attr.memory
if name == ConvXmlCharToString(mem.name) {
return ConvXmlCharToString(mem.children.memory.content)
}
}
return ""
}
/**
* タグ名に一致する全ての子ノードを探す
* @param[in] tagName タグ名
* @return 子ノードの配列
*/
public func findChildTags(tagName: String) -> [HTMLNode] {
var nodes : [HTMLNode] = []
return findChildTags(tagName, node: self.child, retAry: &nodes)
}
private func findChildTags(tagName: String, node: HTMLNode?, inout retAry: [HTMLNode] ) -> [HTMLNode] {
if let n = node {
for curNode in n {
if curNode.tagName == tagName {
retAry.append(curNode)
}
findChildTags(tagName, node: curNode.child, retAry: &retAry)
}
}
return retAry
}
/**
* タグ名で子ノードを探す
* @param[in] tagName タグ名
* @return 子ノード。見つからなければnil
*/
public func findChildTag(tagName: String) -> HTMLNode? {
return findChildTag(tagName, node: self)
}
private func findChildTag(tagName: String, node: HTMLNode?) -> HTMLNode? {
if let nd = node {
for curNode in nd {
if tagName == curNode.tagName {
return curNode
}
if let c = curNode.child {
if let n = findChildTag(tagName, node: c) {
return n
}
}
}
}
return nil
}
//------------------------------------------------------
public func findChildTagsAttr(tagName: String, attrName : String, attrValue : String) -> [HTMLNode] {
var nodes : [HTMLNode] = []
return findChildTagsAttr(tagName, attrName : attrName, attrValue : attrValue, node: self.child, retAry: &nodes)
}
private func findChildTagsAttr(tagName: String, attrName : String, attrValue : String, node: HTMLNode?, inout retAry: [HTMLNode] ) -> [HTMLNode] {
if let n = node {
for curNode in n {
if curNode.tagName == tagName && curNode.getAttributeNamed(attrName) == attrValue {
retAry.append(curNode)
}
findChildTagsAttr(tagName, attrName : attrName, attrValue : attrValue, node: curNode.child, retAry: &retAry)
}
}
return retAry
}
public func findChildTagAttr(tagName : String, attrName : String, attrValue : String) -> HTMLNode?
{
return findChildTagAttr(tagName, attrName : attrName, attrValue : attrValue, node: self)
}
private func findChildTagAttr(tagName : String, attrName : String, attrValue : String, node: HTMLNode?) -> HTMLNode?
{
if let nd = node {
for curNode in nd {
if tagName == curNode.tagName && curNode.getAttributeNamed(attrName) == attrValue {
return curNode
}
if let c = curNode.child {
if let n = findChildTagAttr(tagName,attrName: attrName,attrValue: attrValue, node: c) {
return n
}
}
}
}
return nil
}
/**
* Find node by id (id has to be used properly it is a uniq attribute)
* @param[in] id String
* @return HTMLNode
*/
public func findNodeById(id: String) -> HTMLNode? {
return findNodeById(id, node: self)
}
private func findNodeById(id: String, node: HTMLNode?) -> HTMLNode? {
if let nd = node {
for curNode in nd {
if id == curNode.getAttributeNamed("id") {
return curNode
}
if let c = curNode.child {
if let n = findNodeById(id, node: c) {
return n
}
}
}
}
return nil
}
/**
* xpathで子ノードを探す
* @param[in] xpath xpath
* @return 子ノード。見つからなければnil
*/
public func xpath(xpath: String) -> [HTMLNode]? {
let ctxt = xmlXPathNewContext(self.doc)
if ctxt == nil {
return nil
}
let result = xmlXPathEvalExpression(xpath, ctxt)
xmlXPathFreeContext(ctxt)
if result == nil {
return nil
}
let nodeSet = result.memory.nodesetval
if nodeSet == nil || nodeSet.memory.nodeNr == 0 || nodeSet.memory.nodeTab == nil {
return nil
}
var nodes : [HTMLNode] = []
let size = Int(nodeSet.memory.nodeNr)
for var i = 0; i < size; ++i {
let n = nodeSet.memory
let node = nodeSet.memory.nodeTab[i]
let htmlNode = HTMLNode(doc: self.doc, node: node)
nodes.append(htmlNode)
}
return nodes
}
}
extension HTMLNode : SequenceType {
public func generate() -> HTMLNodeGenerator {
return HTMLNodeGenerator(node: self)
}
}
/**
* HTMLNodeGenerator
*/
public class HTMLNodeGenerator : GeneratorType {
private var node : HTMLNode?
public init(node: HTMLNode?) {
self.node = node
}
public func next() -> HTMLNode? {
var temp = node
node = node?.next
return temp
}
} | mit | 95ee6a23b698d5b2cc292978898b3b8f | 26.046584 | 150 | 0.495866 | 4.597677 | false | false | false | false |
vimeo/VimeoUpload | VimeoUpload/Upload/Networking/Old Upload/VimeoSessionManager+OldUpload.swift | 1 | 7652 | //
// VimeoSessionManager+Upload.swift
// VimeoUpload
//
// Created by Alfred Hanssen on 10/21/15.
// Copyright © 2015 Vimeo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import VimeoNetworking
extension VimeoSessionManager
{
public func myVideosDataTask(completionHandler: @escaping VideosCompletionHandler) throws -> Task?
{
let request = try self.jsonRequestSerializer.myVideosRequest() as URLRequest
return self.request(request) { [jsonResponseSerializer] (sessionManagingResult: SessionManagingResult<JSON>) in
// Do model parsing on a background thread
DispatchQueue.global(qos: .default).async {
switch sessionManagingResult.result {
case .failure(let error as NSError):
completionHandler(nil, error)
case .success(let json):
do {
let videos = try jsonResponseSerializer.process(
myVideosResponse: sessionManagingResult.response,
responseObject: json as AnyObject,
error: nil
)
completionHandler(videos, nil)
} catch let error as NSError {
completionHandler(nil, error)
}
}
}
}
}
public func createVideoDownloadTask(url: URL) throws -> Task?
{
let request = try self.jsonRequestSerializer.createVideoRequest(with: url) as URLRequest
return self.download(request) { _ in }
}
func uploadVideoTask(source: URL, destination: String, completionHandler: ErrorBlock?) throws -> Task?
{
let request = try self.jsonRequestSerializer.uploadVideoRequest(with: source, destination: destination) as URLRequest
return self.upload(request, sourceFile: source) { [jsonResponseSerializer] sessionManagingResult in
switch sessionManagingResult.result {
case .failure(let error):
completionHandler?(error as NSError)
case .success(let json):
do {
try jsonResponseSerializer.process(
uploadVideoResponse: sessionManagingResult.response,
responseObject: json as AnyObject,
error: nil
)
completionHandler?(nil)
} catch let error as NSError {
completionHandler?(error)
}
}
}
}
// For use with background sessions, use session delegate methods for destination and completion
func activateVideoDownloadTask(uri activationUri: String) throws -> Task?
{
let request = try self.jsonRequestSerializer.activateVideoRequest(withURI: activationUri) as URLRequest
return self.download(request) { _ in }
}
// For use with background sessions, use session delegate methods for destination and completion
func videoSettingsDownloadTask(videoUri: String, videoSettings: VideoSettings) throws -> Task?
{
let request = try self.jsonRequestSerializer.videoSettingsRequest(with: videoUri, videoSettings: videoSettings) as URLRequest
return self.download(request) { _ in }
}
public func videoSettingsDataTask(videoUri: String, videoSettings: VideoSettings, completionHandler: @escaping VideoCompletionHandler) throws -> Task?
{
let request = try self.jsonRequestSerializer.videoSettingsRequest(with: videoUri, videoSettings: videoSettings) as URLRequest
return self.request(request) { [jsonResponseSerializer] (sessionManagingResult: SessionManagingResult<JSON>) in
// Do model parsing on a background thread
DispatchQueue.global(qos: .default).async {
switch sessionManagingResult.result {
case .failure(let error):
completionHandler(nil, error as NSError)
case .success(let json):
do {
let video = try jsonResponseSerializer.process(
videoSettingsResponse: sessionManagingResult.response,
responseObject: json as AnyObject,
error: nil
)
completionHandler(video, nil)
} catch let error as NSError {
completionHandler(nil, error)
}
}
}
}
}
func deleteVideoDataTask(videoUri: String, completionHandler: @escaping ErrorBlock) throws -> Task?
{
let request = try self.jsonRequestSerializer.deleteVideoRequest(with: videoUri) as URLRequest
return self.request(request) { [jsonResponseSerializer] (sessionManagingResult: SessionManagingResult<JSON>) in
switch sessionManagingResult.result {
case .failure(let error):
completionHandler(error as NSError)
case .success(let json):
do {
try jsonResponseSerializer.process(
deleteVideoResponse: sessionManagingResult.response,
responseObject: json as AnyObject,
error: nil
)
completionHandler(nil)
} catch let error as NSError {
completionHandler(error)
}
}
}
}
func videoDataTask(videoUri: String, completionHandler: @escaping VideoCompletionHandler) throws -> Task?
{
let request = try self.jsonRequestSerializer.videoRequest(with: videoUri) as URLRequest
return self.request(request) { [jsonResponseSerializer] (sessionManagingResult: SessionManagingResult<JSON>) in
switch sessionManagingResult.result {
case .failure(let error as NSError):
completionHandler(nil, error)
case .success(let json):
do {
let video = try jsonResponseSerializer.process(
videoResponse: sessionManagingResult.response,
responseObject: json as AnyObject,
error: nil
)
completionHandler(video, nil)
} catch let error as NSError {
completionHandler(nil, error)
}
}
}
}
}
| mit | 5ee64e9afb9387413d95fb5d7cf3665d | 44.541667 | 154 | 0.608679 | 5.836003 | false | false | false | false |
anlaital/Swan | Swan/Swan/DateExtensions.swift | 1 | 5031 | //
// DateExtensions.swift
// Swan
//
// Created by Antti Laitala on 22/05/15.
//
//
import Foundation
// MARK: Helpers
public extension Date {
var nanosecond: Int {
return Calendar.mainThreadSharedCalendar().component(.nanosecond, from: self)
}
var second: Int {
return Calendar.mainThreadSharedCalendar().component(.second, from: self)
}
var minute: Int {
return Calendar.mainThreadSharedCalendar().component(.minute, from: self)
}
var hour: Int {
return Calendar.mainThreadSharedCalendar().component(.hour, from: self)
}
var day: Int {
return Calendar.mainThreadSharedCalendar().component(.day, from: self)
}
var month: Int {
return Calendar.mainThreadSharedCalendar().component(.month, from: self)
}
var year: Int {
return Calendar.mainThreadSharedCalendar().component(.year, from: self)
}
/// Returns a date set to the start of the day (00:00:00) of this date.
var startOfDay: Date {
let calendar = Calendar.mainThreadSharedCalendar()
let comps = calendar.dateComponents([.year, .month, .day], from: self)
return calendar.date(from: comps)!
}
/// Returns a date set to the end of the day (23:59:59) of this date.
var endOfDay: Date {
let calendar = Calendar.mainThreadSharedCalendar()
var comps = calendar.dateComponents([.year, .month, .day], from: self)
comps.hour = 23
comps.minute = 59
comps.second = 59
return calendar.date(from: comps)!
}
/// Returns a date set to the start of the month (1st day, 00:00:00) of this date.
var startOfMonth: Date {
let calendar = Calendar.mainThreadSharedCalendar()
let comps = calendar.dateComponents([.year, .month], from: self)
return calendar.date(from: comps)!
}
/// Returns a date set to the end of the month (last day, 23:59:59) of this date.
var endOfMonth: Date {
let calendar = Calendar.mainThreadSharedCalendar()
let dayRange = calendar.range(of: .day, in: .month, for: self)!
var comps = calendar.dateComponents([.year, .month], from: self)
comps.day = dayRange.upperBound - dayRange.lowerBound
comps.hour = 23
comps.minute = 59
comps.second = 59
return calendar.date(from: comps)!
}
/// Returns the noon (12:00:00) of this date.
var noon: Date {
let calendar = Calendar.mainThreadSharedCalendar()
var comps = calendar.dateComponents([.year, .month, .day], from: self)
comps.hour = 12
return calendar.date(from: comps)!
}
/// Returns the zero-indexed weekday component of this date starting on monday in range [0, 6].
var zeroIndexedWeekdayStartingOnMonday: Int {
let weekday = Calendar.mainThreadSharedCalendar().component(.weekday, from: self)
return weekday >= 2 ? weekday - 2 : 6
}
/// Returns the number of calendar days between this date and `date`.
func calendarDaysToDate(_ date: Date) -> Int {
let calendar = Calendar.mainThreadSharedCalendar()
var fromDate = Date()
var toDate = Date()
var interval: TimeInterval = 0
_ = calendar.dateInterval(of: .day, start: &fromDate, interval: &interval, for: self)
_ = calendar.dateInterval(of: .day, start: &toDate, interval: &interval, for: date)
let comps = calendar.dateComponents([.day], from: fromDate, to: toDate)
return comps.day!
}
/// Returns the number of calendar weeks between this date and `date`.
func calendarWeeksToDate(_ date: Date) -> Int {
let calendar = Calendar.mainThreadSharedCalendar()
var fromDate = Date()
var toDate = Date()
var interval: TimeInterval = 0
_ = calendar.dateInterval(of: .day, start: &fromDate, interval: &interval, for: self)
_ = calendar.dateInterval(of: .day, start: &toDate, interval: &interval, for: date)
let comps = calendar.dateComponents([.weekOfYear], from: fromDate, to: toDate)
return comps.weekOfYear!
}
}
// MARK: Date Arithmetic
public struct TimeUnit {
let unit: Calendar.Component
let duration: Int
init(_ unit: Calendar.Component, duration: Int) {
self.unit = unit
self.duration = duration
}
}
public func +(lhs: Date, rhs: TimeUnit) -> Date {
return Calendar.mainThreadSharedCalendar().date(byAdding: rhs.unit, value: rhs.duration, to: lhs)!
}
public func +=(lhs: inout Date, rhs: TimeUnit) {
lhs = Calendar.mainThreadSharedCalendar().date(byAdding: rhs.unit, value: rhs.duration, to: lhs)!
}
public func -(lhs: Date, rhs: TimeUnit) -> Date {
return Calendar.mainThreadSharedCalendar().date(byAdding: rhs.unit, value: -rhs.duration, to: lhs)!
}
public func -=(lhs: inout Date, rhs: TimeUnit) {
lhs = Calendar.mainThreadSharedCalendar().date(byAdding: rhs.unit, value: -rhs.duration, to: lhs)!
}
| mit | 164f618504fcbda60b1f4dfa63d45e7d | 33.22449 | 103 | 0.639237 | 4.263559 | false | false | false | false |
stevebrambilla/Runes | Tests/Tests/ArraySpec.swift | 3 | 2959 | import SwiftCheck
import XCTest
import Runes
class ArraySpec: XCTestCase {
func testFunctor() {
// fmap id = id
property("identity law") <- forAll { (xs: [Int]) in
let lhs = id <^> xs
let rhs = xs
return lhs == rhs
}
// fmap (f . g) = (fmap f) . (fmap g)
property("function composition law") <- forAll { (a: ArrayOf<Int>, fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>) in
let xs = a.getArray
let f = fa.getArrow
let g = fb.getArrow
let lhs = compose(f, g) <^> xs
let rhs = compose(curry(<^>)(f), curry(<^>)(g))(xs)
return lhs == rhs
}
}
func testApplicative() {
// pure id <*> x = x
property("identity law") <- forAll { (xs: [Int]) in
let lhs = pure(id) <*> xs
let rhs = xs
return lhs == rhs
}
// pure f <*> pure x = pure (f x)
property("homomorphism law") <- forAll { (x: Int, fa: ArrowOf<Int, Int>) in
let f = fa.getArrow
let lhs: [Int] = pure(f) <*> pure(x)
let rhs: [Int] = pure(f(x))
return rhs == lhs
}
// f <*> pure x = pure ($ x) <*> f
property("interchange law") <- forAll { (x: Int, fa: ArrayOf<ArrowOf<Int, Int>>) in
let f = fa.getArray.map { $0.getArrow }
let lhs = f <*> pure(x)
let rhs = pure({ $0(x) }) <*> f
return lhs == rhs
}
// f <*> (g <*> x) = pure (.) <*> f <*> g <*> x
property("composition law") <- forAll { (a: ArrayOf<Int>, fa: ArrayOf<ArrowOf<Int, Int>>, fb: ArrayOf<ArrowOf<Int, Int>>) in
let x = a.getArray
let f = fa.getArray.map { $0.getArrow }
let g = fb.getArray.map { $0.getArrow }
let lhs = f <*> (g <*> x)
let rhs = pure(curry(compose)) <*> f <*> g <*> x
return lhs == rhs
}
}
func testMonad() {
// return x >>= f = f x
property("left identity law") <- forAll { (x: Int, fa: ArrowOf<Int, Int>) in
let f: Int -> [Int] = compose(pure, fa.getArrow)
let lhs = pure(x) >>- f
let rhs = f(x)
return lhs == rhs
}
// m >>= return = m
property("right identity law") <- forAll { (x: [Int]) in
let lhs = x >>- pure
let rhs = x
return lhs == rhs
}
// (m >>= f) >>= g = m >>= (\x -> f x >>= g)
property("associativity law") <- forAll { (a: ArrayOf<Int>, fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>) in
let m = a.getArray
let f: Int -> [Int] = compose(pure, fa.getArrow)
let g: Int -> [Int] = compose(pure, fb.getArrow)
let lhs = (m >>- f) >>- g
let rhs = m >>- { x in f(x) >>- g }
return lhs == rhs
}
}
}
| mit | c9480c63dd83447cc61987f72eb2efad | 28.29703 | 132 | 0.438324 | 3.774235 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/UI/ReactiveCocoa/CocoaTarget.swift | 1 | 1457 | import Foundation
import PaversFRP
/// A target that accepts action messages.
internal final class CocoaTarget<Value>: NSObject {
private enum State {
case idle
case sending(queue: [Value])
}
private let observer: Signal<Value, Never>.Observer
private let transform: (Any?) -> Value
private var state: State
internal init(_ observer: Signal<Value, Never>.Observer, transform: @escaping (Any?) -> Value) {
self.observer = observer
self.transform = transform
self.state = .idle
}
/// Broadcast the action message to all observers.
///
/// Reentrancy is supported, and the action message would be deferred until the
/// delivery of the current message has completed.
///
/// - note: It should only be invoked on the main queue.
///
/// - parameters:
/// - sender: The object which sends the action message.
@objc internal func invoke(_ sender: Any?) {
switch state {
case .idle:
state = .sending(queue: [])
observer.send(value: transform(sender))
while case let .sending(values) = state {
guard !values.isEmpty else {
break
}
state = .sending(queue: Array(values.dropFirst()))
observer.send(value: values[0])
}
state = .idle
case let .sending(values):
state = .sending(queue: values + [transform(sender)])
}
}
}
extension CocoaTarget where Value == Void {
internal convenience init(_ observer: Signal<(), Never>.Observer) {
self.init(observer, transform: { _ in })
}
}
| mit | e6ab76b2214d2c88738092a553c4575c | 24.12069 | 97 | 0.678792 | 3.615385 | false | false | false | false |
anhnc55/fantastic-swift-library | Example/Pods/paper-onboarding/Source/PageView/PageContainerView/PageContainer.swift | 1 | 3971 | //
// PageContaineView.swift
// AnimatedPageView
//
// Created by Alex K. on 13/04/16.
// Copyright © 2016 Alex K. All rights reserved.
//
import UIKit
class PageContrainer: UIView {
var items: [PageViewItem]?
let space: CGFloat // space between items
var currentIndex = 0
private let itemRadius: CGFloat
private let selectedItemRadius: CGFloat
private let itemsCount: Int
private let animationKey = "animationKey"
init(radius: CGFloat, selectedRadius: CGFloat, space: CGFloat, itemsCount: Int) {
self.itemsCount = itemsCount
self.space = space
self.itemRadius = radius
self.selectedItemRadius = selectedRadius
super.init(frame: CGRect.zero)
items = createItems(itemsCount, radius: radius, selectedRadius: selectedRadius)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: public
extension PageContrainer {
func currenteIndex(index: Int, duration: Double, animated: Bool) {
guard let items = self.items where
index != currentIndex else {return}
animationItem(items[index], selected: true, duration: duration)
let fillColor = index > currentIndex ? true : false
animationItem(items[currentIndex], selected: false, duration: duration, fillColor: fillColor)
currentIndex = index
}
}
// MARK: animations
extension PageContrainer {
private func animationItem(item: PageViewItem, selected: Bool, duration: Double, fillColor: Bool = false) {
let toValue = selected == true ? selectedItemRadius * 2 : itemRadius * 2
item.constraints
.filter{ $0.identifier == "animationKey" }
.forEach {
$0.constant = toValue
}
UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
item.animationSelected(selected, duration: duration, fillColor: fillColor)
}
}
// MARK: create
extension PageContrainer {
private func createItems(count: Int, radius: CGFloat, selectedRadius: CGFloat) -> [PageViewItem] {
var items = [PageViewItem]()
// create first item
var item = createItem(radius, selectedRadius: selectedRadius, isSelect: true)
addConstraintsToView(item, radius: selectedRadius)
items.append(item)
for _ in 1..<count {
let nextItem = createItem(radius, selectedRadius: selectedRadius)
addConstraintsToView(nextItem, leftItem: item, radius: radius)
items.append(nextItem)
item = nextItem
}
return items
}
private func createItem(radius: CGFloat, selectedRadius: CGFloat, isSelect: Bool = false) -> PageViewItem {
let item = Init(PageViewItem(radius: radius, selectedRadius: selectedRadius, isSelect: isSelect)) {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.backgroundColor = .clearColor()
}
self.addSubview(item)
return item
}
private func addConstraintsToView(item: UIView, radius: CGFloat) {
[NSLayoutAttribute.Left, NSLayoutAttribute.CenterY].forEach { attribute in
(self, item) >>>- { $0.attribute = attribute }
}
[NSLayoutAttribute.Width, NSLayoutAttribute.Height].forEach { attribute in
item >>>- {
$0.attribute = attribute
$0.constant = radius * 2.0
$0.identifier = animationKey
}
}
}
private func addConstraintsToView(item: UIView, leftItem: UIView, radius: CGFloat) {
(self, item) >>>- { $0.attribute = .CenterY }
(self, item, leftItem) >>>- {
$0.attribute = .Leading
$0.secondAttribute = .Trailing
$0.constant = space
}
[NSLayoutAttribute.Width, NSLayoutAttribute.Height].forEach { attribute in
item >>>- {
$0.attribute = attribute
$0.constant = radius * 2.0
$0.identifier = animationKey
}
}
}
} | mit | 4633c9d48180d2ef06f264fd81acc427 | 28.857143 | 109 | 0.657179 | 4.506243 | false | false | false | false |
daniel-barros/TV-Calendar | TV Calendar/LoadingView.swift | 1 | 1385 | //
// LoadingView.swift
// TV Calendar
//
// Created by Daniel Barros López on 10/22/17.
// Copyright © 2017 Daniel Barros. All rights reserved.
//
import UIKit
class LoadingView: UIView {
@IBOutlet private weak var visualEffectView: UIVisualEffectView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var label: UILabel!
init() {
super.init(frame: .zero)
let view = Bundle.main.loadNibNamed("LoadingView", owner: self, options: nil)!.first as! UIView
view.frame = bounds
addSubview(view)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func fadeIn(completion: (() -> ())? = nil) {
visualEffectView.effect = nil
activityIndicator.alpha = 0
label.alpha = 0
UIView.animate(withDuration: 0.3, animations: {
self.visualEffectView.effect = UIBlurEffect(style: .light)
self.activityIndicator.alpha = 1
self.label.alpha = 1
}, completion: { _ in completion?() })
}
func fadeOut(completion: (() -> ())? = nil) {
UIView.animate(withDuration: 0.3, animations: {
self.visualEffectView.effect = nil
self.activityIndicator.alpha = 0
self.label.alpha = 0
}, completion: { _ in completion?() })
}
}
| gpl-3.0 | a1c70ed12e90b6a2b63684c1d14440ef | 29.065217 | 103 | 0.60376 | 4.49026 | false | false | false | false |
A-Kod/vkrypt | Pods/SwiftyVK/Library/Sources/Networking/Attempt/AttemptSheduler.swift | 4 | 1018 | import Foundation
protocol AttemptSheduler: class {
func setLimit(to: AttemptLimit)
func shedule(attempt: Attempt, concurrent: Bool)
}
final class AttemptShedulerImpl: AttemptSheduler {
private lazy var concurrentQueue: OperationQueue = {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = .max
return queue
}()
private let serialQueue: AttemptApiQueue
private var limit: AttemptLimit {
get { return serialQueue.limit }
set { serialQueue.limit = newValue }
}
init(limit: AttemptLimit) {
serialQueue = AttemptApiQueue(limit: limit)
}
func setLimit(to newLimit: AttemptLimit) {
limit = newLimit
}
func shedule(attempt: Attempt, concurrent: Bool) {
let operation = attempt.toOperation()
if concurrent {
concurrentQueue.addOperation(operation)
}
else {
self.serialQueue.addOperation(operation)
}
}
}
| apache-2.0 | fcbc59569987c75eb69259ee51f277cc | 24.45 | 56 | 0.628684 | 5.014778 | false | false | false | false |
wilzh40/SwiftSkeleton | SwiftSkeleton/MenuViewController.swift | 1 | 2807 | //
// MenuViewController.swift
// SwiftSkeleton
//
// Created by Wilson Zhao on 1/28/15.
// Copyright (c) 2015 Innogen. All rights reserved.
//
import Foundation
import UIKit
class MenuViewController: UITableViewController {
let singleton:Singleton = Singleton.sharedInstance
var tableData:NSMutableArray = ["Error"]
func setupData() {
self.tableData = singleton.centerViewControllers
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupData()
ConnectionManager.testNetworking()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "protoCell")
let VC:UIViewController = tableData[indexPath.row] as UIViewController
cell.textLabel?.text = VC.title
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Change the center view controller
let newCenterVC = singleton.centerViewControllers[indexPath.row] as UIViewController
if indexPath.row != singleton.currentCenterViewController {
// Do not allow selection of the current VC
self.evo_drawerController?.setCenterViewController(newCenterVC, withCloseAnimation: true, completion: nil)
self.evo_drawerController?.closeDrawerAnimated(true, completion: nil)
singleton.currentCenterViewController = indexPath.row
}
self.tableView.reloadData()
}
// Visually disable selection of the current VC
override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if indexPath.row == singleton.currentCenterViewController {
return false
}
return true
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if indexPath.row == singleton.currentCenterViewController {
return nil
}
return indexPath
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == singleton.currentCenterViewController {
cell.alpha = 0.4
cell.backgroundColor = UIColor.grayColor()
}
}
} | mit | 38c909bc00f16222010b87695a033fee | 33.243902 | 134 | 0.690417 | 5.752049 | false | false | false | false |
julienbodet/wikipedia-ios | Wikipedia/Code/StorageAndSyncingSettingsViewController.swift | 1 | 17594 | private struct Section {
let type: ItemType
let footerText: String?
let items: [Item]
init(for type: ItemType, with items: [Item]) {
var footerText: String? = nil
switch type {
case .syncSavedArticlesAndLists:
footerText = WMFLocalizedString("settings-storage-and-syncing-enable-sync-footer-text", value: "Allow Wikimedia to save your saved articles and reading lists to your user preferences when you login and sync.", comment: "Footer text of the settings option that enables saved articles and reading lists syncing")
case .showSavedReadingList:
footerText = WMFLocalizedString("settings-storage-and-syncing-show-default-reading-list-footer-text", value: "Show the Saved (eg. default) reading list as a separate list in your reading lists view. This list appears on Android devices.", comment: "Footer text of the settings option that enables showing the default reading list")
case .syncWithTheServer:
footerText = WMFLocalizedString("settings-storage-and-syncing-server-sync-footer-text", value: "Request an update to your synced articles and reading lists.", comment: "Footer text of the settings button that initiates saved articles and reading lists server sync")
default:
break
}
self.type = type
self.footerText = footerText
self.items = items
}
}
private struct Item {
let disclosureType: WMFSettingsMenuItemDisclosureType?
let type: ItemType
let title: String
let isSwitchOn: Bool
init(for type: ItemType, isSwitchOn: Bool = false) {
self.type = type
self.isSwitchOn = isSwitchOn
var disclosureType: WMFSettingsMenuItemDisclosureType? = nil
let title: String
switch type {
case .syncSavedArticlesAndLists:
disclosureType = .switch
title = WMFLocalizedString("settings-storage-and-syncing-enable-sync-title", value: "Sync saved articles and lists", comment: "Title of the settings option that enables saved articles and reading lists syncing")
case .showSavedReadingList:
disclosureType = .switch
title = WMFLocalizedString("settings-storage-and-syncing-show-default-reading-list-title", value: "Show Saved reading list", comment: "Title of the settings option that enables showing the default reading list")
case .syncWithTheServer:
disclosureType = .titleButton
title = WMFLocalizedString("settings-storage-and-syncing-server-sync-title", value: "Update synced reading lists", comment: "Title of the settings button that initiates saved articles and reading lists server sync")
default:
title = ""
break
}
self.title = title
self.disclosureType = disclosureType
}
}
private enum ItemType: Int {
case syncSavedArticlesAndLists, showSavedReadingList, eraseSavedArticles, syncWithTheServer
}
@objc(WMFStorageAndSyncingSettingsViewController)
class StorageAndSyncingSettingsViewController: UIViewController {
private var theme: Theme = Theme.standard
@IBOutlet weak var tableView: UITableView!
@objc public var dataStore: MWKDataStore?
private var indexPathForCellWithSyncSwitch: IndexPath?
private var shouldShowReadingListsSyncAlertWhenViewAppears = false
private var shouldShowReadingListsSyncAlertWhenSyncEnabled = false
private var sections: [Section] {
let syncSavedArticlesAndLists = Item(for: .syncSavedArticlesAndLists, isSwitchOn: isSyncEnabled)
let showSavedReadingList = Item(for: .showSavedReadingList, isSwitchOn: dataStore?.readingListsController.isDefaultListEnabled ?? false)
let eraseSavedArticles = Item(for: .eraseSavedArticles)
let syncWithTheServer = Item(for: .syncWithTheServer)
let syncSavedArticlesAndListsSection = Section(for: .syncSavedArticlesAndLists, with: [syncSavedArticlesAndLists])
let showSavedReadingListSection = Section(for: .showSavedReadingList, with: [showSavedReadingList])
let eraseSavedArticlesSection = Section(for: .eraseSavedArticles, with: [eraseSavedArticles])
let syncWithTheServerSection = Section(for: .syncWithTheServer, with: [syncWithTheServer])
return [syncSavedArticlesAndListsSection, showSavedReadingListSection, eraseSavedArticlesSection, syncWithTheServerSection]
}
override func viewDidLoad() {
super.viewDidLoad()
title = CommonStrings.settingsStorageAndSyncing
tableView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
tableView.register(WMFSettingsTableViewCell.wmf_classNib(), forCellReuseIdentifier: WMFSettingsTableViewCell.identifier)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.identifier)
tableView.register(WMFTableHeaderFooterLabelView.wmf_classNib(), forHeaderFooterViewReuseIdentifier: WMFTableHeaderFooterLabelView.identifier)
tableView.sectionFooterHeight = UITableViewAutomaticDimension
tableView.estimatedSectionFooterHeight = 44
apply(theme: self.theme)
NotificationCenter.default.addObserver(self, selector: #selector(readingListsServerDidConfirmSyncWasEnabledForAccount(notification:)), name: ReadingListsController.readingListsServerDidConfirmSyncWasEnabledForAccountNotification, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard shouldShowReadingListsSyncAlertWhenViewAppears else {
return
}
if isSyncEnabled {
showReadingListsSyncAlert()
} else { // user logged in to an account that has sync disabled, prompt them to enable sync
wmf_showEnableReadingListSyncPanel(theme: theme, oncePerLogin: false, didNotPresentPanelCompletion: nil) {
self.shouldShowReadingListsSyncAlertWhenSyncEnabled = true
}
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
tableView.reloadData()
}
private func showReadingListsSyncAlert() {
wmf_showAlertWithMessage(WMFLocalizedString("settings-storage-and-syncing-full-sync", value: "Your reading lists will be synced in the background", comment: "Message confirming to the user that their reading lists will be synced in the background"))
}
@objc private func readingListsServerDidConfirmSyncWasEnabledForAccount(notification: Notification) {
if let indexPathForCellWithSyncSwitch = indexPathForCellWithSyncSwitch {
tableView.reloadRows(at: [indexPathForCellWithSyncSwitch], with: .none)
}
guard shouldShowReadingListsSyncAlertWhenSyncEnabled else {
return
}
if isSyncEnabled {
showReadingListsSyncAlert()
}
}
private var isSyncEnabled: Bool {
guard let dataStore = dataStore else {
assertionFailure("dataStore is nil")
return false
}
return dataStore.readingListsController.isSyncEnabled
}
@objc private func eraseSavedArticles() {
let alert = UIAlertController(title: WMFLocalizedString("settings-storage-and-syncing-erase-saved-articles-alert-title", value: "Erase all saved articles?", comment: "Title of the alert shown before erasing all saved article."), message: WMFLocalizedString("settings-storage-and-syncing-erase-saved-articles-alert-message", value: "Erasing your saved articles will remove them from your user account if you have syncing turned on as well as from this device. You cannot undo this action.", comment: "Message for the alert shown before erasing all saved articles."), preferredStyle: .alert)
let cancel = UIAlertAction(title: CommonStrings.cancelActionTitle, style: .cancel)
let erase = UIAlertAction(title: CommonStrings.eraseAllSavedArticles, style: .destructive) { (_) in
guard let isSyncEnabled = self.dataStore?.readingListsController.isSyncEnabled else {
assertionFailure("dataStore is nil")
return
}
self.dataStore?.clearCachesForUnsavedArticles()
if isSyncEnabled {
self.dataStore?.readingListsController.setSyncEnabled(true, shouldDeleteLocalLists: true, shouldDeleteRemoteLists: true)
} else {
self.dataStore?.readingListsController.setSyncEnabled(true, shouldDeleteLocalLists: true, shouldDeleteRemoteLists: true)
self.dataStore?.readingListsController.setSyncEnabled(false, shouldDeleteLocalLists: false, shouldDeleteRemoteLists: false)
}
self.tableView.reloadData()
}
alert.addAction(cancel)
alert.addAction(erase)
present(alert, animated: true)
}
private lazy var eraseSavedArticlesView: EraseSavedArticlesView? = {
let eraseSavedArticlesView = EraseSavedArticlesView.wmf_viewFromClassNib()
eraseSavedArticlesView?.titleLabel.text = CommonStrings.eraseAllSavedArticles
eraseSavedArticlesView?.button.setTitle(WMFLocalizedString("settings-storage-and-syncing-erase-saved-articles-button-title", value: "Erase", comment: "Title of the settings button that enables erasing saved articles"), for: .normal)
eraseSavedArticlesView?.button.addTarget(self, action: #selector(eraseSavedArticles), for: .touchUpInside)
return eraseSavedArticlesView
}()
}
// MARK: UITableViewDataSource
extension StorageAndSyncingSettingsViewController: UITableViewDataSource {
private func getItem(at indexPath: IndexPath) -> Item {
return sections[indexPath.section].items[indexPath.row]
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let settingsItem = getItem(at: indexPath)
guard let disclosureType = settingsItem.disclosureType else {
let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.identifier, for: indexPath)
cell.selectionStyle = .none
cell.backgroundColor = theme.colors.paperBackground
if let eraseSavedArticlesView = eraseSavedArticlesView {
let temporaryCacheSize = ImageController.shared.temporaryCacheSize
let sitesDirectorySize = Int64(dataStore?.sitesDirectorySize() ?? 0)
let dataSizeString = ByteCountFormatter.string(fromByteCount: temporaryCacheSize + sitesDirectorySize, countStyle: .file)
let format = WMFLocalizedString("settings-storage-and-syncing-erase-saved-articles-footer-text", value: "Erasing your saved articles will remove them from your user account if you have syncing turned on as well as from this device.\n\nErasing your saved articles will free up about %1$@ of space.", comment: "Footer text of the settings option that enables erasing saved articles. %1$@ will be replaced with a number and a system provided localized unit indicator for MB or KB.")
eraseSavedArticlesView.footerLabel.text = String.localizedStringWithFormat(format, dataSizeString)
eraseSavedArticlesView.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.wmf_addSubviewWithConstraintsToEdges(eraseSavedArticlesView)
} else {
assertionFailure("Couldn't load EraseSavedArticlesView from nib")
}
return cell
}
guard let cell = tableView.dequeueReusableCell(withIdentifier: WMFSettingsTableViewCell.identifier, for: indexPath) as? WMFSettingsTableViewCell else {
return UITableViewCell()
}
cell.delegate = self
cell.configure(disclosureType, disclosureText: nil, title: settingsItem.title, subtitle: nil, iconName: nil, isSwitchOn: settingsItem.isSwitchOn, iconColor: nil, iconBackgroundColor: nil, controlTag: settingsItem.type.rawValue, theme: theme)
if settingsItem.type == .syncSavedArticlesAndLists {
indexPathForCellWithSyncSwitch = indexPath
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let item = getItem(at: indexPath)
switch item.type {
case .syncWithTheServer:
let loginSuccessCompletion = {
self.dataStore?.readingListsController.fullSync({})
self.shouldShowReadingListsSyncAlertWhenViewAppears = true
}
if WMFAuthenticationManager.sharedInstance.isLoggedIn && isSyncEnabled {
dataStore?.readingListsController.fullSync({})
showReadingListsSyncAlert()
} else if !WMFAuthenticationManager.sharedInstance.isLoggedIn {
wmf_showLoginOrCreateAccountToSyncSavedArticlesToReadingListPanel(theme: theme, dismissHandler: nil, loginSuccessCompletion: loginSuccessCompletion, loginDismissedCompletion: nil)
} else {
wmf_showEnableReadingListSyncPanel(theme: theme, oncePerLogin: false, didNotPresentPanelCompletion: nil) {
self.shouldShowReadingListsSyncAlertWhenSyncEnabled = true
}
}
default:
break
}
}
}
// MARK: UITableViewDelegate
extension StorageAndSyncingSettingsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard let footer = tableView.dequeueReusableHeaderFooterView(withIdentifier: WMFTableHeaderFooterLabelView.identifier) as? WMFTableHeaderFooterLabelView else {
return nil
}
footer.setShortTextAsProse(sections[section].footerText)
footer.type = .footer
if let footer = footer as Themeable? {
footer.apply(theme: theme)
}
return footer
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
guard let _ = self.tableView(tableView, viewForFooterInSection: section) as? WMFTableHeaderFooterLabelView else {
return 0
}
return UITableViewAutomaticDimension
}
}
// MARK: - WMFSettingsTableViewCellDelegate
extension StorageAndSyncingSettingsViewController: WMFSettingsTableViewCellDelegate {
func settingsTableViewCell(_ settingsTableViewCell: WMFSettingsTableViewCell!, didToggleDisclosureSwitch sender: UISwitch!) {
guard let settingsItemType = ItemType(rawValue: sender.tag) else {
assertionFailure("Toggled discloure switch of WMFSettingsTableViewCell for undefined StorageAndSyncingSettingsItemType")
return
}
guard let dataStore = self.dataStore else {
return
}
let isSwitchOn = sender.isOn
switch settingsItemType {
case .syncSavedArticlesAndLists where !WMFAuthenticationManager.sharedInstance.isLoggedIn:
assert(!isSyncEnabled, "Sync cannot be enabled if user is not logged in")
let dismissHandler = {
sender.setOn(false, animated: true)
}
let loginSuccessCompletion: () -> Void = {
dataStore.readingListsController.setSyncEnabled(true, shouldDeleteLocalLists: false, shouldDeleteRemoteLists: false)
SettingsFunnel.shared.logSyncEnabledInSettings()
}
wmf_showLoginOrCreateAccountToSyncSavedArticlesToReadingListPanel(theme: theme, dismissHandler: dismissHandler, loginSuccessCompletion: loginSuccessCompletion, loginDismissedCompletion: dismissHandler)
case .syncSavedArticlesAndLists where WMFAuthenticationManager.sharedInstance.isLoggedIn:
let setSyncEnabled = {
dataStore.readingListsController.setSyncEnabled(isSwitchOn, shouldDeleteLocalLists: false, shouldDeleteRemoteLists: !isSwitchOn)
if isSwitchOn {
SettingsFunnel.shared.logSyncEnabledInSettings()
} else {
SettingsFunnel.shared.logSyncDisabledInSettings()
}
}
if !isSwitchOn {
self.wmf_showKeepSavedArticlesOnDevicePanelIfNecessary(triggeredBy: .syncDisabled, theme: self.theme) {
setSyncEnabled()
}
} else {
setSyncEnabled()
}
case .showSavedReadingList:
dataStore.readingListsController.isDefaultListEnabled = isSwitchOn
default:
return
}
}
}
// MARK: Themeable
extension StorageAndSyncingSettingsViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
tableView.backgroundColor = theme.colors.baseBackground
eraseSavedArticlesView?.apply(theme: theme)
}
}
| mit | 3c200691f8b462d59032d7873af3ace9 | 51.053254 | 597 | 0.700807 | 5.870537 | false | false | false | false |
iluuu1994/Conway-s-Game-of-Life | Conway's Game of Life/Conway's Game of Life/CGOLView.swift | 1 | 4069 | //
// CGOLView.swift
// Conway's Game of Life
//
// Created by Ilija Tovilo on 26/08/14.
// Copyright (c) 2014 Ilija Tovilo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class CGOLView: UIView {
// --------------------
// MARK: - Properties -
// --------------------
private var _gridWidth = 10
private var _gridHeight = 10
private var _gameModel: CGOLModel!
private var _tileViews: Matrix<TileView!>!
// --------------
// MARK: - Init -
// --------------
public init(gridWidth: Int, gridHeight: Int) {
super.init(frame: CGRect(x: 0, y: 0, width:500 , height: 500))
_init(gridWidth: gridWidth, gridHeight: gridHeight)
}
required public init(coder: NSCoder) {
super.init(coder: coder)
_init(gridWidth: _gridWidth, gridHeight: _gridHeight)
}
private func _init(#gridWidth: Int, gridHeight: Int) {
// Init values
_gridWidth = gridWidth
_gridHeight = gridHeight
_gameModel = CGOLModel(gridWidth: _gridWidth, gridHeight: _gridHeight)
_tileViews = Matrix<TileView!>(width: _gridWidth, height: _gridHeight, repeatedValue: nil)
// Fill the matrix with views
for (x, y, _) in _tileViews {
let tileView = TileView(frame: CGRectZero)
tileView.coordinates = (x: x, y: y)
let tileModel = _gameModel.getTile(x: x, y: y)
// Two way binding
tileView.twoWayBinding = TwoWayBinding(
leadingElement: tileModel,
leadingKeyPath: "alive",
followingElement: tileView,
followingKeyPath: "alive"
)
addSubview(tileView)
_tileViews[x, y] = tileView
}
}
// -----------------
// MARK: - Methods -
// -----------------
public func step() {
_gameModel.step()
}
public func clear() {
_gameModel.clear()
}
// ----------------
// MARK: - Layout -
// ----------------
override public func layoutSubviews() {
super.layoutSubviews()
_layoutTiles()
}
private func _layoutTiles() {
for (x, y, tileView) in _tileViews {
tileView.frame = tileFrame(x: x, y: y)
}
}
private var tileSize: CGSize {
return CGSize(
width: bounds.width / CGFloat(_gridWidth),
height: bounds.height / CGFloat(_gridHeight)
)
}
private func tileOrigin(coordinates: TileCoordinates) -> CGPoint {
return CGPoint(
x: CGFloat(coordinates.x) * tileSize.width,
y: CGFloat(coordinates.y) * tileSize.height
)
}
private func tileFrame(coordinates: TileCoordinates) -> CGRect {
return CGRect(
origin: tileOrigin(coordinates),
size: tileSize
)
}
}
| bsd-2-clause | f7a04f8a42c5ec92ecd70f19b33ac764 | 30.061069 | 98 | 0.579749 | 4.59774 | false | false | false | false |
lnds/9d9l | desafio1/swift/Sources/toque-y-fama/main.swift | 1 | 1980 |
func validar(tam:Int, acc:String!) -> [Int]? {
var num = [Int]()
let chars = Array(acc)
for (i,c) in chars.enumerated() {
if i >= tam {
return nil
} else if c < "0" || c > "9" {
return nil
} else {
let digito = Int(String(c))!
if num.contains(digito) {
return nil
}
num.append(Int(String(c))!)
}
}
if num.count != tam { return nil }
return num
}
func comparar(num:[Int], sec:[Int]) -> (toques:Int, famas:Int) {
var toques = 0
var famas = 0
for (i, n) in num.enumerated() {
for (j, m) in sec.enumerated() {
if n == m {
if i == j { famas += 1 }
else { toques += 1 }
}
}
}
return (toques, famas)
}
let tam = 5
let numbers = 0...9
var sec = Array(numbers.shuffled().prefix(tam))
print (" Bienvenido a Toque y Fama.\n",
"==========================\n\n",
"En este juego debes tratar de adivinar una secuencia de \(tam) dígitos generadas por el programa.\n",
"Para esto ingresas \(tam) dígitos distintos con el fin de adivinar la secuencia.\n",
"Si has adivinado correctamente la posición de un dígito se produce una Fama.\n",
"Si has adivinado uno de los dígitos de la secuencia, pero en una posición distinta se trata de un Toque.\n\n",
"Ejemplo: Si la secuencia es secuencia: [8, 0, 6, 1, 3] e ingresas 40863, entonces en pantalla aparecerá:\n",
"tu ingresaste [4, 0, 8, 6, 3]\n",
"resultado: 2 Toques 2 Famas\n\n")
var intentos = 0
while true {
intentos += 1
print("Ingresa una secuencia de \(tam) dígitos distintos (o escribe salir):")
let accion = readLine(strippingNewline:true)
if accion == "salir" {
break
} else {
let num = validar(tam:tam, acc:accion!)
if num == nil {
print("error!\n")
} else {
print("ingresaste: ", num!)
let (toques, famas) = comparar(num: num!, sec:sec)
print("resultado: \(toques) Toques, \(famas) Famas\n")
if famas == tam {
print("Ganaste! Acertaste al intento \(intentos)! La secuencia era \(sec).")
break
}
}
}
} | mit | f281d3a9ac29ca74fa8ae01e5cb3f111 | 26.027397 | 113 | 0.611562 | 2.712517 | false | false | false | false |
SixFiveSoftware/Swift_Pair_Programming_Resources | FizzBuzz/FizzBuzz/FizzBuzz.swift | 1 | 900 | //
// FizzBuzz.swift
// FizzBuzz
//
// Created by BJ Miller on 9/27/14.
// Copyright (c) 2014 Six Five Software, LLC. All rights reserved.
//
import Foundation
struct FizzBuzz {
static func check(value: Int) -> String {
var returnValue = "\(value)"
if value % 3 == 0 {
returnValue = "Fizz"
}
if value % 5 == 0 {
returnValue = (returnValue == "Fizz" )
? "FizzBuzz"
: "Buzz"
}
return returnValue
}
}
extension Int {
var FizzBuzz: String {
var returnValue = "\(self)"
if self % 3 == 0 {
returnValue = "Fizz"
}
if self % 5 == 0 {
returnValue = (returnValue == "Fizz" )
? "FizzBuzz"
: "Buzz"
}
return returnValue
}
} | mit | b6d566a42ee4d346f762d8acf28a87ce | 20.97561 | 67 | 0.436667 | 4.522613 | false | false | false | false |
kaushaldeo/Olympics | Olympics/Views/KDStoryboardSegue.swift | 1 | 1148 | //
// KDStoryboardSegue.swift
// Olympics
//
// Created by Kaushal Deo on 6/27/16.
// Copyright © 2016 Scorpion Inc. All rights reserved.
//
import UIKit
class KDStoryboardSegue: UIStoryboardSegue {
override func perform() {
if let window = self.sourceViewController.view.window {
let snapShot = window.snapshotViewAfterScreenUpdates(true)
self.destinationViewController.view.addSubview(snapShot)
window.rootViewController = self.destinationViewController
UIView.animateWithDuration(0.5, animations: {
snapShot.layer.opacity = 0
snapShot.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5)
}, completion: { (finished) in
snapShot.removeFromSuperview()
})
}
}
}
class KDReplaceSegue: UIStoryboardSegue {
override func perform() {
if let window = self.sourceViewController.view.window {
window.rootViewController = self.destinationViewController
}
}
}
| apache-2.0 | c3639a0a3bc9b3345031f7d9422b9a0f | 25.674419 | 80 | 0.58762 | 5.261468 | false | false | false | false |
parkera/swift-corelibs-foundation | Foundation/Host.swift | 1 | 10095 | // 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
//
import CoreFoundation
open class Host: NSObject {
enum ResolveType {
case name
case address
case current
}
internal var _info: String?
internal var _type: ResolveType
internal var _resolved = false
internal var _names = [String]()
internal var _addresses = [String]()
#if os(Android)
static internal let NI_MAXHOST = 1025
#endif
static internal let _current = Host(currentHostName(), .current)
internal init(_ info: String?, _ type: ResolveType) {
_info = info
_type = type
}
static internal func currentHostName() -> String {
#if os(Windows)
var dwLength: DWORD = 0
GetComputerNameExA(ComputerNameDnsHostname, nil, &dwLength)
guard dwLength > 0 else { return "localhost" }
guard let hostname: UnsafeMutablePointer<Int8> =
UnsafeMutableBufferPointer<Int8>
.allocate(capacity: Int(dwLength + 1))
.baseAddress else {
return "localhost"
}
defer { hostname.deallocate() }
guard GetComputerNameExA(ComputerNameDnsHostname, hostname, &dwLength) != FALSE else {
return "localhost"
}
return String(cString: hostname)
#else
let hname = UnsafeMutablePointer<Int8>.allocate(capacity: Int(NI_MAXHOST))
defer {
hname.deallocate()
}
let r = gethostname(hname, Int(NI_MAXHOST))
if r < 0 || hname[0] == 0 {
return "localhost"
}
return String(cString: hname)
#endif
}
open class func current() -> Host {
return _current
}
public convenience init(name: String?) {
self.init(name, .name)
}
public convenience init(address: String) {
self.init(address, .address)
}
open func isEqual(to aHost: Host) -> Bool {
if self === aHost { return true }
return addresses.firstIndex { aHost.addresses.contains($0) } != nil
}
internal func _resolveCurrent() {
#if os(Android)
return
#elseif os(Windows)
var ulSize: ULONG = 0
var ulResult: ULONG =
GetAdaptersAddresses(ULONG(AF_UNSPEC), 0, nil, nil, &ulSize)
let arAdapterInfo: UnsafeMutablePointer<IP_ADAPTER_ADDRESSES> =
UnsafeMutablePointer<IP_ADAPTER_ADDRESSES_LH>
.allocate(capacity: Int(ulSize) / MemoryLayout<IP_ADAPTER_ADDRESSES>.size)
defer { arAdapterInfo.deallocate() }
ulResult = GetAdaptersAddresses(ULONG(AF_UNSPEC), 0, nil, arAdapterInfo, &ulSize)
var buffer: UnsafeMutablePointer<WCHAR> =
UnsafeMutablePointer<WCHAR>.allocate(capacity: Int(NI_MAXHOST))
defer { buffer.deallocate() }
var arCurrentAdapterInfo: UnsafeMutablePointer<IP_ADAPTER_ADDRESSES>? =
arAdapterInfo
while arCurrentAdapterInfo != nil {
var arAddress: UnsafeMutablePointer<IP_ADAPTER_UNICAST_ADDRESS>? =
arCurrentAdapterInfo!.pointee.FirstUnicastAddress
while arAddress != nil {
let arCurrentAddress: IP_ADAPTER_UNICAST_ADDRESS = arAddress!.pointee
switch arCurrentAddress.Address.lpSockaddr.pointee.sa_family {
case ADDRESS_FAMILY(AF_INET), ADDRESS_FAMILY(AF_INET6):
if GetNameInfoW(arCurrentAddress.Address.lpSockaddr,
arCurrentAddress.Address.iSockaddrLength,
buffer, DWORD(NI_MAXHOST),
nil, 0, NI_NUMERICHOST) == 0 {
_addresses.append(String(decodingCString: buffer,
as: UTF16.self))
}
default: break
}
arAddress = arCurrentAddress.Next
}
arCurrentAdapterInfo = arCurrentAdapterInfo!.pointee.Next
}
_resolved = true
#else
var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
if getifaddrs(&ifaddr) != 0 {
return
}
var ifa: UnsafeMutablePointer<ifaddrs>? = ifaddr
let address = UnsafeMutablePointer<Int8>.allocate(capacity: Int(NI_MAXHOST))
defer {
freeifaddrs(ifaddr)
address.deallocate()
}
while let ifaValue = ifa?.pointee {
if let ifa_addr = ifaValue.ifa_addr, ifaValue.ifa_flags & UInt32(IFF_LOOPBACK) == 0 {
let family = ifa_addr.pointee.sa_family
if family == sa_family_t(AF_INET) || family == sa_family_t(AF_INET6) {
let sa_len: socklen_t = socklen_t((family == sa_family_t(AF_INET6)) ? MemoryLayout<sockaddr_in6>.size : MemoryLayout<sockaddr_in>.size)
if getnameinfo(ifa_addr, sa_len, address, socklen_t(NI_MAXHOST), nil, 0, NI_NUMERICHOST) == 0 {
_addresses.append(String(cString: address))
}
}
}
ifa = ifaValue.ifa_next
}
_resolved = true
#endif
}
internal func _resolve() {
guard _resolved == false else { return }
#if os(Android)
return
#elseif os(Windows)
if let info = _info {
if _type == .current { return _resolveCurrent() }
var hints: ADDRINFOW = ADDRINFOW()
memset(&hints, 0, MemoryLayout<ADDRINFOW>.size)
switch (_type) {
case .name:
hints.ai_flags = AI_PASSIVE | AI_CANONNAME
case .address:
hints.ai_flags = AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST
case .current:
break
}
hints.ai_family = AF_UNSPEC
hints.ai_socktype = SOCK_STREAM
hints.ai_protocol = IPPROTO_TCP.rawValue
var aiResult: UnsafeMutablePointer<ADDRINFOW>?
var bSucceeded: Bool = false
info.withCString(encodedAs: UTF16.self) {
if GetAddrInfoW($0, nil, &hints, &aiResult) == 0 {
bSucceeded = true
}
}
guard bSucceeded == true else { return }
defer { FreeAddrInfoW(aiResult) }
let wszHostName =
UnsafeMutablePointer<WCHAR>.allocate(capacity: Int(NI_MAXHOST))
defer { wszHostName.deallocate() }
while aiResult != nil {
let aiInfo: ADDRINFOW = aiResult!.pointee
var sa_len: socklen_t = 0
switch aiInfo.ai_family {
case AF_INET:
sa_len = socklen_t(MemoryLayout<sockaddr_in>.size)
case AF_INET6:
sa_len = socklen_t(MemoryLayout<sockaddr_in6>.size)
default:
aiResult = aiInfo.ai_next
continue
}
let lookup = { (content: inout [String], flags: Int32) in
if GetNameInfoW(aiInfo.ai_addr, sa_len, wszHostName,
DWORD(NI_MAXHOST), nil, 0, flags) == 0 {
content.append(String(decodingCString: wszHostName,
as: UTF16.self))
}
}
lookup(&_addresses, NI_NUMERICHOST)
lookup(&_names, NI_NAMEREQD)
lookup(&_names, NI_NOFQDN | NI_NAMEREQD)
aiResult = aiInfo.ai_next
}
_resolved = true
}
#else
if let info = _info {
var flags: Int32 = 0
switch (_type) {
case .name:
flags = AI_PASSIVE | AI_CANONNAME
case .address:
flags = AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST
case .current:
_resolveCurrent()
return
}
var hints = addrinfo()
hints.ai_family = PF_UNSPEC
#if os(macOS) || os(iOS) || os(Android)
hints.ai_socktype = SOCK_STREAM
#else
hints.ai_socktype = Int32(SOCK_STREAM.rawValue)
#endif
hints.ai_flags = flags
var res0: UnsafeMutablePointer<addrinfo>? = nil
let r = getaddrinfo(info, nil, &hints, &res0)
defer {
freeaddrinfo(res0)
}
if r != 0 {
return
}
var res: UnsafeMutablePointer<addrinfo>? = res0
let host = UnsafeMutablePointer<Int8>.allocate(capacity: Int(NI_MAXHOST))
defer {
host.deallocate()
}
while res != nil {
let info = res!.pointee
let family = info.ai_family
if family != AF_INET && family != AF_INET6 {
res = info.ai_next
continue
}
let sa_len: socklen_t = socklen_t((family == AF_INET6) ? MemoryLayout<sockaddr_in6>.size : MemoryLayout<sockaddr_in>.size)
let lookupInfo = { (content: inout [String], flags: Int32) in
if getnameinfo(info.ai_addr, sa_len, host, socklen_t(NI_MAXHOST), nil, 0, flags) == 0 {
content.append(String(cString: host))
}
}
lookupInfo(&_addresses, NI_NUMERICHOST)
lookupInfo(&_names, NI_NAMEREQD)
lookupInfo(&_names, NI_NOFQDN|NI_NAMEREQD)
res = info.ai_next
}
_resolved = true
}
#endif
}
open var name: String? {
return names.first
}
open var names: [String] {
_resolve()
return _names
}
open var address: String? {
return addresses.first
}
open var addresses: [String] {
_resolve()
return _addresses
}
open var localizedName: String? {
return nil
}
}
| apache-2.0 | 7c635dce2643257d28c73b7e34389e07 | 32.875839 | 155 | 0.546112 | 4.437363 | false | false | false | false |
rizumita/TransitionOperator | TransitionOperator/CompositeTransitionOperator.swift | 1 | 1261 | //
// CompositeTransitionOperator.swift
// TransitionOperator
//
// Created by 和泉田 領一 on 2016/02/28.
// Copyright © 2016年 CAPH TECH. All rights reserved.
//
import Foundation
public class CompositeTransitionOperator: TransitionOperatorType, ArrayLiteralConvertible {
public typealias Element = TransitionOperatorType
public required init(arrayLiteral elements: Element...) {
operators = elements
}
public var forced: Bool = false
private var operators: [Element] = []
init(operators: [Element], forced: Bool = false) {
self.operators = operators
}
public func add(nextOperator nextOperator: Element) {
operators.append(nextOperator)
}
public func operate(executor executor: TransitionExecutorType, source: Any, destination: Any) -> Bool {
for op in operators {
if op.operate(executor: executor, source: source, destination: destination) == false && !forced {
return false
}
}
return true
}
}
infix operator += {}
public func +=(compositeOperator: CompositeTransitionOperator, nextOperator: TransitionOperatorType) {
compositeOperator.add(nextOperator: nextOperator)
}
| mit | 3c2ca6795ed07b45d3bf9aaa0b63ff83 | 26.130435 | 109 | 0.666667 | 4.875 | false | false | false | false |
tomtclai/swift-algorithm-club | Monty Hall Problem/MontyHall.playground/Contents.swift | 8 | 1332 | //: Playground - noun: a place where people can play
import Foundation
func random(_ n: Int) -> Int {
return Int(arc4random_uniform(UInt32(n)))
}
let numberOfDoors = 3
var rounds = 0
var winOriginalChoice = 0
var winChangedMind = 0
func playRound() {
// The door with the prize.
let prizeDoor = random(numberOfDoors)
// The door the player chooses.
let chooseDoor = random(numberOfDoors)
// The door that Monty opens. This must be empty and not the one the player chose.
var openDoor = -1
repeat {
openDoor = random(numberOfDoors)
} while openDoor == prizeDoor || openDoor == chooseDoor
// What happens when the player changes his mind and picks the other door.
var changeMind = -1
repeat {
changeMind = random(numberOfDoors)
} while changeMind == openDoor || changeMind == chooseDoor
// Figure out which choice was the winner.
if chooseDoor == prizeDoor {
winOriginalChoice += 1
}
if changeMind == prizeDoor {
winChangedMind += 1
}
rounds += 1
}
// Run the simulation a large number of times.
for i in 1...5000 {
playRound()
}
let stubbornPct = Double(winOriginalChoice)/Double(rounds)
let changedMindPct = Double(winChangedMind)/Double(rounds)
print(String(format: "Played %d rounds, stubborn: %g%% vs changed mind: %g%%", rounds, stubbornPct, changedMindPct))
| mit | 491ac5e82a9d5cd6d0193c303abdedd5 | 24.132075 | 116 | 0.702703 | 4.048632 | false | false | false | false |
MrSuperJJ/JJMediatorDemo | JJMediatorDemo/JJMediator/JJMediator.swift | 1 | 4920 | //
// JJMediator.swift
// JJMediator
//
// Created by yejiajun on 2017/4/27.
// Copyright © 2017年 yejiajun. All rights reserved.
//
import UIKit
public class JJMediator: NSObject {
// 单例
private static let singleInstance = JJMediator()
public class func sharedInstance() -> JJMediator {
return singleInstance
}
/// 远程APP调用入口
/// 格式 - scheme://[target]/[action]?[params],例子 - scheme://target/action?key=value
/// 上述URL为固定格式,有定制化需求的话,请修改具体的处理逻辑
///
/// - Parameters:
/// - URL: URL
/// - completion: block回调
public func performAction(URL url: URL, completion: (_ result: AnyObject) -> Void) -> AnyObject? {
// 判断URLScheme和命名空间(项目名称)是否一致
let scheme = url.scheme!
guard scheme == fetchNameSpace() else {
return NSNumber(value: false)
}
var parameters = Dictionary<String, Any>()
let targetName = url.host
let actionName = url.lastPathComponent
let parameterString = url.query
if let targetName = targetName, let parameterString = parameterString {
let keyEqualValueArray = parameterString.components(separatedBy: "&")
for keyEqualValueString in keyEqualValueArray {
let keyAndValueArray = keyEqualValueString.components(separatedBy: "=")
if keyAndValueArray.count != 2 {
continue
}
parameters[keyAndValueArray[0]] = keyAndValueArray[1]
}
// 远程调用的Action方法,为保证结构统一,parameters参数建议使用字典类型封装
let result = perform(targetName: targetName, actionName: actionName, parameters: parameters)
if let result = result{
completion(result)
}
}
return NSNumber(value: true)
}
/// 本地组件调用入口
///
/// - Parameters:
/// - targetName: target名称
/// - actionName: action名称
/// - parameters: 参数
/// - isSwiftClass: target是否是Swift类
/// - Returns: Optional<AnyObject>对象
public func perform(targetName: String, actionName: String, parameters: Dictionary<String, Any>?, moduleName: String? = nil) -> AnyObject? {
// Target名称(类名),Swift类需加上命名空间
let targetClassString: String
if let moduleName = moduleName {
targetClassString = moduleName + "." + "Target_" + targetName
} else {
targetClassString = "Target_" + targetName
}
// Action名称(方法名)
let actionString = "Action_" + actionName + (parameters != nil ? ":" : "" )
// // 根据Target获取Class,返回Optional<NSObject.Type>类型的值
// let targetClass = NSClassFromString(targetClassString) as? NSObject.Type
// // Class实例化,返回Optional<NSObject>类型的值
// let target = targetClass?.init()
// 根据Target获取Class,返回Optional<AnyClass>类型的值
let targetClass: AnyClass? = NSClassFromString(targetClassString)
// Class实例化,返回Optional<AnyObject>类型的值
let target = targetClass?.alloc()
// 根据Action获取Selector
let action = NSSelectorFromString(actionString)
if let target = target {
// 检查Class实例能否响应Action方法,并执行Selector
if target.responds(to: action) {
let object = target.perform(action, with: parameters)
// 返回Optional<Unmanaged<AnyObject>>对象
if let object = object {
return object.takeUnretainedValue()
} else {
return nil
}
} else {
// 无响应请求时,调用默认notFound方法
let action = NSSelectorFromString("notFound:")
if target.responds(to: action) {
let object = target.perform(action, with: parameters)
if let object = object {
return object.takeUnretainedValue()
} else {
return nil
}
} else {
// notFound方法也无响应时,返回nil
return nil
}
}
} else {
// target不存在,返回nil
return nil
}
}
// 获取命名空间
private func fetchNameSpace() -> String {
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
return namespace
}
}
| mit | ae1875fd2701f25906e21d849b38629d | 34.704 | 144 | 0.552095 | 4.920617 | false | false | false | false |
Rag0n/QuNotes | Core/Utility/Extensions/Array+Extensions.swift | 1 | 921 | //
// Array+Extensions.swift
// QuNotes
//
// Created by Alexander Guschin on 12.07.17.
// Copyright © 2017 Alexander Guschin. All rights reserved.
//
extension Array where Element: Equatable {
func appending(_ newElement: Element) -> [Element] {
var updatedArray = self
updatedArray.append(newElement)
return updatedArray
}
func removing(_ element: Element) -> [Element] {
guard let index = index(of: element) else { return self }
var updatedArray = self
updatedArray.remove(at: index)
return updatedArray
}
func removing(at index: Int) -> [Element] {
var updatedArray = self
updatedArray.remove(at: index)
return updatedArray
}
func replacing(at index: Int, with element: Element) -> [Element] {
var updatedArray = self
updatedArray[index] = element
return updatedArray
}
}
| gpl-3.0 | e2cad8264983a457b89653fee6fb753b | 26.058824 | 71 | 0.629348 | 4.509804 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Services/Service.LeakSensor.swift | 1 | 1380 | import Foundation
extension Service {
open class LeakSensor: Service {
public init(characteristics: [AnyCharacteristic] = []) {
var unwrapped = characteristics.map { $0.wrapped }
leakDetected = getOrCreateAppend(
type: .leakDetected,
characteristics: &unwrapped,
generator: { PredefinedCharacteristic.leakDetected() })
name = get(type: .name, characteristics: unwrapped)
statusActive = get(type: .statusActive, characteristics: unwrapped)
statusFault = get(type: .statusFault, characteristics: unwrapped)
statusLowBattery = get(type: .statusLowBattery, characteristics: unwrapped)
statusTampered = get(type: .statusTampered, characteristics: unwrapped)
super.init(type: .leakSensor, characteristics: unwrapped)
}
// MARK: - Required Characteristics
public let leakDetected: GenericCharacteristic<Enums.LeakDetected>
// MARK: - Optional Characteristics
public let name: GenericCharacteristic<String>?
public let statusActive: GenericCharacteristic<Bool>?
public let statusFault: GenericCharacteristic<UInt8>?
public let statusLowBattery: GenericCharacteristic<Enums.StatusLowBattery>?
public let statusTampered: GenericCharacteristic<UInt8>?
}
}
| mit | 05e7d9e44a734f587496534fe2fb800e | 46.586207 | 87 | 0.673188 | 5.542169 | false | false | false | false |
openhab/openhab.ios | openHAB/DynamicButtonStyleBell.swift | 1 | 2084 | // Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import DynamicButton
import UIKit
/// Bell symbol style: 🔔
struct DynamicButtonStyleBell: DynamicButtonBuildableStyle {
/// "Bell" style.
static var styleName: String {
"Bell"
}
let pathVector: DynamicButtonPathVector
init(center: CGPoint, size: CGFloat, offset: CGPoint, lineWidth: CGFloat) {
let gongRadius = size / 7
let gongCenter = CGPoint(x: center.x, y: size - gongRadius - lineWidth)
let startAngle = CGFloat.pi
let endAngle = startAngle + CGFloat.pi
let gongPath = UIBezierPath(arcCenter: gongCenter, radius: gongRadius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
let bellHeight = gongCenter.y - (lineWidth / 2.0)
let bellTop = UIBezierPath()
bellTop.move(to: CGPoint(x: 0, y: 26))
bellTop.addCurve(to: CGPoint(x: 6, y: 12), controlPoint1: CGPoint(x: 0, y: 26), controlPoint2: CGPoint(x: 4.5, y: 22))
bellTop.addCurve(to: CGPoint(x: 16, y: 2), controlPoint1: CGPoint(x: 6, y: 6), controlPoint2: CGPoint(x: 10.5, y: 2))
bellTop.addCurve(to: CGPoint(x: 26, y: 12), controlPoint1: CGPoint(x: 21.5, y: 2), controlPoint2: CGPoint(x: 26, y: 6))
bellTop.addCurve(to: CGPoint(x: 32, y: 26), controlPoint1: CGPoint(x: 27.5, y: 22), controlPoint2: CGPoint(x: 32, y: 26))
bellTop.apply(CGAffineTransform(scaleX: size / 32.0, y: bellHeight / 26.0))
let bellBottom = UIBezierPath()
bellBottom.move(to: CGPoint(x: 0, y: bellHeight))
bellBottom.addLine(to: CGPoint(x: size, y: bellHeight))
pathVector = DynamicButtonPathVector(p1: bellTop.cgPath, p2: bellBottom.cgPath, p3: bellBottom.cgPath, p4: gongPath.cgPath)
}
}
| epl-1.0 | 7c181e457acbffeaa59681b031d09552 | 42.354167 | 140 | 0.673715 | 3.631763 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/DiscountCodeApplication.swift | 1 | 7206 | //
// DiscountCodeApplication.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// Discount code applications capture the intentions of a discount code at the
/// time that it is applied.
open class DiscountCodeApplicationQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = DiscountCodeApplication
/// The method by which the discount's value is allocated to its entitled
/// items.
@discardableResult
open func allocationMethod(alias: String? = nil) -> DiscountCodeApplicationQuery {
addField(field: "allocationMethod", aliasSuffix: alias)
return self
}
/// Specifies whether the discount code was applied successfully.
@discardableResult
open func applicable(alias: String? = nil) -> DiscountCodeApplicationQuery {
addField(field: "applicable", aliasSuffix: alias)
return self
}
/// The string identifying the discount code that was used at the time of
/// application.
@discardableResult
open func code(alias: String? = nil) -> DiscountCodeApplicationQuery {
addField(field: "code", aliasSuffix: alias)
return self
}
/// Which lines of targetType that the discount is allocated over.
@discardableResult
open func targetSelection(alias: String? = nil) -> DiscountCodeApplicationQuery {
addField(field: "targetSelection", aliasSuffix: alias)
return self
}
/// The type of line that the discount is applicable towards.
@discardableResult
open func targetType(alias: String? = nil) -> DiscountCodeApplicationQuery {
addField(field: "targetType", aliasSuffix: alias)
return self
}
/// The value of the discount application.
@discardableResult
open func value(alias: String? = nil, _ subfields: (PricingValueQuery) -> Void) -> DiscountCodeApplicationQuery {
let subquery = PricingValueQuery()
subfields(subquery)
addField(field: "value", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// Discount code applications capture the intentions of a discount code at the
/// time that it is applied.
open class DiscountCodeApplication: GraphQL.AbstractResponse, GraphQLObject, DiscountApplication {
public typealias Query = DiscountCodeApplicationQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "allocationMethod":
guard let value = value as? String else {
throw SchemaViolationError(type: DiscountCodeApplication.self, field: fieldName, value: fieldValue)
}
return DiscountApplicationAllocationMethod(rawValue: value) ?? .unknownValue
case "applicable":
guard let value = value as? Bool else {
throw SchemaViolationError(type: DiscountCodeApplication.self, field: fieldName, value: fieldValue)
}
return value
case "code":
guard let value = value as? String else {
throw SchemaViolationError(type: DiscountCodeApplication.self, field: fieldName, value: fieldValue)
}
return value
case "targetSelection":
guard let value = value as? String else {
throw SchemaViolationError(type: DiscountCodeApplication.self, field: fieldName, value: fieldValue)
}
return DiscountApplicationTargetSelection(rawValue: value) ?? .unknownValue
case "targetType":
guard let value = value as? String else {
throw SchemaViolationError(type: DiscountCodeApplication.self, field: fieldName, value: fieldValue)
}
return DiscountApplicationTargetType(rawValue: value) ?? .unknownValue
case "value":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: DiscountCodeApplication.self, field: fieldName, value: fieldValue)
}
return try UnknownPricingValue.create(fields: value)
default:
throw SchemaViolationError(type: DiscountCodeApplication.self, field: fieldName, value: fieldValue)
}
}
/// The method by which the discount's value is allocated to its entitled
/// items.
open var allocationMethod: Storefront.DiscountApplicationAllocationMethod {
return internalGetAllocationMethod()
}
func internalGetAllocationMethod(alias: String? = nil) -> Storefront.DiscountApplicationAllocationMethod {
return field(field: "allocationMethod", aliasSuffix: alias) as! Storefront.DiscountApplicationAllocationMethod
}
/// Specifies whether the discount code was applied successfully.
open var applicable: Bool {
return internalGetApplicable()
}
func internalGetApplicable(alias: String? = nil) -> Bool {
return field(field: "applicable", aliasSuffix: alias) as! Bool
}
/// The string identifying the discount code that was used at the time of
/// application.
open var code: String {
return internalGetCode()
}
func internalGetCode(alias: String? = nil) -> String {
return field(field: "code", aliasSuffix: alias) as! String
}
/// Which lines of targetType that the discount is allocated over.
open var targetSelection: Storefront.DiscountApplicationTargetSelection {
return internalGetTargetSelection()
}
func internalGetTargetSelection(alias: String? = nil) -> Storefront.DiscountApplicationTargetSelection {
return field(field: "targetSelection", aliasSuffix: alias) as! Storefront.DiscountApplicationTargetSelection
}
/// The type of line that the discount is applicable towards.
open var targetType: Storefront.DiscountApplicationTargetType {
return internalGetTargetType()
}
func internalGetTargetType(alias: String? = nil) -> Storefront.DiscountApplicationTargetType {
return field(field: "targetType", aliasSuffix: alias) as! Storefront.DiscountApplicationTargetType
}
/// The value of the discount application.
open var value: PricingValue {
return internalGetValue()
}
func internalGetValue(alias: String? = nil) -> PricingValue {
return field(field: "value", aliasSuffix: alias) as! PricingValue
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
return []
}
}
}
| mit | c9adecb6fcfe11778e4892f7a12e54a2 | 36.53125 | 115 | 0.742437 | 4.520703 | false | false | false | false |
NobodyNada/SwiftStack | Sources/SwiftStack/RequestsPrivileges.swift | 1 | 1998 | //
// RequestsPrivileges.swift
// SwiftStack
//
// Created by FelixSFD on 14.02.17.
//
//
import Foundation
/**
This extension contains all requests in the PRIVILEGES section of the StackExchange API Documentation.
- authors: NobodyNada, FelixSFD
*/
public extension APIClient {
// - MARK: /privileges
/**
Fetches all `Privileges`s synchronously.
- parameter parameters: The dictionary of parameters used in the request
- parameter backoffBehavior: The behavior when an `APIRequest` has a backoff
- returns: The list of sites as `APIResponse<Privilege>`
- authors: NobodyNada, FelixSFD
*/
func fetchPrivileges(
parameters: [String:String] = [:],
backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Privilege> {
return try performAPIRequest(
"privileges",
parameters: parameters,
backoffBehavior: backoffBehavior
)
}
/**
Fetches all `Privileges`s asynchronously.
- parameter parameters: The dictionary of parameters used in the request
- parameter backoffBehavior: The behavior when an `APIRequest` has a backoff
- parameter completionHandler: Passes either an `APIResponse<Privilege>?` or an `Error?`
- authors: NobodyNada, FelixSFD
*/
func fetchPrivileges(
parameters: [String: String] = [:],
backoffBehavior: BackoffBehavior = .wait,
completionHandler: @escaping (APIResponse<Privilege>?, Error?) -> ()) {
queue.async {
do {
let response: APIResponse<Privilege> = try self.fetchPrivileges(
parameters: parameters,
backoffBehavior: backoffBehavior
)
completionHandler(response, nil)
} catch {
completionHandler(nil, error)
}
}
}
}
| mit | 505f6b01d98e887032e40f7a78d48773 | 26.369863 | 103 | 0.593093 | 5.444142 | false | false | false | false |
sschiau/swift-package-manager | Tests/POSIXTests/ReaddirTests.swift | 2 | 1786 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import POSIX
extension MemoryLayout {
fileprivate static func ofInstance(_: @autoclosure () -> T) -> MemoryLayout<T>.Type {
return MemoryLayout<T>.self
}
}
class ReaddirTests: XCTestCase {
func testName() {
do {
var s = dirent()
withUnsafeMutablePointer(to: &s.d_name) { ptr in
let ptr = UnsafeMutableRawPointer(ptr).assumingMemoryBound(to: UInt8.self)
ptr[0] = UInt8(ascii: "A")
ptr[1] = UInt8(ascii: "B")
ptr[2] = 0
}
XCTAssertEqual(s.name, "AB")
}
do {
var s = dirent()
withUnsafeMutablePointer(to: &s.d_name) { ptr in
let ptr = UnsafeMutableRawPointer(ptr).assumingMemoryBound(to: UInt8.self)
ptr[0] = 0xFF
ptr[1] = 0xFF
ptr[2] = 0
}
XCTAssertEqual(s.name, nil)
}
do {
var s = dirent()
let n = MemoryLayout.ofInstance(s.d_name).size - 1
withUnsafeMutablePointer(to: &s.d_name) { ptr in
let ptr = UnsafeMutableRawPointer(ptr).assumingMemoryBound(to: UInt8.self)
for i in 0 ..< n {
ptr[i] = UInt8(ascii: "A")
}
ptr[n] = 0
}
XCTAssertEqual(s.name, String(repeating: "A", count: n))
}
}
}
| apache-2.0 | 2a33e4add82154dd01e1f369dc04bfaa | 29.793103 | 90 | 0.536954 | 4.24228 | false | true | false | false |
DianQK/Flix | Example/Providers/UniqueButtonTableViewProvider.swift | 1 | 1421 | //
// UniqueButtonTableViewProvider.swift
// Example
//
// Created by DianQK on 04/10/2017.
// Copyright © 2017 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import Flix
open class UniqueButtonTableViewProvider: SingleUITableViewCellProvider {
let textLabel = UILabel()
let activityIndicatorView = UIActivityIndicatorView()
public override init() {
super.init()
textLabel.textAlignment = .center
backgroundView = UIView()
selectedBackgroundView = UIView()
contentView.addSubview(textLabel)
textLabel.translatesAutoresizingMaskIntoConstraints = false
textLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
textLabel.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
textLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
textLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
contentView.addSubview(activityIndicatorView)
activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
activityIndicatorView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15).isActive = true
activityIndicatorView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
}
}
| mit | 15942071fd00ae8ae7725c47e8acba5e | 36.368421 | 120 | 0.742958 | 5.916667 | false | false | false | false |
ryanglobus/Augustus | Augustus/Augustus/AUDateLabel.swift | 1 | 2806 | //
// AUDateViewLabel.swift
// Augustus
//
// Created by Ryan Globus on 7/19/15.
// Copyright (c) 2015 Ryan Globus. All rights reserved.
//
import Cocoa
import AppKit
class AUDateLabel: NSView {
var date: Date
var auDelegate: AUDateLabelDelegate?
override var intrinsicContentSize: NSSize {
return CGSize(width: 0, height: 50)
}
convenience init(date: Date) {
self.init(date: date, frame: NSRect())
}
init(date: Date, frame frameRect: NSRect) {
self.date = date
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
NSGraphicsContext.current()?.saveGraphicsState()
// Drawing code here.
self.drawBorders()
self.drawDayOfMonth()
self.drawDayOfWeek()
NSGraphicsContext.current()?.restoreGraphicsState()
}
override func mouseDown(with theEvent: NSEvent) {
if theEvent.clickCount == 2 {
self.auDelegate?.requestNewEventForDateLabel?(self)
} else {
self.auDelegate?.selectDateLabel?(self)
}
}
// TODO fonts and placement are not robust
fileprivate func drawBorders() {
let path = NSBezierPath()
// border below
path.move(to: NSPoint(x: 0, y: 0))
path.line(to: NSPoint(x: self.frame.width, y: 0))
path.lineWidth = 2
path.stroke()
}
fileprivate func drawDayOfMonth() {
let dayOfMonth = (AUModel.calendar as NSCalendar).component(NSCalendar.Unit.day, from: self.date).description
let dayOfMonthAttributes = [NSFontAttributeName: NSFont.boldSystemFont(ofSize: 20)]
let dayOfMonthLabel = NSAttributedString(string: dayOfMonth, attributes: dayOfMonthAttributes)
let x = (self.frame.width - dayOfMonthLabel.size().width) / 2.0
dayOfMonthLabel.draw(at: CGPoint(x: x, y: 0))
}
fileprivate func drawDayOfWeek() {
let dayOfWeekNumber = (AUModel.calendar as NSCalendar).component(NSCalendar.Unit.weekday, from: self.date)
let dayOfWeek = AUModel.calendar.weekdaySymbols[dayOfWeekNumber - 1]
let dayOfWeekAttributes = [NSFontAttributeName: NSFont.systemFont(ofSize: 18)]
let dayOfWeekLabel = NSAttributedString(string: dayOfWeek, attributes: dayOfWeekAttributes)
let x = (self.frame.width - dayOfWeekLabel.size().width) / 2.0
dayOfWeekLabel.draw(at: CGPoint(x: x, y: 25))
}
}
@objc protocol AUDateLabelDelegate {
@objc optional func selectDateLabel(_ dateLabel: AUDateLabel)
@objc optional func requestNewEventForDateLabel(_ dateLabel: AUDateLabel)
}
| gpl-2.0 | 26940f87cbf13d07eb9abf4f99a2fe27 | 31.252874 | 117 | 0.648254 | 4.425868 | false | false | false | false |
pkx0128/UIKit | MUIPinchGestureRecognizer/MUIPinchGestureRecognizer/ViewController.swift | 1 | 1302 | //
// ViewController.swift
// MUIPinchGestureRecognizer
//
// Created by pankx on 2017/10/11.
// Copyright © 2017年 pankx. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var pinchView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
pinchView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
pinchView.center = view.center
pinchView.backgroundColor = UIColor.blue
view.addSubview(pinchView)
let pinchG = UIPinchGestureRecognizer(target: self, action: #selector(pinchEvent))
pinchView.addGestureRecognizer(pinchG)
}
@objc func pinchEvent(e: UIPinchGestureRecognizer) {
let pf = pinchView.frame
if e.state == .began {
print("pinch Began!")
}else if e.state == .changed {
if pf.width * e.scale > 100 && pf.height * e.scale < 400 {
pinchView.frame = CGRect(x: pf.origin.x, y: pf.origin.y, width: pf.width * e.scale, height: pf.height * e.scale)
}
}else if e.state == .ended {
print("Pinch End")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 0d59048db71544ac4469a921c2f75e0e | 29.209302 | 128 | 0.61047 | 4.203883 | false | false | false | false |
iwheelbuy/VK | VK/Object/VK+Object+MarketItem.swift | 1 | 4855 | import Foundation
public extension Object {
/// Объект, описывающий товар
public struct MarketItem: Decodable {
/// Статус доступности товара
public enum Availability: Decodable {
/// Товар доступен
case available
/// Товар удален
case deleted
/// Товар недоступен
case unavailable
/// Неизвестное значение
case unexpected(Int)
init(rawValue: Int) {
switch rawValue {
case 0:
self = .available
case 1:
self = .deleted
case 2:
self = .unavailable
default:
self = .unexpected(rawValue)
}
}
public var rawValue: Int {
switch self {
case .available:
return 0
case .deleted:
return 1
case .unavailable:
return 2
case .unexpected(let value):
return value
}
}
public init(from decoder: Decoder) throws {
var container = try decoder.singleValueContainer()
let rawValue: Int = try container.decode()
self = Object.MarketItem.Availability(rawValue: rawValue)
}
}
/// Категория товара
public struct Category: Decodable {
/// Секция
public struct Section: Decodable {
/// Идентификатор секции
public let id: Int?
/// Название секции
public let name: String?
}
/// Идентификатор категории
public let id: Int?
/// Название категории
public let name: String?
/// Секция
public let section: Object.MarketItem.Category.Section?
}
/// Информация об отметках «Мне нравится»
public struct Likes: Decodable {
/// Число отметок «Мне нравится»
let count: Int?
/// Есть ли отметка «Мне нравится» от текущего пользователя
let user_likes: Object.Boolean?
}
/// Объект, описывающий цену
public struct Price: Decodable {
/// Объект, описывающий информацию о валюте
public struct Currency: Decodable {
/// Идентификатор валюты
public let id: Int?
/// Буквенное обозначение валюты
public let name: String?
}
/// Цена товара в сотых долях единицы валюты
public let amount: String?
/// Объект currency
public let currency: Object.MarketItem.Price.Currency?
/// Строка с локализованной ценой и валютой
public let text: String?
}
/// Статус доступности товара
public let availability: Object.MarketItem.Availability?
/// Возможность комментировать товар для текущего пользователя
public let can_comment: Object.Boolean?
/// Возможность сделать репост товара для текущего пользователя
public let can_repost: Object.Boolean?
/// Категория товара
public let category: Object.MarketItem.Category?
/// Creation date in Unixtime
public let date: Int?
/// Текст описания товара
public let description: String?
/// Идентификатор товара
public let id: Int?
/// Информация об отметках «Мне нравится»
public let likes: Object.MarketItem.Likes?
/// Идентификатор владельца товара
public let owner_id: Int?
/// Изображения товара
public let photos: [Object.Photo]?
/// Цена
public let price: Object.MarketItem.Price?
/// URL of the item photo
public let thumb_photo: String?
/// Название товара
public let title: String?
}
}
| mit | 7686120e4d77f99f15e426db91045de9 | 34.301724 | 73 | 0.517705 | 4.723183 | false | false | false | false |
gerlandiolucena/iosvisits | iOSVisits/Pods/RealmSwift/RealmSwift/Realm.swift | 16 | 29241 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
A `Realm` instance (also referred to as "a Realm") represents a Realm database.
Realms can either be stored on disk (see `init(path:)`) or in memory (see `Configuration`).
`Realm` instances are cached internally, and constructing equivalent `Realm` objects (for example, by using the same
path or identifier) produces limited overhead.
If you specifically want to ensure a `Realm` instance is destroyed (for example, if you wish to open a Realm, check
some property, and then possibly delete the Realm file and re-open it), place the code which uses the Realm within an
`autoreleasepool {}` and ensure you have no other strong references to it.
- warning: `Realm` instances are not thread safe and cannot be shared across threads or dispatch queues. You must
construct a new instance for each thread in which a Realm will be accessed. For dispatch queues, this means
that you must construct a new instance in each block which is dispatched, as a queue is not guaranteed to
run all of its blocks on the same thread.
*/
public final class Realm {
// MARK: Properties
/// The `Schema` used by the Realm.
public var schema: Schema { return Schema(rlmRealm.schema) }
/// The `Configuration` value that was used to create the `Realm` instance.
public var configuration: Configuration { return Configuration.fromRLMRealmConfiguration(rlmRealm.configuration) }
/// Indicates if the Realm contains any objects.
public var isEmpty: Bool { return rlmRealm.isEmpty }
// MARK: Initializers
/**
Obtains an instance of the default Realm.
The default Realm is persisted as *default.realm* under the *Documents* directory of your Application on iOS, and
in your application's *Application Support* directory on OS X.
The default Realm is created using the default `Configuration`, which can be changed by setting the
`Realm.Configuration.defaultConfiguration` property to a new value.
- throws: An `NSError` if the Realm could not be initialized.
*/
public convenience init() throws {
let rlmRealm = try RLMRealm(configuration: RLMRealmConfiguration.default())
self.init(rlmRealm)
}
/**
Obtains a `Realm` instance with the given configuration.
- parameter configuration: A configuration value to use when creating the Realm.
- throws: An `NSError` if the Realm could not be initialized.
*/
public convenience init(configuration: Configuration) throws {
let rlmRealm = try RLMRealm(configuration: configuration.rlmConfiguration)
self.init(rlmRealm)
}
/**
Obtains a `Realm` instance persisted at a specified file URL.
- parameter fileURL: The local URL of the file the Realm should be saved at.
- throws: An `NSError` if the Realm could not be initialized.
*/
public convenience init(fileURL: URL) throws {
var configuration = Configuration.defaultConfiguration
configuration.fileURL = fileURL
try self.init(configuration: configuration)
}
// MARK: Transactions
/**
Performs actions contained within the given block inside a write transaction.
If the block throws an error, the transaction will be canceled and any
changes made before the error will be rolled back.
Only one write transaction can be open at a time for each Realm file. Write
transactions cannot be nested, and trying to begin a write transaction on a
Realm which is already in a write transaction will throw an exception.
Calls to `write` from `Realm` instances for the same Realm file in other
threads or other processes will block until the current write transaction
completes or is cancelled.
Before beginning the write transaction, `write` updates the `Realm`
instance to the latest Realm version, as if `refresh()` had been called,
and generates notifications if applicable. This has no effect if the Realm
was already up to date.
- parameter block: The block containing actions to perform.
- throws: An `NSError` if the transaction could not be completed successfully.
If `block` throws, the function throws the propagated `ErrorType` instead.
*/
public func write(_ block: (() throws -> Void)) throws {
beginWrite()
do {
try block()
} catch let error {
if isInWriteTransaction { cancelWrite() }
throw error
}
if isInWriteTransaction { try commitWrite() }
}
/**
Begins a write transaction on the Realm.
Only one write transaction can be open at a time for each Realm file. Write
transactions cannot be nested, and trying to begin a write transaction on a
Realm which is already in a write transaction will throw an exception.
Calls to `beginWrite` from `Realm` instances for the same Realm file in
other threads or other processes will block until the current write
transaction completes or is cancelled.
Before beginning the write transaction, `beginWrite` updates the `Realm`
instance to the latest Realm version, as if `refresh()` had been called,
and generates notifications if applicable. This has no effect if the Realm
was already up to date.
It is rarely a good idea to have write transactions span multiple cycles of
the run loop, but if you do wish to do so you will need to ensure that the
Realm participating in the write transaction is kept alive until the write
transaction is committed.
*/
public func beginWrite() {
rlmRealm.beginWriteTransaction()
}
/**
Commits all write operations in the current write transaction, and ends
the transaction.
After saving the changes and completing the write transaction, all
notification blocks registered on this specific `Realm` instance are called
synchronously. Notification blocks for `Realm` instances on other threads
and blocks registered for any Realm collection (including those on the
current thread) are scheduled to be called synchronously.
You can skip notifiying specific notification blocks about the changes made
in this write transaction by passing in their associated notification
tokens. This is primarily useful when the write transaction is saving
changes already made in the UI and you do not want to have the notification
block attempt to re-apply the same changes.
The tokens passed to this function must be for notifications for this Realm
which were added on the same thread as the write transaction is being
performed on. Notifications for different threads cannot be skipped using
this method.
- warning: This method may only be called during a write transaction.
- throws: An `NSError` if the transaction could not be written due to
running out of disk space or other i/o errors.
*/
public func commitWrite(withoutNotifying tokens: [NotificationToken] = []) throws {
try rlmRealm.commitWriteTransactionWithoutNotifying(tokens)
}
/**
Reverts all writes made in the current write transaction and ends the transaction.
This rolls back all objects in the Realm to the state they were in at the
beginning of the write transaction, and then ends the transaction.
This restores the data for deleted objects, but does not revive invalidated
object instances. Any `Object`s which were added to the Realm will be
invalidated rather than becoming unmanaged.
Given the following code:
```swift
let oldObject = objects(ObjectType).first!
let newObject = ObjectType()
realm.beginWrite()
realm.add(newObject)
realm.delete(oldObject)
realm.cancelWrite()
```
Both `oldObject` and `newObject` will return `true` for `isInvalidated`,
but re-running the query which provided `oldObject` will once again return
the valid object.
KVO observers on any objects which were modified during the transaction
will be notified about the change back to their initial values, but no
other notifcations are produced by a cancelled write transaction.
- warning: This method may only be called during a write transaction.
*/
public func cancelWrite() {
rlmRealm.cancelWriteTransaction()
}
/**
Indicates whether the Realm is currently in a write transaction.
- warning: Do not simply check this property and then start a write transaction whenever an object needs to be
created, updated, or removed. Doing so might cause a large number of write transactions to be created,
degrading performance. Instead, always prefer performing multiple updates during a single transaction.
*/
public var isInWriteTransaction: Bool {
return rlmRealm.inWriteTransaction
}
// MARK: Adding and Creating objects
/**
Adds or updates an existing object into the Realm.
Only pass `true` to `update` if the object has a primary key. If no objects exist in the Realm with the same
primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values.
When added, all child relationships referenced by this object will also be added to the Realm if they are not
already in it. If the object or any related objects are already being managed by a different Realm an error will be
thrown. Instead, use one of the `create` functions to insert a copy of a managed object into a different Realm.
The object to be added must be valid and cannot have been previously deleted from a Realm (i.e. `isInvalidated`
must be `false`).
- parameter object: The object to be added to this Realm.
- parameter update: If `true`, the Realm will try to find an existing copy of the object (with the same primary
key), and update it. Otherwise, the object will be added.
*/
public func add(_ object: Object, update: Bool = false) {
if update && object.objectSchema.primaryKeyProperty == nil {
throwRealmException("'\(object.objectSchema.className)' does not have a primary key and can not be updated")
}
RLMAddObjectToRealm(object, rlmRealm, update)
}
/**
Adds or updates all the objects in a collection into the Realm.
- see: `add(_:update:)`
- warning: This method may only be called during a write transaction.
- parameter objects: A sequence which contains objects to be added to the Realm.
- parameter update: If `true`, objects that are already in the Realm will be updated instead of added anew.
*/
public func add<S: Sequence>(_ objects: S, update: Bool = false) where S.Iterator.Element: Object {
for obj in objects {
add(obj, update: update)
}
}
/**
Creates or updates a Realm object with a given value, adding it to the Realm and returning it.
Only pass `true` to `update` if the object has a primary key. If no objects exist in
the Realm with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
The `value` argument can be a key-value coding compliant object, an array or dictionary returned from the methods
in `NSJSONSerialization`, or an `Array` containing one element for each managed property. An exception will be
thrown if any required properties are not present and those properties were not defined with default values. Do not
pass in a `LinkingObjects` instance, either by itself or as a member of a collection.
When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as
the properties defined in the model.
- warning: This method may only be called during a write transaction.
- parameter type: The type of the object to create.
- parameter value: The value used to populate the object.
- parameter update: If `true`, the Realm will try to find an existing copy of the object (with the same primary
key), and update it. Otherwise, the object will be added.
- returns: The newly created object.
*/
@discardableResult
public func create<T: Object>(_ type: T.Type, value: Any = [:], update: Bool = false) -> T {
let typeName = (type as Object.Type).className()
if update && schema[typeName]?.primaryKeyProperty == nil {
throwRealmException("'\(typeName)' does not have a primary key and can not be updated")
}
return unsafeDowncast(RLMCreateObjectInRealmWithValue(rlmRealm, typeName, value, update), to: T.self)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `create(_:value:update:)`.
Creates or updates an object with the given class name and adds it to the `Realm`, populating
the object with the given value.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or
dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing one element for each
managed property. An exception will be thrown if any required properties are not present and those properties were
not defined with default values.
When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as
the properties defined in the model.
- warning: This method can only be called during a write transaction.
- parameter className: The class name of the object to create.
- parameter value: The value used to populate the object.
- parameter update: If true will try to update existing objects with the same primary key.
- returns: The created object.
:nodoc:
*/
@discardableResult
public func dynamicCreate(_ typeName: String, value: Any = [:], update: Bool = false) -> DynamicObject {
if update && schema[typeName]?.primaryKeyProperty == nil {
throwRealmException("'\(typeName)' does not have a primary key and can not be updated")
}
return noWarnUnsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, typeName, value, update),
to: DynamicObject.self)
}
// MARK: Deleting objects
/**
Deletes an object from the Realm. Once the object is deleted it is considered invalidated.
- warning: This method may only be called during a write transaction.
- parameter object: The object to be deleted.
*/
public func delete(_ object: Object) {
RLMDeleteObjectFromRealm(object, rlmRealm)
}
/**
Deletes zero or more objects from the Realm.
Do not pass in a slice to a `Results` or any other auto-updating Realm collection
type (for example, the type returned by the Swift `suffix(_:)` standard library
method). Instead, make a copy of the objects to delete using `Array()`, and pass
that instead. Directly passing in a view into an auto-updating collection may
result in 'index out of bounds' exceptions being thrown.
- warning: This method may only be called during a write transaction.
- parameter objects: The objects to be deleted. This can be a `List<Object>`,
`Results<Object>`, or any other Swift `Sequence` whose
elements are `Object`s (subject to the caveats above).
*/
public func delete<S: Sequence>(_ objects: S) where S.Iterator.Element: Object {
for obj in objects {
delete(obj)
}
}
/**
Deletes zero or more objects from the Realm.
- warning: This method may only be called during a write transaction.
- parameter objects: A list of objects to delete.
:nodoc:
*/
public func delete<T: Object>(_ objects: List<T>) {
rlmRealm.deleteObjects(objects._rlmArray)
}
/**
Deletes zero or more objects from the Realm.
- warning: This method may only be called during a write transaction.
- parameter objects: A `Results` containing the objects to be deleted.
:nodoc:
*/
public func delete<T: Object>(_ objects: Results<T>) {
rlmRealm.deleteObjects(objects.rlmResults)
}
/**
Deletes all objects from the Realm.
- warning: This method may only be called during a write transaction.
*/
public func deleteAll() {
RLMDeleteAllObjectsFromRealm(rlmRealm)
}
// MARK: Object Retrieval
/**
Returns all objects of the given type stored in the Realm.
- parameter type: The type of the objects to be returned.
- returns: A `Results` containing the objects.
*/
public func objects<T: Object>(_ type: T.Type) -> Results<T> {
return Results<T>(RLMGetObjects(rlmRealm, (type as Object.Type).className(), nil))
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `objects(type:)`.
Returns all objects for a given class name in the Realm.
- parameter typeName: The class name of the objects to be returned.
- returns: All objects for the given class name as dynamic objects
:nodoc:
*/
public func dynamicObjects(_ typeName: String) -> Results<DynamicObject> {
return Results<DynamicObject>(RLMGetObjects(rlmRealm, typeName, nil))
}
/**
Retrieves the single instance of a given object type with the given primary key from the Realm.
This method requires that `primaryKey()` be overridden on the given object class.
- see: `Object.primaryKey()`
- parameter type: The type of the object to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `type`, or `nil` if no instance with the given primary key exists.
*/
public func object<T: Object, K>(ofType type: T.Type, forPrimaryKey key: K) -> T? {
return unsafeBitCast(RLMGetObject(rlmRealm, (type as Object.Type).className(),
dynamicBridgeCast(fromSwift: key)) as! RLMObjectBase?,
to: Optional<T>.self)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `objectForPrimaryKey(_:key:)`.
Get a dynamic object with the given class name and primary key.
Returns `nil` if no object exists with the given class name and primary key.
This method requires that `primaryKey()` be overridden on the given subclass.
- see: Object.primaryKey()
- warning: This method is useful only in specialized circumstances.
- parameter className: The class name of the object to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `DynamicObject` or `nil` if an object with the given primary key does not exist.
:nodoc:
*/
public func dynamicObject(ofType typeName: String, forPrimaryKey key: Any) -> DynamicObject? {
return unsafeBitCast(RLMGetObject(rlmRealm, typeName, key) as! RLMObjectBase?, to: Optional<DynamicObject>.self)
}
// MARK: Notifications
/**
Adds a notification handler for changes made to this Realm, and returns a notification token.
Notification handlers are called after each write transaction is committed, independent of the thread or process.
Handler blocks are called on the same thread that they were added on, and may only be added on threads which are
currently within a run loop. Unless you are specifically creating and running a run loop on a background thread,
this will normally only be the main thread.
Notifications can't be delivered as long as the run loop is blocked by other activity. When notifications can't be
delivered instantly, multiple notifications may be coalesced.
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `stop()` on the token.
- parameter block: A block which is called to process Realm notifications. It receives the following parameters:
`notification`: the incoming notification; `realm`: the Realm for which the notification
occurred.
- returns: A token which must be held for as long as you wish to continue receiving change notifications.
*/
public func addNotificationBlock(_ block: @escaping NotificationBlock) -> NotificationToken {
return rlmRealm.addNotificationBlock { rlmNotification, _ in
switch rlmNotification {
case RLMNotification.DidChange:
block(.didChange, self)
case RLMNotification.RefreshRequired:
block(.refreshRequired, self)
default:
fatalError("Unhandled notification type: \(rlmNotification)")
}
}
}
// MARK: Autorefresh and Refresh
/**
Set this property to `true` to automatically update this Realm when changes happen in other threads.
If set to `true` (the default), changes made on other threads will be reflected in this Realm on the next cycle of
the run loop after the changes are committed. If set to `false`, you must manually call `refresh()` on the Realm
to update it to get the latest data.
Note that by default, background threads do not have an active run loop and you will need to manually call
`refresh()` in order to update to the latest version, even if `autorefresh` is set to `true`.
Even with this property enabled, you can still call `refresh()` at any time to update the Realm before the
automatic refresh would occur.
Notifications are sent when a write transaction is committed whether or not automatic refreshing is enabled.
Disabling `autorefresh` on a `Realm` without any strong references to it will not have any effect, and
`autorefresh` will revert back to `true` the next time the Realm is created. This is normally irrelevant as it
means that there is nothing to refresh (as managed `Object`s, `List`s, and `Results` have strong references to the
`Realm` that manages them), but it means that setting `autorefresh = false` in
`application(_:didFinishLaunchingWithOptions:)` and only later storing Realm objects will not work.
Defaults to `true`.
*/
public var autorefresh: Bool {
get {
return rlmRealm.autorefresh
}
set {
rlmRealm.autorefresh = newValue
}
}
/**
Updates the Realm and outstanding objects managed by the Realm to point to the most recent data.
- returns: Whether there were any updates for the Realm. Note that `true` may be returned even if no data actually
changed.
*/
@discardableResult
public func refresh() -> Bool {
return rlmRealm.refresh()
}
// MARK: Invalidation
/**
Invalidates all `Object`s, `Results`, `LinkingObjects`, and `List`s managed by the Realm.
A Realm holds a read lock on the version of the data accessed by it, so
that changes made to the Realm on different threads do not modify or delete the
data seen by this Realm. Calling this method releases the read lock,
allowing the space used on disk to be reused by later write transactions rather
than growing the file. This method should be called before performing long
blocking operations on a background thread on which you previously read data
from the Realm which you no longer need.
All `Object`, `Results` and `List` instances obtained from this `Realm` instance on the current thread are
invalidated. `Object`s and `Array`s cannot be used. `Results` will become empty. The Realm itself remains valid,
and a new read transaction is implicitly begun the next time data is read from the Realm.
Calling this method multiple times in a row without reading any data from the
Realm, or before ever reading any data from the Realm, is a no-op. This method
may not be called on a read-only Realm.
*/
public func invalidate() {
rlmRealm.invalidate()
}
// MARK: Writing a Copy
/**
Writes a compacted and optionally encrypted copy of the Realm to the given local URL.
The destination file cannot already exist.
Note that if this method is called from within a write transaction, the *current* data is written, not the data
from the point when the previous write transaction was committed.
- parameter fileURL: Local URL to save the Realm to.
- parameter encryptionKey: Optional 64-byte encryption key to encrypt the new file with.
- throws: An `NSError` if the copy could not be written.
*/
public func writeCopy(toFile fileURL: URL, encryptionKey: Data? = nil) throws {
try rlmRealm.writeCopy(to: fileURL, encryptionKey: encryptionKey)
}
// MARK: Internal
internal var rlmRealm: RLMRealm
internal init(_ rlmRealm: RLMRealm) {
self.rlmRealm = rlmRealm
}
}
// MARK: Equatable
extension Realm: Equatable {
/// Returns whether two `Realm` isntances are equal.
public static func == (lhs: Realm, rhs: Realm) -> Bool {
return lhs.rlmRealm == rhs.rlmRealm
}
}
// MARK: Notifications
extension Realm {
/// A notification indicating that changes were made to a Realm.
public enum Notification: String {
/**
This notification is posted when the data in a Realm has changed.
`didChange` is posted after a Realm has been refreshed to reflect a write transaction, This can happen when an
autorefresh occurs, `refresh()` is called, after an implicit refresh from `write(_:)`/`beginWrite()`, or after
a local write transaction is committed.
*/
case didChange = "RLMRealmDidChangeNotification"
/**
This notification is posted when a write transaction has been committed to a Realm on a different thread for
the same file.
It is not posted if `autorefresh` is enabled, or if the Realm is refreshed before the notification has a chance
to run.
Realms with autorefresh disabled should normally install a handler for this notification which calls
`refresh()` after doing some work. Refreshing the Realm is optional, but not refreshing the Realm may lead to
large Realm files. This is because an extra copy of the data must be kept for the stale Realm.
*/
case refreshRequired = "RLMRealmRefreshRequiredNotification"
}
}
/// The type of a block to run for notification purposes when the data in a Realm is modified.
public typealias NotificationBlock = (_ notification: Realm.Notification, _ realm: Realm) -> Void
// MARK: Unavailable
extension Realm {
@available(*, unavailable, renamed: "isInWriteTransaction")
public var inWriteTransaction: Bool { fatalError() }
@available(*, unavailable, renamed: "object(ofType:forPrimaryKey:)")
public func objectForPrimaryKey<T: Object>(_ type: T.Type, key: AnyObject) -> T? { fatalError() }
@available(*, unavailable, renamed: "dynamicObject(ofType:forPrimaryKey:)")
public func dynamicObjectForPrimaryKey(_ className: String, key: AnyObject) -> DynamicObject? { fatalError() }
@available(*, unavailable, renamed: "writeCopy(toFile:encryptionKey:)")
public func writeCopyToURL(_ fileURL: NSURL, encryptionKey: Data? = nil) throws { fatalError() }
}
| gpl-3.0 | 403708638e385fbffaca21ec271b0372 | 42.001471 | 120 | 0.692589 | 4.983129 | false | false | false | false |
coderMONSTER/ioscelebrity | YStar/YStar/Scenes/Controller/TimeAndPlaceVC.swift | 1 | 5409 | //
// TimeAndPlaceVC.swift
// YStar
//
// Created by MONSTER on 2017/7/28.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
import SVProgressHUD
private let KoneCellID = "oneCell"
private let KtwoCellID = "twoCell"
private let KthreeCellID = "threeCell"
class TimeAndPlaceVC: BaseTableViewController,DateSelectorViewDelegate {
var placeString : String = "上海市"
var beginDateString : String = ""
var endDatrString : String = ""
// 点击时间标识
var startOrEnd : Bool = true
// MARK: - 初始化
override func viewDidLoad() {
super.viewDidLoad()
self.title = "时间地址管理"
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0)
}
// MARK: - UITableViewDataSource,UITableViewDelegate
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: KoneCellID, for: indexPath)
cell.detailTextLabel?.text = placeString
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: KtwoCellID, for: indexPath)
cell.detailTextLabel?.text = beginDateString
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: KthreeCellID, for: indexPath)
cell.detailTextLabel?.text = endDatrString
return cell
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row == 0 {
let choosePlaceVC = ChoosePlaceVC.init(style: .plain)
choosePlaceVC.placeBlock = { (placeCityStr) in
self.placeString = placeCityStr
self.tableView.reloadData()
}
self.navigationController?.pushViewController(choosePlaceVC, animated: true)
}
if indexPath.row == 1 {
let datePickerView = DateSelectorView(delegate: self)
datePickerView.datePicker.minimumDate = NSDate() as Date
startOrEnd = true
datePickerView.showPicker()
}
if indexPath.row == 2 {
let datePickerView = DateSelectorView(delegate: self)
datePickerView.datePicker.minimumDate = NSDate() as Date
startOrEnd = false
datePickerView.showPicker()
}
}
// MARK: - DateSelectorViewDelegate
func chooseDate(datePickerView: DateSelectorView, date: Date) {
if startOrEnd == true {
let dateString = date.string_from(formatter: "yyyy-MM-dd")
self.beginDateString = dateString
self.tableView.reloadData()
} else {
let dateString = date.string_from(formatter: "yyyy-MM-dd")
self.endDatrString = dateString
self.tableView.reloadData()
}
}
// MARK: - 确定修改按钮Action
@IBAction func sureToModifyAction(_ sender: UIButton) {
if self.placeString == "" {
SVProgressHUD.showErrorMessage(ErrorMessage: "约见城市不允许为空", ForDuration: 2.0, completion: nil)
return
}
if self.beginDateString == "" {
SVProgressHUD.showErrorMessage(ErrorMessage: "约见起始日期不允许为空", ForDuration: 2.0, completion: nil)
return
}
if self.endDatrString == "" {
SVProgressHUD.showErrorMessage(ErrorMessage: "约见结束日期不允许为空", ForDuration: 2.0, completion: nil)
return
}
// 比较 约见起始日期 - 约见结束日期
let beginDate = Date.yt_convertDateStrToDate(self.beginDateString, format: "yyyy-MM-dd")
let endDate = Date.yt_convertDateStrToDate(self.endDatrString, format: "yyyy-MM-dd")
let result:ComparisonResult = beginDate.compare(endDate)
if result == ComparisonResult.orderedDescending {
SVProgressHUD.showErrorMessage(ErrorMessage: "约见结束日期不允许小于约见开始日期", ForDuration: 2.0, completion: nil)
return
}
let model = placeAndDateRequestModel()
model.meet_city = self.placeString
model.startdate = self.beginDateString
model.enddate = self.endDatrString
AppAPIHelper.commen().requestPlaceAndDate(model: model, complete: { (response) -> ()? in
if let objects = response as? ResultModel {
if objects.result == 1 {
SVProgressHUD.showSuccessMessage(SuccessMessage: "修改成功", ForDuration: 2.0, completion: {
self.navigationController?.popViewController(animated: true)
})
}
}
return nil
}, error: errorBlockFunc())
}
}
| mit | b47a533b250f596e5b9aa2d6613d5afe | 34.073826 | 112 | 0.60486 | 5.005747 | false | true | false | false |
fr500/RetroArch | pkg/apple/OnScreenKeyboard/EmulatorKeyboardViewModel.swift | 6 | 1957 | //
// EmulatorKeyboardViewModel.swift
// RetroArchiOS
//
// Created by Yoshi Sugawara on 3/3/22.
// Copyright © 2022 RetroArch. All rights reserved.
//
struct KeyPosition {
let row: Int
let column: Int
}
@objc class EmulatorKeyboardViewModel: NSObject, KeyRowsDataSource {
var keys = [[KeyCoded]]()
var alternateKeys: [[KeyCoded]]?
var modifiers: [Int16: KeyCoded]?
var isDraggable = true
@objc weak var delegate: EmulatorKeyboardKeyPressedDelegate?
@objc weak var modifierDelegate: EmulatorKeyboardModifierPressedDelegate?
init(keys: [[KeyCoded]], alternateKeys: [[KeyCoded]]? = nil) {
self.keys = keys
self.alternateKeys = alternateKeys
}
func createView() -> EmulatorKeyboardView {
let view = EmulatorKeyboardView()
view.viewModel = self
return view
}
func keyForPositionAt(_ position: KeyPosition) -> KeyCoded? {
guard position.row < keys.count else {
return nil
}
let row = keys[position.row]
guard position.column < row.count else {
return nil
}
return row[position.column]
}
func modifierKeyToggleStateForKey(_ key: KeyCoded) -> Bool {
return key.isModifier && (modifierDelegate?.isModifierEnabled(key: key) ?? false)
}
func keyPressed(_ key: KeyCoded) {
if key.isModifier {
let isPressed = modifierDelegate?.isModifierEnabled(key: key) ?? false
modifierDelegate?.modifierPressedWithKey(key, enable: !isPressed)
return
}
delegate?.keyDown(key)
}
func keyReleased(_ key: KeyCoded) {
if key.isModifier {
return
}
delegate?.keyUp(key)
}
// KeyCoded can support a shifted key label
// view can update with shifted key labels?
// cluster can support alternate keys and view can swap them out?
}
| gpl-3.0 | 41190a7fb456fd64a5961d0b2d1c5540 | 27.347826 | 89 | 0.620143 | 4.559441 | false | false | false | false |
TeachersPayTeachers/PerspectivePhotoBrowser | Pod/Classes/Extensions/UICollectionView.swift | 1 | 892 |
extension UICollectionView {
func widthForCell(withNumberOfColumns numberOfColumns: Int) -> CGFloat {
let collectionViewFlowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
let leftInset = collectionViewFlowLayout.sectionInset.left
let rightInset = collectionViewFlowLayout.sectionInset.right
let lineSpacing = collectionViewFlowLayout.minimumLineSpacing
let contentWidth = (bounds.width - leftInset - rightInset - lineSpacing * CGFloat(numberOfColumns - 1)) / CGFloat(numberOfColumns)
return contentWidth
}
func minimumHeight() -> CGFloat {
let collectionViewFlowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
let totalHeight = bounds.height - collectionViewFlowLayout.sectionInset.top - collectionViewFlowLayout.sectionInset.bottom - self.contentInset.bottom - self.contentInset.top
return totalHeight
}
}
| mit | 6ed0d1766d511cf309a9d5a0f8d7c7fb | 45.947368 | 177 | 0.799327 | 6.371429 | false | false | false | false |
silt-lang/silt | Sources/Mantle/Invert.swift | 1 | 8024 | /// Invert.swift
///
/// Copyright 2017-2018, The Silt Language Project.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
import Lithosphere
import Moho
import Basic
extension TypeChecker {
/// An inversion is a substitution mapping the free variables in the spine of
/// an applied metavariable to TT terms.
///
/// An inversion may fail to create a non-trivial substitution map. Thus,
/// we also tag the inversion with the arity of the type so we don't lie
/// to the signature while solving.
struct Inversion: CustomStringConvertible {
let substitution: [(Var, Term<TT>)]
let arity: Int
var description: String {
let invBody = self.substitution.map({ (variable, term) in
return "\(variable) |-> \(term)"
}).joined(separator: ", ")
return "Inversion[\(invBody)]"
}
}
/// Attempts to generate an inversion from a sequence of eliminators.
///
/// Given a metavariable `($0: T)` with spine `[e1, e2, ..., en]` and a
/// target term `t`, inversion attempts to find a value for `$0` that solves
/// the equation `$0[e1, e2, ..., en] ≡ t`.
func invert(_ elims: [Elim<Term<TT>>]) -> Validation<Set<Meta>, Inversion> {
guard let args = elims.mapM({ $0.applyTerm }) else {
return .failure([])
}
let mvArgs = args.mapM(self.checkSpineArgument)
switch mvArgs {
case .failure(.fail(_)):
return .failure([])
case let .failure(.collect(mvs)):
return .failure(mvs)
case let .success(mvArgs):
guard let inv = self.tryGenerateInversion(mvArgs) else {
return .failure([])
}
return .success(inv)
}
}
/// Checks that the pattern condition holds before generating an inversion.
///
/// The list of variables must be linear.
func tryGenerateInversion(_ vars: [Var]) -> Inversion? {
guard vars.count == Set(vars).count else {
return nil
}
guard !vars.isEmpty else {
return Inversion(substitution: [], arity: vars.count)
}
let zips = zip((0..<vars.count).reversed(), vars)
let subs = zips.map({ (idx, v) -> (Var, Term<TT>) in
return (v, TT.apply(.variable(Var(wildcardName, UInt(idx))), []))
})
return Inversion(substitution: subs, arity: subs.count)
}
typealias SpineCheck = Validation<Collect<(), Set<Meta>>, Var>
func checkSpineArgument(_ arg: Term<TT>) -> SpineCheck {
switch self.toWeakHeadNormalForm(arg) {
case let .notBlocked(t):
switch self.toWeakHeadNormalForm(self.etaContract(t)).ignoreBlocking {
case let .apply(.variable(v), vArgs):
guard vArgs.mapM({ $0.projectTerm }) != nil else {
return .failure(.fail(()))
}
return .success(v)
case let .constructor(dataCon, dataArgs):
print(dataCon, dataArgs)
fatalError("Support inversion of constructor spines")
default:
return .failure(.fail(()))
}
case let .onHead(mv, _):
return .failure(.collect([mv]))
case let .onMetas(mvs, _, _):
return .failure(.collect(mvs))
}
}
}
extension TypeChecker where PhaseState == SolvePhaseState {
// typealias InversionResult<T> = Validation<Collect<Var, Set<Meta>>, T>
private func isIdentity(_ ts: [(Var, Term<TT>)]) -> Bool {
for (v, u) in ts {
switch self.toWeakHeadNormalForm(u).ignoreBlocking {
case let .apply(.variable(v2), xs) where xs.isEmpty:
if v == v2 {
continue
}
return false
default:
return false
}
}
return true
}
// Takes a meta inversion and applies it to a term. If substitution encounters
// a free variable, this function will fail and return that variable. If
// inversion fails because of unsolved metas, the substitution will
// also fail and return the set of blocking metas.
func applyInversion(
_ inversion: Inversion, to term: Term<TT>, in ctx: Context
) -> Validation<Collect<Var, Set<Meta>>, Meta.Binding> {
guard isIdentity(inversion.substitution) else {
return self.applyInversionSubstitution(inversion.substitution, term).map {
return Meta.Binding(arity: inversion.arity, body: $0)
}
}
// Optimization: The identity substitution requires no work.
guard ctx.count != inversion.substitution.count else {
return .success(Meta.Binding(arity: inversion.arity, body: term))
}
let fvs = freeVars(term)
let invVars = inversion.substitution.map { $0.0 }
guard fvs.all.isSubset(of: invVars) else {
return self.applyInversionSubstitution(inversion.substitution, term).map {
return Meta.Binding(arity: inversion.arity, body: $0)
}
}
return .success(Meta.Binding(arity: inversion.arity, body: term))
}
private func applyInversionSubstitution(
_ subst: [(Var, Term<TT>)], _ term: Term<TT>
) -> Validation<Collect<Var, Set<Meta>>, Term<TT>> {
func invert(_ str: UInt, _ v0: Var) -> Either<Var, Term<TT>> {
guard let v = v0.strengthen(0, by: str) else {
return .right(TT.apply(.variable(v0), []))
}
guard let (_, substVar) = subst.first(where: { $0.0 == v }) else {
return .left(v)
}
return .right(substVar.forceApplySubstitution(.weaken(Int(str)),
self.eliminate))
}
func applyInversion(
after idx: UInt, _ t: Term<TT>
) -> Validation<Collect<Var, Set<Meta>>, Term<TT>> {
switch self.toWeakHeadNormalForm(t).ignoreBlocking {
case .refl:
return .success(.refl)
case .type:
return .success(.type)
case let .lambda(body):
switch applyInversion(after: idx + 1, body) {
case let .failure(f):
return .failure(f)
case let .success(bdy):
return .success(TT.lambda(bdy))
}
case let .pi(domain, codomain):
let invDomain = applyInversion(after: idx, domain)
let invCodomain = applyInversion(after: idx + 1, codomain)
switch invDomain.merge2(invCodomain) {
case let .success((dom, cod)):
return .success(TT.pi(dom, cod))
case let .failure(e):
return .failure(e)
}
case let .equal(type, lhs, rhs):
let invType = applyInversion(after: idx, type)
let invLHS = applyInversion(after: idx, lhs)
let invRHS = applyInversion(after: idx, rhs)
switch invType.merge2(invLHS).merge2(invRHS) {
case let .success(((type2, x2), y2)):
return .success(TT.equal(type2, x2, y2))
case let .failure(e):
return .failure(e)
}
case let .constructor(dataCon, args):
switch args.mapM({ arg in applyInversion(after: idx, arg) }) {
case let .success(args2):
return .success(TT.constructor(dataCon, args2))
case let .failure(e):
return .failure(e)
}
case let .apply(h, elims):
typealias InvElim = Validation<Collect<Var, Set<Meta>>, Elim<TT>>
let invElims = elims.mapM({ (e) -> InvElim in
switch e {
case let .apply(t2):
return applyInversion(after: idx, t2).map(Elim<TT>.apply)
case .project(_):
return .success(e)
}
})
switch h {
case let .meta(mv):
switch invElims {
case let .failure(.collect(mvs)):
return .failure(.collect(mvs.union([mv])))
case .failure(.fail(_)):
return .failure(.collect(Set([mv])))
default:
return invElims.map { TT.apply(h, $0) }
}
case .definition(_):
return invElims.map { TT.apply(h, $0) }
case let .variable(v):
switch invert(idx, v) {
case let .right(inv):
return invElims.map { self.eliminate(inv, $0) }
case let .left(e):
return .failure(.fail(e))
}
}
}
}
return applyInversion(after: 0, term)
}
}
| mit | 3f283b37e35f98941160a335d3694ae7 | 33.727273 | 80 | 0.598978 | 3.875362 | false | false | false | false |
stephencelis/SQLite.swift | Tests/SQLiteTests/Typed/QueryIntegrationTests.swift | 1 | 11138 | import XCTest
#if SQLITE_SWIFT_STANDALONE
import sqlite3
#elseif SQLITE_SWIFT_SQLCIPHER
import SQLCipher
#elseif os(Linux)
import CSQLite
#else
import SQLite3
#endif
@testable import SQLite
class QueryIntegrationTests: SQLiteTestCase {
let id = Expression<Int64>("id")
let email = Expression<String>("email")
let age = Expression<Int>("age")
override func setUpWithError() throws {
try super.setUpWithError()
try createUsersTable()
}
// MARK: -
func test_select() throws {
let managerId = Expression<Int64>("manager_id")
let managers = users.alias("managers")
let alice = try db.run(users.insert(email <- "[email protected]"))
_ = try db.run(users.insert(email <- "[email protected]", managerId <- alice))
for user in try db.prepare(users.join(managers, on: managers[id] == users[managerId])) {
_ = user[users[managerId]]
}
}
func test_prepareRowIterator() throws {
let names = ["a", "b", "c"]
try insertUsers(names)
let emailColumn = Expression<String>("email")
let emails = try db.prepareRowIterator(users).map { $0[emailColumn] }
XCTAssertEqual(names.map({ "\($0)@example.com" }), emails.sorted())
}
func test_ambiguousMap() throws {
let names = ["a", "b", "c"]
try insertUsers(names)
let emails = try db.prepare("select email from users", []).map { $0[0] as! String }
XCTAssertEqual(names.map({ "\($0)@example.com" }), emails.sorted())
}
func test_select_optional() throws {
let managerId = Expression<Int64?>("manager_id")
let managers = users.alias("managers")
let alice = try db.run(users.insert(email <- "[email protected]"))
_ = try db.run(users.insert(email <- "[email protected]", managerId <- alice))
for user in try db.prepare(users.join(managers, on: managers[id] == users[managerId])) {
_ = user[users[managerId]]
}
}
func test_select_codable() throws {
let table = Table("codable")
try db.run(table.create { builder in
builder.column(Expression<Int>("int"))
builder.column(Expression<String>("string"))
builder.column(Expression<Bool>("bool"))
builder.column(Expression<Double>("float"))
builder.column(Expression<Double>("double"))
builder.column(Expression<Date>("date"))
builder.column(Expression<UUID>("uuid"))
builder.column(Expression<String?>("optional"))
builder.column(Expression<Data>("sub"))
})
let value1 = TestCodable(int: 1, string: "2", bool: true, float: 3, double: 4,
date: Date(timeIntervalSince1970: 0), uuid: testUUIDValue, optional: nil, sub: nil)
let value = TestCodable(int: 5, string: "6", bool: true, float: 7, double: 8,
date: Date(timeIntervalSince1970: 5000), uuid: testUUIDValue, optional: "optional", sub: value1)
try db.run(table.insert(value))
let rows = try db.prepare(table)
let values: [TestCodable] = try rows.map({ try $0.decode() })
XCTAssertEqual(values.count, 1)
XCTAssertEqual(values[0].int, 5)
XCTAssertEqual(values[0].string, "6")
XCTAssertEqual(values[0].bool, true)
XCTAssertEqual(values[0].float, 7)
XCTAssertEqual(values[0].double, 8)
XCTAssertEqual(values[0].date, Date(timeIntervalSince1970: 5000))
XCTAssertEqual(values[0].uuid, testUUIDValue)
XCTAssertEqual(values[0].optional, "optional")
XCTAssertEqual(values[0].sub?.int, 1)
XCTAssertEqual(values[0].sub?.string, "2")
XCTAssertEqual(values[0].sub?.bool, true)
XCTAssertEqual(values[0].sub?.float, 3)
XCTAssertEqual(values[0].sub?.double, 4)
XCTAssertEqual(values[0].sub?.date, Date(timeIntervalSince1970: 0))
XCTAssertNil(values[0].sub?.optional)
XCTAssertNil(values[0].sub?.sub)
}
func test_scalar() throws {
XCTAssertEqual(0, try db.scalar(users.count))
XCTAssertEqual(false, try db.scalar(users.exists))
try insertUsers("alice")
XCTAssertEqual(1, try db.scalar(users.select(id.average)))
}
func test_pluck() throws {
let rowid = try db.run(users.insert(email <- "[email protected]"))
XCTAssertEqual(rowid, try db.pluck(users)![id])
}
func test_insert() throws {
let id = try db.run(users.insert(email <- "[email protected]"))
XCTAssertEqual(1, id)
}
func test_insert_many() throws {
let id = try db.run(users.insertMany([[email <- "[email protected]"], [email <- "[email protected]"]]))
XCTAssertEqual(2, id)
}
func test_insert_many_encodables() throws {
let table = Table("codable")
try db.run(table.create { builder in
builder.column(Expression<Int?>("int"))
builder.column(Expression<String?>("string"))
builder.column(Expression<Bool?>("bool"))
builder.column(Expression<Double?>("float"))
builder.column(Expression<Double?>("double"))
builder.column(Expression<Date?>("date"))
builder.column(Expression<UUID?>("uuid"))
})
let value1 = TestOptionalCodable(int: 5, string: "6", bool: true, float: 7, double: 8,
date: Date(timeIntervalSince1970: 5000), uuid: testUUIDValue)
let valueWithNils = TestOptionalCodable(int: nil, string: nil, bool: nil, float: nil, double: nil, date: nil, uuid: nil)
try db.run(table.insertMany([value1, valueWithNils]))
let rows = try db.prepare(table)
let values: [TestOptionalCodable] = try rows.map({ try $0.decode() })
XCTAssertEqual(values.count, 2)
}
func test_upsert() throws {
try XCTSkipUnless(db.satisfiesMinimumVersion(minor: 24))
let fetchAge = { () throws -> Int? in
try self.db.pluck(self.users.filter(self.email == "[email protected]")).flatMap { $0[self.age] }
}
let id = try db.run(users.upsert(email <- "[email protected]", age <- 30, onConflictOf: email))
XCTAssertEqual(1, id)
XCTAssertEqual(30, try fetchAge())
let nextId = try db.run(users.upsert(email <- "[email protected]", age <- 42, onConflictOf: email))
XCTAssertEqual(1, nextId)
XCTAssertEqual(42, try fetchAge())
}
func test_update() throws {
let changes = try db.run(users.update(email <- "[email protected]"))
XCTAssertEqual(0, changes)
}
func test_delete() throws {
let changes = try db.run(users.delete())
XCTAssertEqual(0, changes)
}
func test_union() throws {
let expectedIDs = [
try db.run(users.insert(email <- "[email protected]")),
try db.run(users.insert(email <- "[email protected]"))
]
let query1 = users.filter(email == "[email protected]")
let query2 = users.filter(email == "[email protected]")
let actualIDs = try db.prepare(query1.union(query2)).map { $0[id] }
XCTAssertEqual(expectedIDs, actualIDs)
let query3 = users.select(users[*], Expression<Int>(literal: "1 AS weight")).filter(email == "[email protected]")
let query4 = users.select(users[*], Expression<Int>(literal: "2 AS weight")).filter(email == "[email protected]")
let sql = query3.union(query4).order(Expression<Int>(literal: "weight")).asSQL()
XCTAssertEqual(sql,
"""
SELECT "users".*, 1 AS weight FROM "users" WHERE ("email" = '[email protected]') UNION \
SELECT "users".*, 2 AS weight FROM "users" WHERE ("email" = '[email protected]') ORDER BY weight
""")
let orderedIDs = try db.prepare(query3.union(query4).order(Expression<Int>(literal: "weight"), email)).map { $0[id] }
XCTAssertEqual(Array(expectedIDs.reversed()), orderedIDs)
}
func test_no_such_column() throws {
let doesNotExist = Expression<String>("doesNotExist")
try insertUser("alice")
let row = try db.pluck(users.filter(email == "[email protected]"))!
XCTAssertThrowsError(try row.get(doesNotExist)) { error in
if case QueryError.noSuchColumn(let name, _) = error {
XCTAssertEqual("\"doesNotExist\"", name)
} else {
XCTFail("unexpected error: \(error)")
}
}
}
func test_catchConstraintError() throws {
try db.run(users.insert(email <- "[email protected]"))
do {
try db.run(users.insert(email <- "[email protected]"))
XCTFail("expected error")
} catch let Result.error(_, code, _) where code == SQLITE_CONSTRAINT {
// expected
} catch let error {
XCTFail("unexpected error: \(error)")
}
}
// https://github.com/stephencelis/SQLite.swift/issues/285
func test_order_by_random() throws {
try insertUsers(["a", "b", "c'"])
let result = Array(try db.prepare(users.select(email).order(Expression<Int>.random()).limit(1)))
XCTAssertEqual(1, result.count)
}
func test_with_recursive() throws {
let nodes = Table("nodes")
let id = Expression<Int64>("id")
let parent = Expression<Int64?>("parent")
let value = Expression<Int64>("value")
try db.run(nodes.create { builder in
builder.column(id)
builder.column(parent)
builder.column(value)
})
try db.run(nodes.insertMany([
[id <- 0, parent <- nil, value <- 2],
[id <- 1, parent <- 0, value <- 4],
[id <- 2, parent <- 0, value <- 9],
[id <- 3, parent <- 2, value <- 8],
[id <- 4, parent <- 2, value <- 7],
[id <- 5, parent <- 4, value <- 3]
]))
// Compute the sum of the values of node 5 and its ancestors
let ancestors = Table("ancestors")
let sum = try db.scalar(
ancestors
.select(value.sum)
.with(ancestors,
columns: [id, parent, value],
recursive: true,
as: nodes
.where(id == 5)
.union(all: true,
nodes.join(ancestors, on: nodes[id] == ancestors[parent])
.select(nodes[id], nodes[parent], nodes[value])
)
)
)
XCTAssertEqual(21, sum)
}
}
extension Connection {
func satisfiesMinimumVersion(minor: Int, patch: Int = 0) -> Bool {
guard let version = try? scalar("SELECT sqlite_version()") as? String else { return false }
let components = version.split(separator: ".", maxSplits: 3).compactMap { Int($0) }
guard components.count == 3 else { return false }
return components[1] >= minor && components[2] >= patch
}
}
| mit | d7c32253bab702a20ac9fbf5251372fc | 37.539792 | 128 | 0.581343 | 4.079853 | false | true | false | false |
jjatie/Charts | ChartsDemo-iOS/Swift/Demos/AnotherBarChartViewController.swift | 1 | 2848 | //
// AnotherBarChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
#if canImport(UIKit)
import UIKit
#endif
import Charts
class AnotherBarChartViewController: DemoBaseViewController {
@IBOutlet var chartView: BarChartView!
@IBOutlet var sliderX: UISlider!
@IBOutlet var sliderY: UISlider!
@IBOutlet var sliderTextX: UITextField!
@IBOutlet var sliderTextY: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "Another Bar Chart"
options = [.toggleValues,
.toggleHighlight,
.animateX,
.animateY,
.animateXY,
.saveToGallery,
.togglePinchZoom,
.toggleData,
.toggleBarBorders]
chartView.delegate = self
chartView.chartDescription.isEnabled = false
chartView.maxVisibleCount = 60
chartView.isPinchZoomEnabled = false
chartView.isDrawBarShadowEnabled = false
let xAxis = chartView.xAxis
xAxis.labelPosition = .bottom
chartView.legend.isEnabled = false
sliderX.value = 10
sliderY.value = 100
slidersValueChanged(nil)
}
override func updateChartData() {
if shouldHideData {
chartView.data = nil
return
}
setDataCount(Int(sliderX.value) + 1, range: Double(sliderY.value))
}
func setDataCount(_ count: Int, range: Double) {
let yVals = (0 ..< count).map { (i) -> BarChartDataEntry in
let mult = range + 1
let val = Double(arc4random_uniform(UInt32(mult))) + mult / 3
return BarChartDataEntry(x: Double(i), y: val)
}
var set1: BarChartDataSet!
if let set = chartView.data?.first as? BarChartDataSet {
set1 = set
set1?.replaceEntries(yVals)
chartView.data?.notifyDataChanged()
chartView.notifyDataSetChanged()
} else {
set1 = BarChartDataSet(entries: yVals, label: "Data Set")
set1.colors = ChartColorTemplates.vordiplom
set1.isDrawValuesEnabled = false
let data = BarChartData(dataSet: set1)
chartView.data = data
chartView.fitBars = true
}
chartView.setNeedsDisplay()
}
override func optionTapped(_ option: Option) {
super.handleOption(option, forChartView: chartView)
}
// MARK: - Actions
@IBAction func slidersValueChanged(_: Any?) {
sliderTextX.text = "\(Int(sliderX.value))"
sliderTextY.text = "\(Int(sliderY.value))"
updateChartData()
}
}
| apache-2.0 | 496a24b026d37f8ad89ecbc534f2948f | 27.188119 | 74 | 0.593607 | 4.977273 | false | false | false | false |
strangeliu/firefox-ios | Client/Frontend/Browser/TabTrayController.swift | 2 | 31298 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import SnapKit
struct TabTrayControllerUX {
static let CornerRadius = CGFloat(4.0)
static let BackgroundColor = UIConstants.AppBackgroundColor
static let CellBackgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1)
static let TextBoxHeight = CGFloat(32.0)
static let FaviconSize = CGFloat(18.0)
static let Margin = CGFloat(15)
static let ToolbarBarTintColor = UIConstants.AppBackgroundColor
static let ToolbarButtonOffset = CGFloat(10.0)
static let TabTitleTextFont = UIConstants.DefaultSmallFontBold
static let CloseButtonSize = CGFloat(18.0)
static let CloseButtonMargin = CGFloat(6.0)
static let CloseButtonEdgeInset = CGFloat(10)
static let NumberOfColumnsThin = 1
static let NumberOfColumnsWide = 3
static let CompactNumberOfColumnsThin = 2
// Moved from UIConstants temporarily until animation code is merged
static var StatusBarHeight: CGFloat {
if UIScreen.mainScreen().traitCollection.verticalSizeClass == .Compact {
return 0
}
return 20
}
}
struct LightTabCellUX {
static let TabTitleTextColor = UIColor.blackColor()
}
struct DarkTabCellUX {
static let TabTitleTextColor = UIColor.whiteColor()
}
protocol TabCellDelegate: class {
func tabCellDidClose(cell: TabCell)
}
class TabCell: UICollectionViewCell {
enum Style {
case Light
case Dark
}
static let Identifier = "TabCellIdentifier"
var style: Style = .Light {
didSet {
applyStyle(style)
}
}
let backgroundHolder = UIView()
let background = UIImageViewAligned()
let titleText: UILabel
let innerStroke: InnerStrokedView
let favicon: UIImageView = UIImageView()
let closeButton: UIButton
var title: UIVisualEffectView!
var animator: SwipeAnimator!
weak var delegate: TabCellDelegate?
// Changes depending on whether we're full-screen or not.
var margin = CGFloat(0)
override init(frame: CGRect) {
self.backgroundHolder.backgroundColor = UIColor.whiteColor()
self.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
self.backgroundHolder.clipsToBounds = true
self.backgroundHolder.backgroundColor = TabTrayControllerUX.CellBackgroundColor
self.background.contentMode = UIViewContentMode.ScaleAspectFill
self.background.clipsToBounds = true
self.background.userInteractionEnabled = false
self.background.alignLeft = true
self.background.alignTop = true
self.favicon.backgroundColor = UIColor.clearColor()
self.favicon.layer.cornerRadius = 2.0
self.favicon.layer.masksToBounds = true
self.titleText = UILabel()
self.titleText.textAlignment = NSTextAlignment.Left
self.titleText.userInteractionEnabled = false
self.titleText.numberOfLines = 1
self.titleText.font = TabTrayControllerUX.TabTitleTextFont
self.closeButton = UIButton()
self.closeButton.setImage(UIImage(named: "stop"), forState: UIControlState.Normal)
self.closeButton.imageEdgeInsets = UIEdgeInsetsMake(TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset)
self.innerStroke = InnerStrokedView(frame: self.backgroundHolder.frame)
self.innerStroke.layer.backgroundColor = UIColor.clearColor().CGColor
super.init(frame: frame)
self.opaque = true
self.animator = SwipeAnimator(animatingView: self.backgroundHolder, container: self)
self.closeButton.addTarget(self.animator, action: "SELcloseWithoutGesture", forControlEvents: UIControlEvents.TouchUpInside)
contentView.addSubview(backgroundHolder)
backgroundHolder.addSubview(self.background)
backgroundHolder.addSubview(innerStroke)
// Default style is light
applyStyle(style)
self.accessibilityCustomActions = [
UIAccessibilityCustomAction(name: NSLocalizedString("Close", comment: "Accessibility label for action denoting closing a tab in tab list (tray)"), target: self.animator, selector: "SELcloseWithoutGesture")
]
}
private func applyStyle(style: Style) {
self.title?.removeFromSuperview()
let title: UIVisualEffectView
switch style {
case .Light:
title = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight))
self.titleText.textColor = LightTabCellUX.TabTitleTextColor
case .Dark:
title = UIVisualEffectView(effect: UIBlurEffect(style: .Dark))
self.titleText.textColor = DarkTabCellUX.TabTitleTextColor
}
titleText.backgroundColor = UIColor.clearColor()
title.layer.shadowColor = UIColor.blackColor().CGColor
title.layer.shadowOpacity = 0.2
title.layer.shadowOffset = CGSize(width: 0, height: 0.5)
title.layer.shadowRadius = 0
title.addSubview(self.closeButton)
title.addSubview(self.titleText)
title.addSubview(self.favicon)
backgroundHolder.addSubview(title)
self.title = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let w = frame.width
let h = frame.height
backgroundHolder.frame = CGRect(x: margin,
y: margin,
width: w,
height: h)
background.frame = CGRect(origin: CGPointMake(0, 0), size: backgroundHolder.frame.size)
title.frame = CGRect(x: 0,
y: 0,
width: backgroundHolder.frame.width,
height: TabTrayControllerUX.TextBoxHeight)
favicon.frame = CGRect(x: 6,
y: (TabTrayControllerUX.TextBoxHeight - TabTrayControllerUX.FaviconSize)/2,
width: TabTrayControllerUX.FaviconSize,
height: TabTrayControllerUX.FaviconSize)
let titleTextLeft = favicon.frame.origin.x + favicon.frame.width + 6
titleText.frame = CGRect(x: titleTextLeft,
y: 0,
width: title.frame.width - titleTextLeft - margin - TabTrayControllerUX.CloseButtonSize - TabTrayControllerUX.CloseButtonMargin * 2,
height: title.frame.height)
innerStroke.frame = background.frame
closeButton.snp_makeConstraints { make in
make.size.equalTo(title.snp_height)
make.trailing.centerY.equalTo(title)
}
let top = (TabTrayControllerUX.TextBoxHeight - titleText.bounds.height) / 2.0
titleText.frame.origin = CGPoint(x: titleText.frame.origin.x, y: max(0, top))
}
override func prepareForReuse() {
// Reset any close animations.
backgroundHolder.transform = CGAffineTransformIdentity
backgroundHolder.alpha = 1
}
override func accessibilityScroll(direction: UIAccessibilityScrollDirection) -> Bool {
var right: Bool
switch direction {
case .Left:
right = false
case .Right:
right = true
default:
return false
}
animator.close(right: right)
return true
}
}
@available(iOS 9, *)
struct PrivateModeStrings {
static let toggleAccessibilityLabel = NSLocalizedString("Private Mode", tableName: "PrivateBrowsing", comment: "Accessibility label for toggling on/off private mode")
static let toggleAccessibilityHint = NSLocalizedString("Turns private mode on or off", tableName: "PrivateBrowsing", comment: "Accessiblity hint for toggling on/off private mode")
static let toggleAccessibilityValueOn = NSLocalizedString("On", tableName: "PrivateBrowsing", comment: "Toggled ON accessibility value")
static let toggleAccessibilityValueOff = NSLocalizedString("Off", tableName: "PrivateBrowsing", comment: "Toggled OFF accessibility value")
}
class TabTrayController: UIViewController {
let tabManager: TabManager
let profile: Profile
var collectionView: UICollectionView!
var navBar: UIView!
var addTabButton: UIButton!
var settingsButton: UIButton!
var collectionViewTransitionSnapshot: UIView?
private var privateMode: Bool = false {
didSet {
if #available(iOS 9, *) {
togglePrivateMode.selected = privateMode
togglePrivateMode.accessibilityValue = privateMode ? PrivateModeStrings.toggleAccessibilityValueOn : PrivateModeStrings.toggleAccessibilityValueOff
emptyPrivateTabsView.hidden = !(privateMode && tabManager.privateTabs.count == 0)
tabDataSource.tabs = tabsToDisplay
collectionView.reloadData()
}
}
}
private var tabsToDisplay: [Browser] {
return self.privateMode ? tabManager.privateTabs : tabManager.normalTabs
}
@available(iOS 9, *)
lazy var togglePrivateMode: UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "smallPrivateMask"), forState: UIControlState.Normal)
button.setImage(UIImage(named: "smallPrivateMaskSelected"), forState: UIControlState.Selected)
button.addTarget(self, action: "SELdidTogglePrivateMode", forControlEvents: .TouchUpInside)
button.accessibilityLabel = PrivateModeStrings.toggleAccessibilityLabel
button.accessibilityHint = PrivateModeStrings.toggleAccessibilityHint
button.accessibilityValue = self.privateMode ? PrivateModeStrings.toggleAccessibilityValueOn : PrivateModeStrings.toggleAccessibilityValueOff
return button
}()
@available(iOS 9, *)
private lazy var emptyPrivateTabsView: EmptyPrivateTabsView = {
return EmptyPrivateTabsView()
}()
private lazy var tabDataSource: TabManagerDataSource = {
return TabManagerDataSource(tabs: self.tabsToDisplay, cellDelegate: self)
}()
private lazy var tabLayoutDelegate: TabLayoutDelegate = {
let delegate = TabLayoutDelegate(profile: self.profile, traitCollection: self.traitCollection)
delegate.tabSelectionDelegate = self
return delegate
}()
private var removedTabIndexPath: NSIndexPath?
init(tabManager: TabManager, profile: Profile) {
self.tabManager = tabManager
self.profile = profile
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View Controller Callbacks
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.")
tabManager.addDelegate(self)
navBar = UIView()
navBar.backgroundColor = TabTrayControllerUX.BackgroundColor
addTabButton = UIButton()
addTabButton.setImage(UIImage(named: "add"), forState: .Normal)
addTabButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: .TouchUpInside)
addTabButton.accessibilityLabel = NSLocalizedString("Add Tab", comment: "Accessibility label for the Add Tab button in the Tab Tray.")
settingsButton = UIButton()
settingsButton.setImage(UIImage(named: "settings"), forState: .Normal)
settingsButton.addTarget(self, action: "SELdidClickSettingsItem", forControlEvents: .TouchUpInside)
settingsButton.accessibilityLabel = NSLocalizedString("Settings", comment: "Accessibility label for the Settings button in the Tab Tray.")
let flowLayout = TabTrayCollectionViewLayout()
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: flowLayout)
collectionView.dataSource = tabDataSource
collectionView.delegate = tabLayoutDelegate
collectionView.registerClass(TabCell.self, forCellWithReuseIdentifier: TabCell.Identifier)
collectionView.backgroundColor = TabTrayControllerUX.BackgroundColor
view.addSubview(collectionView)
view.addSubview(navBar)
view.addSubview(addTabButton)
view.addSubview(settingsButton)
makeConstraints()
if #available(iOS 9, *) {
view.addSubview(togglePrivateMode)
togglePrivateMode.snp_makeConstraints { make in
make.right.equalTo(addTabButton.snp_left).offset(-10)
make.size.equalTo(UIConstants.ToolbarHeight)
make.centerY.equalTo(self.navBar)
}
view.insertSubview(emptyPrivateTabsView, aboveSubview: collectionView)
emptyPrivateTabsView.hidden = !(privateMode && tabManager.privateTabs.count == 0)
emptyPrivateTabsView.snp_makeConstraints { make in
make.edges.equalTo(self.view)
}
if let tab = tabManager.selectedTab where tab.isPrivate {
privateMode = true
}
}
}
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Update the trait collection we reference in our layout delegate
tabLayoutDelegate.traitCollection = traitCollection
collectionView.collectionViewLayout.invalidateLayout()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
private func makeConstraints() {
let viewBindings: [String: AnyObject] = [
"topLayoutGuide" : topLayoutGuide,
"navBar" : navBar
]
let topConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[topLayoutGuide][navBar]", options: [], metrics: nil, views: viewBindings)
view.addConstraints(topConstraints)
navBar.snp_makeConstraints { make in
make.height.equalTo(UIConstants.ToolbarHeight)
make.left.right.equalTo(self.view)
}
addTabButton.snp_makeConstraints { make in
make.trailing.bottom.equalTo(self.navBar)
make.size.equalTo(UIConstants.ToolbarHeight)
}
settingsButton.snp_makeConstraints { make in
make.leading.bottom.equalTo(self.navBar)
make.size.equalTo(UIConstants.ToolbarHeight)
}
collectionView.snp_makeConstraints { make in
make.top.equalTo(navBar.snp_bottom)
make.left.right.bottom.equalTo(self.view)
}
}
// MARK: Selectors
func SELdidClickDone() {
presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
}
func SELdidClickSettingsItem() {
let settingsTableViewController = SettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
let controller = SettingsNavigationController(rootViewController: settingsTableViewController)
controller.popoverDelegate = self
controller.modalPresentationStyle = UIModalPresentationStyle.FormSheet
presentViewController(controller, animated: true, completion: nil)
}
func SELdidClickAddTab() {
if #available(iOS 9, *) {
if privateMode {
emptyPrivateTabsView.hidden = true
}
}
// We're only doing one update here, but using a batch update lets us delay selecting the tab
// until after its insert animation finishes.
self.collectionView.performBatchUpdates({ _ in
var tab: Browser
if #available(iOS 9, *) {
tab = self.tabManager.addTab(isPrivate: self.privateMode)
} else {
tab = self.tabManager.addTab()
}
self.tabManager.selectTab(tab)
}, completion: { finished in
if finished {
self.navigationController?.popViewControllerAnimated(true)
}
})
}
@available(iOS 9, *)
func SELdidTogglePrivateMode() {
privateMode = !privateMode
}
}
extension TabTrayController: TabSelectionDelegate {
func didSelectTabAtIndex(index: Int) {
let tab = tabsToDisplay[index]
tabManager.selectTab(tab)
self.navigationController?.popViewControllerAnimated(true)
}
}
extension TabTrayController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(modalViewController: UIViewController, animated: Bool) {
dismissViewControllerAnimated(animated, completion: { self.collectionView.reloadData() })
}
}
extension TabTrayController: TabManagerDelegate {
func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) {
}
func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool) {
}
func tabManager(tabManager: TabManager, didAddTab tab: Browser, restoring: Bool) {
// Get the index of the added tab from it's set (private or normal)
guard let index = tabsToDisplay.indexOf(tab) else { return }
tabDataSource.tabs.append(tab)
self.collectionView.performBatchUpdates({ _ in
self.collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)])
}, completion: { finished in
if finished {
tabManager.selectTab(tab)
// don't pop the tab tray view controller if it is not in the foreground
if self.presentedViewController == nil {
self.navigationController?.popViewControllerAnimated(true)
}
}
})
}
func tabManager(tabManager: TabManager, didRemoveTab tab: Browser) {
if let removedIndex = removedTabIndexPath {
tabDataSource.tabs.removeAtIndex(removedIndex.item)
self.collectionView.deleteItemsAtIndexPaths([removedIndex])
self.collectionView.reloadItemsAtIndexPaths(self.collectionView.indexPathsForVisibleItems())
removedTabIndexPath = nil
if #available(iOS 9, *) {
if privateMode && tabsToDisplay.count == 0 {
emptyPrivateTabsView.hidden = false
}
}
}
}
func tabManagerDidAddTabs(tabManager: TabManager) {
}
func tabManagerDidRestoreTabs(tabManager: TabManager) {
}
}
extension TabTrayController: UIScrollViewAccessibilityDelegate {
func accessibilityScrollStatusForScrollView(scrollView: UIScrollView) -> String? {
var visibleCells = collectionView.visibleCells() as! [TabCell]
var bounds = collectionView.bounds
bounds = CGRectOffset(bounds, collectionView.contentInset.left, collectionView.contentInset.top)
bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right
bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom
// visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...)
visibleCells = visibleCells.filter { !CGRectIsEmpty(CGRectIntersection($0.frame, bounds)) }
var indexPaths = visibleCells.map { self.collectionView.indexPathForCell($0)! }
indexPaths.sortInPlace { $0.section < $1.section || ($0.section == $1.section && $0.row < $1.row) }
if indexPaths.count == 0 {
return NSLocalizedString("No tabs", comment: "Message spoken by VoiceOver to indicate that there are no tabs in the Tabs Tray")
}
let firstTab = indexPaths.first!.row + 1
let lastTab = indexPaths.last!.row + 1
let tabCount = collectionView.numberOfItemsInSection(0)
if (firstTab == lastTab) {
let format = NSLocalizedString("Tab %@ of %@", comment: "Message spoken by VoiceOver saying the position of the single currently visible tab in Tabs Tray, along with the total number of tabs. E.g. \"Tab 2 of 5\" says that tab 2 is visible (and is the only visible tab), out of 5 tabs total.")
return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: tabCount))
} else {
let format = NSLocalizedString("Tabs %@ to %@ of %@", comment: "Message spoken by VoiceOver saying the range of tabs that are currently visible in Tabs Tray, along with the total number of tabs. E.g. \"Tabs 8 to 10 of 15\" says tabs 8, 9 and 10 are visible, out of 15 tabs total.")
return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: lastTab), NSNumber(integer: tabCount))
}
}
}
extension TabTrayController: SwipeAnimatorDelegate {
func swipeAnimator(animator: SwipeAnimator, viewDidExitContainerBounds: UIView) {
let tabCell = animator.container as! TabCell
if let indexPath = collectionView.indexPathForCell(tabCell) {
let tab = tabsToDisplay[indexPath.item]
removedTabIndexPath = indexPath
tabManager.removeTab(tab)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Closing tab", comment: ""))
}
}
}
extension TabTrayController: TabCellDelegate {
func tabCellDidClose(cell: TabCell) {
let indexPath = collectionView.indexPathForCell(cell)!
let tab = tabsToDisplay[indexPath.item]
removedTabIndexPath = indexPath
tabManager.removeTab(tab)
}
}
private class TabManagerDataSource: NSObject, UICollectionViewDataSource {
unowned var cellDelegate: protocol<TabCellDelegate, SwipeAnimatorDelegate>
var tabs: [Browser]
init(tabs: [Browser], cellDelegate: protocol<TabCellDelegate, SwipeAnimatorDelegate>) {
self.cellDelegate = cellDelegate
self.tabs = tabs
super.init()
}
@objc func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let tabCell = collectionView.dequeueReusableCellWithReuseIdentifier(TabCell.Identifier, forIndexPath: indexPath) as! TabCell
tabCell.animator.delegate = cellDelegate
tabCell.delegate = cellDelegate
let tab = tabs[indexPath.item]
tabCell.style = tab.isPrivate ? .Dark : .Light
tabCell.titleText.text = tab.displayTitle
if !tab.displayTitle.isEmpty {
tabCell.accessibilityLabel = tab.displayTitle
} else {
tabCell.accessibilityLabel = AboutUtils.getAboutComponent(tab.url)
}
tabCell.isAccessibilityElement = true
tabCell.accessibilityHint = NSLocalizedString("Swipe right or left with three fingers to close the tab.", comment: "Accessibility hint for tab tray's displayed tab.")
if let favIcon = tab.displayFavicon {
tabCell.favicon.sd_setImageWithURL(NSURL(string: favIcon.url)!)
} else {
tabCell.favicon.image = UIImage(named: "defaultFavicon")
}
tabCell.background.image = tab.screenshot
return tabCell
}
@objc func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabs.count
}
}
@objc protocol TabSelectionDelegate: class {
func didSelectTabAtIndex(index :Int)
}
private class TabLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout {
weak var tabSelectionDelegate: TabSelectionDelegate?
private var traitCollection: UITraitCollection
private var profile: Profile
private var numberOfColumns: Int {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
// iPhone 4-6+ portrait
if traitCollection.horizontalSizeClass == .Compact && traitCollection.verticalSizeClass == .Regular {
return compactLayout ? TabTrayControllerUX.CompactNumberOfColumnsThin : TabTrayControllerUX.NumberOfColumnsThin
} else {
return TabTrayControllerUX.NumberOfColumnsWide
}
}
init(profile: Profile, traitCollection: UITraitCollection) {
self.profile = profile
self.traitCollection = traitCollection
super.init()
}
private func cellHeightForCurrentDevice() -> CGFloat {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
let shortHeight = (compactLayout ? TabTrayControllerUX.TextBoxHeight * 6 : TabTrayControllerUX.TextBoxHeight * 5)
if self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.Compact {
return shortHeight
} else if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.Compact {
return shortHeight
} else {
return TabTrayControllerUX.TextBoxHeight * 8
}
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let cellWidth = (collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns)
return CGSizeMake(cellWidth, self.cellHeightForCurrentDevice())
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin)
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row)
}
}
// There seems to be a bug with UIKit where when the UICollectionView changes its contentSize
// from > frame.size to <= frame.size: the contentSet animation doesn't properly happen and 'jumps' to the
// final state.
// This workaround forces the contentSize to always be larger than the frame size so the animation happens more
// smoothly. This also makes the tabs be able to 'bounce' when there are not enough to fill the screen, which I
// think is fine, but if needed we can disable user scrolling in this case.
private class TabTrayCollectionViewLayout: UICollectionViewFlowLayout {
private override func collectionViewContentSize() -> CGSize {
var calculatedSize = super.collectionViewContentSize()
let collectionViewHeight = collectionView?.bounds.size.height ?? 0
if calculatedSize.height < collectionViewHeight && collectionViewHeight > 0 {
calculatedSize.height = collectionViewHeight + 1
}
return calculatedSize
}
}
// A transparent view with a rectangular border with rounded corners, stroked
// with a semi-transparent white border.
class InnerStrokedView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let strokeWidth = 1.0 as CGFloat
let halfWidth = strokeWidth/2 as CGFloat
let path = UIBezierPath(roundedRect: CGRect(x: halfWidth,
y: halfWidth,
width: rect.width - strokeWidth,
height: rect.height - strokeWidth),
cornerRadius: TabTrayControllerUX.CornerRadius)
path.lineWidth = strokeWidth
UIColor.whiteColor().colorWithAlphaComponent(0.2).setStroke()
path.stroke()
}
}
struct EmptyPrivateTabsViewUX {
static let TitleColor = UIColor.whiteColor()
static let TitleFont = UIFont.systemFontOfSize(22, weight: UIFontWeightMedium)
static let DescriptionColor = UIColor.whiteColor()
static let DescriptionFont = UIFont.systemFontOfSize(17)
static let TextMargin: CGFloat = 18
static let MaxDescriptionWidth: CGFloat = 250
}
// View we display when there are no private tabs created
private class EmptyPrivateTabsView: UIView {
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = EmptyPrivateTabsViewUX.TitleColor
label.font = EmptyPrivateTabsViewUX.TitleFont
label.textAlignment = NSTextAlignment.Center
return label
}()
private var descriptionLabel: UILabel = {
let label = UILabel()
label.textColor = EmptyPrivateTabsViewUX.DescriptionColor
label.font = EmptyPrivateTabsViewUX.DescriptionFont
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = 3
label.preferredMaxLayoutWidth = EmptyPrivateTabsViewUX.MaxDescriptionWidth
return label
}()
private var iconImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "largePrivateMask"))
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.text = NSLocalizedString("Private Browsing",
tableName: "PrivateBrowsing", comment: "Title displayed for when there are no open tabs while in private mode")
descriptionLabel.text = NSLocalizedString("Firefox won't remember any of your history or cookies, but new bookmarks will be saved.",
tableName: "PrivateBrowsing", comment: "Description text displayed when there are no open tabs while in private mode")
// This landed last-minute as a new string that is needed in the EmptyPrivateTabsView
let learnMoreLabelText = NSLocalizedString("Learn More", tableName: "PrivateBrowsing", comment: "Text button displayed when there are no tabs open while in private mode")
addSubview(titleLabel)
addSubview(descriptionLabel)
addSubview(iconImageView)
titleLabel.snp_makeConstraints { make in
make.center.equalTo(self)
}
iconImageView.snp_makeConstraints { make in
make.bottom.equalTo(titleLabel.snp_top).offset(-EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
descriptionLabel.snp_makeConstraints { make in
make.top.equalTo(titleLabel.snp_bottom).offset(EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | f6f376608f0dca1e46e81b1dc87fa928 | 39.965969 | 304 | 0.694901 | 5.618022 | false | false | false | false |
andrebocchini/SwiftChatty | SwiftChatty/Requests/Notifications/DetachAccountRequest.swift | 1 | 626 | //
// 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: HTTPMethod = .post
public let account: Account
public var customParameters: [String : Any] = [:]
public init(withClientId clientId: String, account: Account) {
self.account = account
self.customParameters["clientId"] = clientId
}
}
| mit | 183407423a76106b83bcfaf357cc8ad9 | 27.409091 | 66 | 0.704 | 4.251701 | false | false | false | false |
onevcat/Kingfisher | Sources/Extensions/NSButton+Kingfisher.swift | 2 | 15146 | //
// NSButton+Kingfisher.swift
// Kingfisher
//
// Created by Jie Zhang on 14/04/2016.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if canImport(AppKit) && !targetEnvironment(macCatalyst)
import AppKit
extension KingfisherWrapper where Base: NSButton {
// MARK: Setting Image
/// Sets an image to the button with a source.
///
/// - Parameters:
/// - source: The `Source` object contains information about how to get the image.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// Internally, this method will use `KingfisherManager` to get the requested source.
/// Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
return setImage(
with: source,
placeholder: placeholder,
parsedOptions: options,
progressBlock: progressBlock,
completionHandler: completionHandler
)
}
/// Sets an image to the button with a requested resource.
///
/// - Parameters:
/// - resource: The `Resource` object contains information about the resource.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
/// or network. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with resource: Resource?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setImage(
with: resource?.convertToSource(),
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
func setImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
parsedOptions: KingfisherParsedOptionsInfo,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
var mutatingSelf = self
guard let source = source else {
base.image = placeholder
mutatingSelf.taskIdentifier = nil
completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
return nil
}
var options = parsedOptions
if !options.keepCurrentImageWhileLoading {
base.image = placeholder
}
let issuedIdentifier = Source.Identifier.next()
mutatingSelf.taskIdentifier = issuedIdentifier
if let block = progressBlock {
options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
}
let task = KingfisherManager.shared.retrieveImage(
with: source,
options: options,
downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
progressiveImageSetter: { self.base.image = $0 },
referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
completionHandler: { result in
CallbackQueue.mainCurrentOrAsync.execute {
guard issuedIdentifier == self.taskIdentifier else {
let reason: KingfisherError.ImageSettingErrorReason
do {
let value = try result.get()
reason = .notCurrentSourceTask(result: value, error: nil, source: source)
} catch {
reason = .notCurrentSourceTask(result: nil, error: error, source: source)
}
let error = KingfisherError.imageSettingError(reason: reason)
completionHandler?(.failure(error))
return
}
mutatingSelf.imageTask = nil
mutatingSelf.taskIdentifier = nil
switch result {
case .success(let value):
self.base.image = value.image
completionHandler?(result)
case .failure:
if let image = options.onFailureImage {
self.base.image = image
}
completionHandler?(result)
}
}
}
)
mutatingSelf.imageTask = task
return task
}
// MARK: Cancelling Downloading Task
/// Cancels the image download task of the button if it is running.
/// Nothing will happen if the downloading has already finished.
public func cancelImageDownloadTask() {
imageTask?.cancel()
}
// MARK: Setting Alternate Image
@discardableResult
public func setAlternateImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
return setAlternateImage(
with: source,
placeholder: placeholder,
parsedOptions: options,
progressBlock: progressBlock,
completionHandler: completionHandler
)
}
/// Sets an alternate image to the button with a requested resource.
///
/// - Parameters:
/// - resource: The `Resource` object contains information about the resource.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
/// or network. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setAlternateImage(
with resource: Resource?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setAlternateImage(
with: resource?.convertToSource(),
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
func setAlternateImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
parsedOptions: KingfisherParsedOptionsInfo,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
var mutatingSelf = self
guard let source = source else {
base.alternateImage = placeholder
mutatingSelf.alternateTaskIdentifier = nil
completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
return nil
}
var options = parsedOptions
if !options.keepCurrentImageWhileLoading {
base.alternateImage = placeholder
}
let issuedIdentifier = Source.Identifier.next()
mutatingSelf.alternateTaskIdentifier = issuedIdentifier
if let block = progressBlock {
options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
}
if let provider = ImageProgressiveProvider(options, refresh: { image in
self.base.alternateImage = image
}) {
options.onDataReceived = (options.onDataReceived ?? []) + [provider]
}
options.onDataReceived?.forEach {
$0.onShouldApply = { issuedIdentifier == self.alternateTaskIdentifier }
}
let task = KingfisherManager.shared.retrieveImage(
with: source,
options: options,
downloadTaskUpdated: { mutatingSelf.alternateImageTask = $0 },
completionHandler: { result in
CallbackQueue.mainCurrentOrAsync.execute {
guard issuedIdentifier == self.alternateTaskIdentifier else {
let reason: KingfisherError.ImageSettingErrorReason
do {
let value = try result.get()
reason = .notCurrentSourceTask(result: value, error: nil, source: source)
} catch {
reason = .notCurrentSourceTask(result: nil, error: error, source: source)
}
let error = KingfisherError.imageSettingError(reason: reason)
completionHandler?(.failure(error))
return
}
mutatingSelf.alternateImageTask = nil
mutatingSelf.alternateTaskIdentifier = nil
switch result {
case .success(let value):
self.base.alternateImage = value.image
completionHandler?(result)
case .failure:
if let image = options.onFailureImage {
self.base.alternateImage = image
}
completionHandler?(result)
}
}
}
)
mutatingSelf.alternateImageTask = task
return task
}
// MARK: Cancelling Alternate Image Downloading Task
/// Cancels the alternate image download task of the button if it is running.
/// Nothing will happen if the downloading has already finished.
public func cancelAlternateImageDownloadTask() {
alternateImageTask?.cancel()
}
}
// MARK: - Associated Object
private var taskIdentifierKey: Void?
private var imageTaskKey: Void?
private var alternateTaskIdentifierKey: Void?
private var alternateImageTaskKey: Void?
extension KingfisherWrapper where Base: NSButton {
// MARK: Properties
public private(set) var taskIdentifier: Source.Identifier.Value? {
get {
let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
return box?.value
}
set {
let box = newValue.map { Box($0) }
setRetainedAssociatedObject(base, &taskIdentifierKey, box)
}
}
private var imageTask: DownloadTask? {
get { return getAssociatedObject(base, &imageTaskKey) }
set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
}
public private(set) var alternateTaskIdentifier: Source.Identifier.Value? {
get {
let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &alternateTaskIdentifierKey)
return box?.value
}
set {
let box = newValue.map { Box($0) }
setRetainedAssociatedObject(base, &alternateTaskIdentifierKey, box)
}
}
private var alternateImageTask: DownloadTask? {
get { return getAssociatedObject(base, &alternateImageTaskKey) }
set { setRetainedAssociatedObject(base, &alternateImageTaskKey, newValue)}
}
}
#endif
| mit | 7357e0aac283376af9e6a08f350fc97c | 40.839779 | 119 | 0.623663 | 5.696126 | false | false | false | false |
pgorzelany/experimental-swift-ios | ExperimentalSwift/ActivityHandler.swift | 1 | 1086 | //
// NetworkActivityHandler.swift
// ExperimentalSwift
//
// Created by PiotrGorzelanyMac on 10/04/2017.
// Copyright © 2017 rst-it. All rights reserved.
//
import Foundation
import UIKit
protocol ActivityHandler {
func showActivityIndicator()
func hideActivityIndicator()
}
extension UIViewController: ActivityHandler {
@nonobjc static var activityIndicator: UIActivityIndicatorView?
func showActivityIndicator() {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
UIViewController.activityIndicator = activityIndicator
view.addSubview(activityIndicator)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
activityIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
func hideActivityIndicator() {
UIViewController.activityIndicator?.removeFromSuperview()
UIViewController.activityIndicator = nil
}
}
| mit | cddd5af6b683d0c705da63dbaaf8fe36 | 30 | 95 | 0.75023 | 5.961538 | false | false | false | false |
morizotter/SwiftFontName | Example/ExampleTests/FontsTests.swift | 1 | 1459 | //
// ExampleTests.swift
// ExampleTests
//
// Created by MORITANAOKI on 2015/07/18.
// Copyright (c) 2015年 molabo. All rights reserved.
//
import UIKit
import XCTest
@testable import Example
class FontsTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testExistsFontNames() {
for systemFamilyName in UIFont.familyNames {
for systemFontName in UIFont.fontNames(forFamilyName: systemFamilyName) {
let index = FontName.fontNames().firstIndex(of: systemFontName)
print(systemFontName)
XCTAssertTrue(index != nil, "\(systemFontName) doesn't exist.")
}
}
}
func testLocalizations() {
let preferredLanguage = Locale.preferredLanguages.first!
let fontName = LocalizedFontName(FontName.Copperplate, localizedFontNames: ["ja": FontName.HiraKakuProNW6, "en": FontName.HelveticaNeueLight])
if preferredLanguage == "ja" {
XCTAssertEqual(fontName, FontName.HiraKakuProNW6, "Localization failed: \(preferredLanguage)")
} else if preferredLanguage == "en" {
XCTAssertEqual(fontName, FontName.HelveticaNeueLight, "Localization failed: \(preferredLanguage)")
} else {
XCTAssertEqual(fontName, FontName.Copperplate, "Localization failed: \(preferredLanguage)")
}
}
}
| mit | fd11f1c1da721153dcb80dbafeb9f432 | 31.377778 | 150 | 0.645848 | 5.112281 | false | true | false | false |
GrandCentralBoard/GrandCentralBoard | GrandCentralBoard/Widgets/GitHub/GitHubTableDataSource.swift | 2 | 945 | //
// GitHubTableDataSource.swift
// GrandCentralBoard
//
// Created by Michał Laskowski on 21/05/16.
//
import UIKit
class GitHubTableDataSource: NSObject, UITableViewDataSource {
private let maxRowsToShow = 3
private let cellID = "cell"
var items: [GitHubCellViewModel] = []
func setUpTableView(tableView: UITableView) {
tableView.registerNib(UINib(nibName: "GitHubCell", bundle: nil), forCellReuseIdentifier: cellID)
tableView.dataSource = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return min(maxRowsToShow, items.count)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! GitHubCell
cell.configureWithViewModel(items[indexPath.row])
return cell
}
}
| gpl-3.0 | d476f4b12a37538c074655c444a3497f | 29.451613 | 110 | 0.721398 | 4.891192 | false | false | false | false |
alexbredy/ABBadgeButton | ABBadgeButton/Classes/ABBadgeButton.swift | 1 | 2926 | //
// ABBadgeButton.swift
// ABBadgeButton
//
// Created by Alexander Bredy on 11/08/2016.
// Copyright (c) 2016 Alexander Bredy. All rights reserved.
//
import UIKit
open class ABBadgeButton: UIButton {
fileprivate var badge: UILabel
open var badgeValue: String = ""{
didSet{
setBadgeText(badgeValue)
}
}
open var badgeInsets: CGFloat = 6{
didSet{
setBadgeText(badgeValue)
}
}
open var badgeOriginOffset: CGPoint = CGPoint(x: 0, y: 0){
didSet{
setBadgeText(badgeValue)
}
}
open var badgeBorderColor: CGColor?{
didSet{
updateBadgeStyle()
}
}
open var badgeBorderWidth: CGFloat = 0{
didSet{
updateBadgeStyle()
}
}
open var badgeBackgroundColor: UIColor = UIColor.red{
didSet{
updateBadgeStyle()
}
}
open var badgeTextColor: UIColor = UIColor.white{
didSet{
updateBadgeStyle()
}
}
open var badgeFont: UIFont = UIFont.systemFont(ofSize: 12){
didSet{
setBadgeText(badgeValue)
}
}
override public init(frame: CGRect) {
badge = UILabel()
super.init(frame: frame)
setBadgeText("")
}
required public init?(coder aDecoder: NSCoder) {
badge = UILabel()
super.init(coder: aDecoder)
setBadgeText("")
}
/*
* Update the UI style of the badge (colors, borders, alignment and font)
*/
fileprivate func updateBadgeStyle(){
badge.textAlignment = NSTextAlignment.center
badge.backgroundColor = badgeBackgroundColor
badge.textColor = badgeTextColor
badge.layer.borderWidth = badgeBorderWidth
badge.layer.borderColor = badgeBorderColor
}
/*
* Calculates the badge frame based on the badgeValue and badgeInsets properties
*/
fileprivate func setBadgeText(_ text: String) {
badge.text = text
badge.font = badgeFont
badge.clipsToBounds = true
badge.sizeToFit()
let badgeHeight = badge.frame.height + badgeInsets
let minBadgeWidth = badge.bounds.size.width + badgeInsets
var frame = badge.frame
frame.size.height = badgeHeight
frame.size.width = minBadgeWidth < badgeHeight ? badgeHeight : minBadgeWidth
let origin: CGPoint = CGPoint(x: (self.frame.width - frame.width/2) + badgeOriginOffset.x, y: (-frame.size.height/2) + badgeOriginOffset.y)
badge.frame = CGRect(origin: origin, size: frame.size)
badge.layer.cornerRadius = badgeHeight / 2
updateBadgeStyle()
addSubview(badge)
badge.layer.zPosition = 9999
badge.isHidden = (text.characters.count == 0)
}
}
| mit | 828a58953460dd46a7ea5d3c1911640b | 24.893805 | 147 | 0.584416 | 4.901173 | false | false | false | false |
MingLoan/PageTabBarController | sources/PageTabBarBackdropView.swift | 1 | 1757 | //
// PageTabBarBackdropView.swift
// PageTabBarController
//
// Created by Keith Chan on 7/3/2018.
// Copyright © 2018 com.mingloan. All rights reserved.
//
import UIKit
final class PageTabBarBackdropView: UIView {
var translucentFactor: CGFloat = 0.6
var isTranslucent: Bool = true {
didSet {
backgroundColor = isTranslucent ? barTintColor.withAlphaComponent(translucentFactor) : barTintColor
}
}
var barBlurStyle: UIBlurEffect.Style = .light {
didSet {
backDropBlurView.effect = UIBlurEffect(style: barBlurStyle)
}
}
var barTintColor: UIColor = .white {
didSet {
backgroundColor = isTranslucent ? barTintColor.withAlphaComponent(translucentFactor) : barTintColor
}
}
private let backDropBlurView: UIVisualEffectView = {
let backDropBlurView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffect.Style.light))
backDropBlurView.translatesAutoresizingMaskIntoConstraints = false
return backDropBlurView
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
addSubview(backDropBlurView)
NSLayoutConstraint.activate([backDropBlurView.topAnchor.constraint(equalTo: topAnchor),
backDropBlurView.leftAnchor.constraint(equalTo: leftAnchor),
backDropBlurView.rightAnchor.constraint(equalTo: rightAnchor),
backDropBlurView.bottomAnchor.constraint(equalTo: bottomAnchor)])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 13b292b4c5d56bed065f7760a4494332 | 32.132075 | 111 | 0.646355 | 5.757377 | false | false | false | false |
michaello/AEConsole | Sources/Brain.swift | 1 | 8641 | //
// Brain.swift
//
// Copyright (c) 2016 Marko Tadić <[email protected]> http://tadija.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 UIKit
import AELog
class Brain: NSObject {
// MARK: - Outlets
var console: View!
// MARK: - Properties
fileprivate let config = Config.shared
var lines = [Line]()
var filteredLines = [Line]()
var contentWidth: CGFloat = 0.0
var filterText: String? {
didSet {
isFilterActive = !isEmpty(filterText)
}
}
var isFilterActive = false {
didSet {
updateFilter()
updateInterfaceIfNeeded()
}
}
// MARK: - API
func configureConsole(with appDelegate: UIApplicationDelegate) {
guard let _window = appDelegate.window, let window = _window else { return }
console = createConsoleView(in: window)
console.tableView.dataSource = self
console.tableView.delegate = self
console.textField.delegate = self
}
public func configureConsoleUI(with delegate: UIApplicationDelegate, injectedConsoleView: View) {
guard let _window = delegate.window, let window = _window else { return }
let aConsole = injectedConsoleView
aConsole.frame = window.bounds
aConsole.autoresizingMask = [.flexibleWidth, .flexibleHeight]
aConsole.isOnScreen = Config.shared.isAutoStartEnabled
window.addSubview(aConsole)
console = aConsole
console.tableView.dataSource = self
console.tableView.delegate = self
console.tableView.rowHeight = UITableViewAutomaticDimension
console.textField.delegate = self
}
func addLogLine(_ line: Line) {
calculateContentWidth(for: line)
updateFilteredLines(with: line)
if let lastLine = lines.last, lastLine.message != line.message {
lines.append(line)
} else if lines.last == nil {
lines.append(line)
}
updateInterfaceIfNeeded()
}
func isEmpty(_ text: String?) -> Bool {
guard let text = text else { return true }
let characterSet = CharacterSet.whitespacesAndNewlines
let isTextEmpty = text.trimmingCharacters(in: characterSet).isEmpty
return isTextEmpty
}
// MARK: - Actions
func clearLog() {
lines.removeAll()
filteredLines.removeAll()
updateInterfaceIfNeeded()
}
func exportAllLogLines() {
let stringLines = lines.map({ $0.description })
let log = stringLines.joined(separator: "\n")
if isEmpty(log) {
aelog("Log is empty, nothing to export here.")
} else {
writeLog(log)
}
}
}
extension Brain {
// MARK: - Helpers
fileprivate func updateFilter() {
if isFilterActive {
applyFilter()
} else {
clearFilter()
}
}
private func applyFilter() {
guard let filter = filterText else { return }
aelog("Filter Lines [\(isFilterActive)] - <\(filter)>")
let filtered = lines.filter({ $0.description.localizedCaseInsensitiveContains(filter) })
filteredLines = filtered
}
private func clearFilter() {
aelog("Filter Lines [\(isFilterActive)]")
filteredLines.removeAll()
}
fileprivate func updateInterfaceIfNeeded() {
if console.isOnScreen {
console.updateUI()
}
}
fileprivate func createConsoleView(in window: UIWindow) -> View {
let view = View()
view.frame = window.bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.isOnScreen = config.isAutoStartEnabled
window.addSubview(view)
return view
}
fileprivate func calculateContentWidth(for line: Line) {
contentWidth = UIScreen.main.bounds.width
}
fileprivate func updateFilteredLines(with line: Line) {
if isFilterActive {
guard let filter = filterText else { return }
if line.description.contains(filter) {
filteredLines.append(line)
}
}
}
private func getWidth(for line: Line) -> CGFloat {
let text = line.description
let maxSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: config.rowHeight)
let options = NSStringDrawingOptions.usesLineFragmentOrigin
let attributes = [NSFontAttributeName : config.consoleFont]
let nsText = text as NSString
let size = nsText.boundingRect(with: maxSize, options: options, attributes: attributes, context: nil)
let width = size.width
return width
}
fileprivate func writeLog(_ log: String) {
let filename = "\(Date().timeIntervalSince1970).aelog"
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let documentsURL = URL(fileURLWithPath: documentsPath)
let fileURL = documentsURL.appendingPathComponent(filename)
do {
try log.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
aelog("Log is exported to path: \(fileURL)")
} catch {
aelog(error)
}
}
}
extension Brain: UITableViewDataSource, UITableViewDelegate {
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let rows = isFilterActive ? filteredLines : lines
return rows.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Cell.identifier) as! Cell
return cell
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let rows = isFilterActive ? filteredLines : lines
let logLine = rows[indexPath.row]
cell.textLabel?.text = logLine.description
}
func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
let pasteboard = UIPasteboard.general
pasteboard.string = lines.reduce("\n ") { $0 + $1.message + "\n" }
}
func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
if action == "copy:" {
return true
}
return false
}
func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
return true
}
// MARK: - UIScrollViewDelegate
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
console.currentOffsetX = scrollView.contentOffset.x
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
console.currentOffsetX = scrollView.contentOffset.x
}
}
extension Brain: UITextFieldDelegate {
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if !isEmpty(textField.text) {
filterText = textField.text
}
return true
}
}
| mit | bf2b29538b5ab928ffaf1cd2ecd7f09a | 31.118959 | 145 | 0.635648 | 5.19543 | false | false | false | false |
EZ-NET/ESSwim | Sources/Calculation/Zeroable.swift | 1 | 1688 | //
// Zeroable.swift
// ESSwim
//
// Created by Tomohiro Kumagai on H27/07/30.
//
//
public protocol Zeroable {
static var zero:Self { get }
var isZero:Bool { get }
}
extension Zeroable {
public func nonZeroMap<Result:Zeroable>(predicate:(Self) throws -> Result) rethrows -> Result {
if self.isZero {
return Result.zero
}
else {
return try predicate(self)
}
}
}
extension Zeroable where Self : Equatable {
public var isZero:Bool {
return self == Self.zero
}
public var isNonZero:Bool {
return !self.isZero
}
}
// MARK: - Extension
extension Float : Zeroable {
public static let zero:Float = 0
}
extension Double : Zeroable {
public static let zero:Double = 0
}
extension Int : Zeroable {
public static let zero:Int = 0
}
extension Int8 : Zeroable {
public static let zero:Int8 = 0
}
extension Int16 : Zeroable {
public static let zero:Int16 = 0
}
extension Int32 : Zeroable {
public static let zero:Int32 = 0
}
extension Int64 : Zeroable {
public static let zero:Int64 = 0
}
extension UInt : Zeroable {
public static let zero:UInt = 0
}
extension UInt8 : Zeroable {
public static let zero:UInt8 = 0
}
extension UInt16 : Zeroable {
public static let zero:UInt16 = 0
}
extension UInt32 : Zeroable {
public static let zero:UInt32 = 0
}
extension UInt64 : Zeroable {
public static let zero:UInt64 = 0
}
extension String : Zeroable {
public static let zero:String = ""
public var isZero:Bool {
return self.isEmpty
}
}
extension Set : Zeroable {
public static var zero:Set<Element> {
return Set<Element>()
}
public var isZero:Bool {
return self.isEmpty
}
}
| mit | 491aeceab66b479e71b848fc83ba7455 | 12.291339 | 96 | 0.667062 | 3.309804 | false | false | false | false |
sebastiancrossa/smack | Smack/Controller/LoginVC.swift | 1 | 1739 | //
// LoginVC.swift
// Smack
//
// Created by Sebastian Crossa on 7/29/17.
// Copyright © 2017 Sebastian Crossa. All rights reserved.
//
import UIKit
class LoginVC: UIViewController {
// Outlets
@IBOutlet weak var usernameText: UITextField!
@IBOutlet weak var passwordText: UITextField!
@IBOutlet weak var spinner: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
@IBAction func loginPressed(_ sender: Any) {
spinner.isHidden = false
spinner.startAnimating()
guard let email = usernameText.text , usernameText.text != "" else { return }
guard let pass = passwordText.text , passwordText.text != "" else { return }
AuthService.instance.loginUser(email: email, password: pass) { (success) in
if success {
AuthService.instance.findUserByEmail(completion: { (success) in
if success {
NotificationCenter.default.post(name: NOTIF_USER_DATA_DID_CHANGE, object: nil)
self.spinner.isHidden = true
self.spinner.stopAnimating()
self.dismiss(animated: true, completion: nil)
}
})
}
}
}
// Will segue to CreateAccountVC
@IBAction func createAccountButtonPressed(_ sender: Any) {
performSegue(withIdentifier: TO_CREATE_ACCOUNT, sender: nil)
}
@IBAction func closePressed (_ sender: Any) {
dismiss(animated: true, completion: nil)
}
func setupView() {
spinner.isHidden = true
}
}
| apache-2.0 | bb507e6c999f43cd68f424303c835a0d | 28.457627 | 102 | 0.56847 | 5.052326 | false | false | false | false |
machelix/SwiftLocation | SwiftLocationExample/SwiftLocationExample/ViewController.swift | 1 | 2402 | //
// ViewController.swift
// SwiftLocationExample
//
// Created by daniele on 31/07/15.
// Copyright (c) 2015 danielemargutti. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
SwiftLocation.shared.currentLocation(Accuracy.Neighborhood, timeout: 20, onSuccess: { (location) -> Void in
// location is a CLPlacemark
println("Location found \(location?.description)")
}) { (error) -> Void in
// something went wrong
println("Something went wrong -> \(error?.localizedDescription)")
}
return
SwiftLocation.shared.reverseAddress(Service.Apple, address: "1 Infinite Loop, Cupertino (USA)", region: nil, onSuccess: { (place) -> Void in
// our CLPlacemark is here
}) { (error) -> Void in
// something went wrong
}
let coordinates = CLLocationCoordinate2DMake(41.890198, 12.492204)
SwiftLocation.shared.reverseCoordinates(Service.Apple, coordinates: coordinates, onSuccess: { (place) -> Void in
// our placemark is here
}) { (error) -> Void in
// something went wrong
}
let requestID = SwiftLocation.shared.continuousLocation(Accuracy.Room, onSuccess: { (location) -> Void in
// a new location has arrived
}) { (error) -> Void in
// something went wrong. request will be cancelled automatically
}
// Sometime in the future... you may want to interrupt it
SwiftLocation.shared.cancelRequest(requestID)
SwiftLocation.shared.significantLocation({ (location) -> Void in
// a new significant location has arrived
}, onFail: { (error) -> Void in
// something went wrong. request will be cancelled automatically
})
let regionCoordinates = CLLocationCoordinate2DMake(41.890198, 12.492204)
var region = CLCircularRegion(center: regionCoordinates, radius: CLLocationDistance(50), identifier: "identifier_region")
SwiftLocation.shared.monitorRegion(region, onEnter: { (region) -> Void in
// events called on enter
}) { (region) -> Void in
// event called on exit
}
let bRegion = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "ciao"), identifier: "myIdentifier")
SwiftLocation.shared.monitorBeaconsInRegion(bRegion, onRanging: { (regions) -> Void in
// events called on ranging
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 5801487277fb42a40d1dcf5dc991444a | 30.605263 | 142 | 0.713156 | 4.030201 | false | false | false | false |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/InsertMediaSettingsViewController.swift | 1 | 14734 | import UIKit
import SafariServices
typealias InsertMediaSettings = InsertMediaSettingsViewController.Settings
final class InsertMediaSettingsViewController: ViewController {
private let tableView = UITableView(frame: .zero, style: .grouped)
private let image: UIImage
let searchResult: InsertMediaSearchResult
private var textViewHeightDelta: (value: CGFloat, row: Int)?
private var textViewsGroupedByType = [TextViewType: UITextView]()
struct Settings {
let caption: String?
let alternativeText: String?
let advanced: Advanced
struct Advanced {
let wrapTextAroundImage: Bool
let imagePosition: ImagePosition
let imageType: ImageType
let imageSize: ImageSize
enum ImagePosition: String {
case right
case left
case center
case none
var displayTitle: String {
switch self {
case .right:
return WMFLocalizedString("insert-media-image-position-setting-right", value: "Right", comment: "Title for image position setting that positions image on the right")
case .left:
return WMFLocalizedString("insert-media-image-position-setting-left", value: "Left", comment: "Title for image position setting that positions image on the left")
case .center:
return WMFLocalizedString("insert-media-image-position-setting-center", value: "Center", comment: "Title for image position setting that positions image in the center")
case .none:
return WMFLocalizedString("insert-media-image-position-setting-none", value: "None", comment: "Title for image position setting that doesn't set image's position")
}
}
static var displayTitle: String {
return WMFLocalizedString("insert-media-image-position-settings-title", value: "Image position", comment: "Display ritle for image position setting")
}
}
enum ImageType: String {
case thumbnail = "thumb"
case frameless
case frame
case basic
var displayTitle: String {
switch self {
case .thumbnail:
return WMFLocalizedString("insert-media-image-type-setting-thumbnail", value: "Thumbnail", comment: "Title for image type setting that formats image as thumbnail")
case .frameless:
return WMFLocalizedString("insert-media-image-type-setting-frameless", value: "Frameless", comment: "Title for image type setting that formats image as frameless")
case .frame:
return WMFLocalizedString("insert-media-image-type-setting-frame", value: "Frame", comment: "Title for image type setting that formats image as framed")
case .basic:
return WMFLocalizedString("insert-media-image-type-setting-basic", value: "Basic", comment: "Title for image type setting that formats image as basic")
}
}
static var displayTitle: String {
return WMFLocalizedString("insert-media-image-type-settings-title", value: "Image type", comment: "Display ritle for image type setting")
}
}
enum ImageSize {
case `default`
case custom(width: Int, height: Int)
var displayTitle: String {
switch self {
case .default:
return WMFLocalizedString("insert-media-image-size-setting-default", value: "Default", comment: "Title for image size setting that sizes image using default size")
case .custom:
return WMFLocalizedString("insert-media-image-size-setting-custom", value: "Custom", comment: "Title for image size setting that sizes image using custom size")
}
}
static var displayTitle: String {
return WMFLocalizedString("insert-media-image-size-settings-title", value: "Image size", comment: "Display ritle for image size setting")
}
var rawValue: String {
switch self {
case .default:
return "\(ImageSize.defaultWidth)x\(ImageSize.defaultHeight)px"
case .custom(let width, let height):
return "\(width)x\(height)px"
}
}
static var unitName = WMFLocalizedString("insert-media-image-size-settings-px-unit-name", value: "px", comment: "Image size unit name, abbreviation for 'pixels'")
static var defaultWidth = 220
static var defaultHeight = 124
}
init(wrapTextAroundImage: Bool = false, imagePosition: ImagePosition = .right, imageType: ImageType = .thumbnail, imageSize: ImageSize = .default) {
self.wrapTextAroundImage = wrapTextAroundImage
self.imagePosition = imagePosition
self.imageType = imageType
self.imageSize = imageSize
}
}
init(caption: String?, alternativeText: String?, advanced: Advanced = Advanced()) {
self.caption = caption
self.alternativeText = alternativeText
self.advanced = advanced
}
}
var settings: Settings? {
let captionTextView = textViewsGroupedByType[.caption]
let alternativeTextTextView = textViewsGroupedByType[.alternativeText]
let caption = captionTextView?.text.wmf_hasNonWhitespaceText ?? false ? captionTextView?.text : nil
let alternativeText = alternativeTextTextView?.text.wmf_hasNonWhitespaceText ?? false ? alternativeTextTextView?.text : nil
return Settings(caption: caption, alternativeText: alternativeText, advanced: insertMediaAdvancedSettingsViewController.advancedSettings)
}
private lazy var imageView: InsertMediaSettingsImageView = {
let imageView = InsertMediaSettingsImageView.wmf_viewFromClassNib()!
imageView.image = image
imageView.heading = WMFLocalizedString("insert-media-uploaded-image-title", value: "Uploaded image", comment: "Title that appears next to an image in media settings")
imageView.title = searchResult.displayTitle
imageView.titleURL = searchResult.imageInfo?.filePageURL
imageView.titleAction = { [weak self] url in
self?.present(SFSafariViewController(url: url), animated: true)
}
imageView.autoresizingMask = []
return imageView
}()
private lazy var insertMediaAdvancedSettingsViewController = InsertMediaAdvancedSettingsViewController()
private lazy var buttonView: InsertMediaSettingsButtonView = {
let buttonView = InsertMediaSettingsButtonView.wmf_viewFromClassNib()!
let isRTL = UIApplication.shared.wmf_isRTL
let buttonTitleWithoutChevron = InsertMediaAdvancedSettingsViewController.title
let buttonTitleWithChevron = isRTL ? "< \(buttonTitleWithoutChevron)" : "\(buttonTitleWithoutChevron) >"
buttonView.buttonTitle = buttonTitleWithChevron
buttonView.buttonAction = { [weak self] _ in
guard let self = self else {
return
}
self.insertMediaAdvancedSettingsViewController.apply(theme: self.theme)
self.navigationController?.pushViewController(self.insertMediaAdvancedSettingsViewController, animated: true)
}
buttonView.autoresizingMask = []
return buttonView
}()
private struct TextViewModel {
let type: TextViewType
let headerText: String
let placeholder: String
let footerText: String
init(type: TextViewType) {
self.type = type
switch type {
case .caption:
headerText = WMFLocalizedString("insert-media-caption-title", value: "Caption", comment: "Title for setting that allows users to add image captions")
placeholder = WMFLocalizedString("insert-media-caption-caption-placeholder", value: "How does this image relate to the article?", comment: "Placeholder text for setting that allows users to add image captions")
footerText = WMFLocalizedString("insert-media-caption-description", value: "Label that shows next to the item for all readers", comment: "Description for setting that allows users to add image captions")
case .alternativeText:
headerText = WMFLocalizedString("insert-media-alternative-text-title", value: "Alternative text", comment: "Title for setting that allows users to add image alternative text")
placeholder = WMFLocalizedString("insert-media-alternative-text-placeholder", value: "Describe this image", comment: "Placeholder text for setting that allows users to add image alternative text")
footerText = WMFLocalizedString("insert-media-alternative-text-description", value: "Text description for readers who cannot see the image", comment: "Description for setting that allows users to add image alternative text")
}
}
}
private enum TextViewType: Int, Hashable {
case caption
case alternativeText
}
private lazy var viewModels: [TextViewModel] = {
let captionViewModel = TextViewModel(type: .caption)
let alternativeTextViewModel = TextViewModel(type: .alternativeText)
return [captionViewModel, alternativeTextViewModel]
}()
init(image: UIImage, searchResult: InsertMediaSearchResult) {
self.image = image
self.searchResult = searchResult
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
scrollView = tableView
super.viewDidLoad()
navigationBar.isBarHidingEnabled = false
tableView.dataSource = self
view.wmf_addSubviewWithConstraintsToEdges(tableView)
tableView.register(InsertMediaSettingsTextTableViewCell.wmf_classNib(), forCellReuseIdentifier: InsertMediaSettingsTextTableViewCell.identifier)
tableView.separatorStyle = .none
tableView.tableHeaderView = imageView
tableView.tableFooterView = buttonView
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard let headerView = tableView.tableHeaderView else {
return
}
let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
guard headerView.frame.size.height != height else {
return
}
headerView.frame.size.height = height
tableView.tableHeaderView = headerView
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
guard textViewHeightDelta != nil else {
return
}
UIView.performWithoutAnimation {
self.textViewHeightDelta = nil
self.tableView.beginUpdates()
self.tableView.endUpdates()
}
}
// MARK: - Themeable
override func apply(theme: Theme) {
super.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
tableView.backgroundColor = view.backgroundColor
imageView.apply(theme: theme)
buttonView.apply(theme: theme)
}
}
// MARK: - Table view data source
extension InsertMediaSettingsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: InsertMediaSettingsTextTableViewCell.identifier, for: indexPath) as? InsertMediaSettingsTextTableViewCell else {
return UITableViewCell()
}
let viewModel = viewModels[indexPath.row]
cell.headerText = viewModel.headerText
textViewsGroupedByType[viewModel.type] = cell.textViewConfigured(with: self, placeholder: viewModel.placeholder, placeholderDelegate: self, clearDelegate: self, tag: indexPath.row)
cell.footerText = viewModel.footerText
cell.selectionStyle = .none
cell.apply(theme: theme)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard
let cell = tableView.visibleCells[safeIndex: indexPath.row] as? InsertMediaSettingsTextTableViewCell,
let textViewHeightDelta = textViewHeightDelta,
textViewHeightDelta.row == indexPath.row
else {
return UITableView.automaticDimension
}
return cell.frame.size.height + textViewHeightDelta.value
}
}
extension InsertMediaSettingsViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
updateTextViewHeight(textView)
}
private func updateTextViewHeight(_ textView: UITextView) {
let oldHeight = textView.frame.size.height
let newHeight = textView.systemLayoutSizeFitting(textView.frame.size).height
guard oldHeight != newHeight else {
return
}
textViewHeightDelta = (newHeight - oldHeight, textView.tag)
UIView.performWithoutAnimation {
textView.frame.size.height = newHeight
tableView.beginUpdates()
tableView.endUpdates()
}
}
}
extension InsertMediaSettingsViewController: ThemeableTextViewPlaceholderDelegate {
func themeableTextViewPlaceholderDidHide(_ themeableTextView: UITextView, isPlaceholderHidden: Bool) {
updateTextViewHeight(themeableTextView)
}
}
extension InsertMediaSettingsViewController: ThemeableTextViewClearDelegate {
func themeableTextViewDidClear(_ themeableTextView: UITextView) {
updateTextViewHeight(themeableTextView)
}
}
| mit | 35e4903cdce00a26847c2c9e8de77b87 | 45.04375 | 240 | 0.652301 | 5.784845 | false | false | false | false |
robbdimitrov/pixelgram-ios | PixelGram/Classes/Shared/ViewControllers/ViewController.swift | 1 | 3062 | //
// ViewController.swift
// PixelGram
//
// Created by Robert Dimitrov on 10/31/17.
// Copyright © 2017 Robert Dimitrov. All rights reserved.
//
import UIKit
import RxSwift
class ViewController: UIViewController {
let disposeBag = DisposeBag()
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationItem()
}
// MARK: - Config
func setupNavigationItem() {
navigationItem.leftBarButtonItems = leftButtonItems()
navigationItem.rightBarButtonItems = rightButtonItems()
}
func leftButtonItems() -> [UIBarButtonItem]? {
// Implemented by subclasses
return nil
}
func rightButtonItems() -> [UIBarButtonItem]? {
// Implemented by subclasses
return nil
}
func setupTitleView(with image: UIImage) {
let logoView = UIImageView()
let image = UIImage(named: "logo")
let ratio: CGFloat = (image?.size.width ?? 0) / (image?.size.height ?? 1)
let height: CGFloat = 30.0;
let size = CGSize(width: height * ratio, height: height)
logoView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
logoView.image = image
let titleView = UIView()
titleView.addSubview(logoView)
logoView.center = titleView.center
self.navigationItem.titleView = titleView
}
func setupTitleView(with title: String, font: UIFont = UIFont.systemFont(ofSize: 17.0)) {
let label = UILabel()
label.font = font
label.text = title
navigationItem.titleView = label
}
// MARK: - State
func showMessage(title: String, content: String) {
let alert = UIAlertController(title: title, message: content, preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
func showError(error: String) {
showMessage(title: "Error", content: error)
}
// MARK: - Components
func buttonItem(with title: String) -> UIBarButtonItem {
return UIBarButtonItem(title: title, style: .plain,
target: nil, action: nil)
}
func cancelButtonItem() -> UIBarButtonItem {
return buttonItem(with: "Cancel")
}
func doneButtonItem() -> UIBarButtonItem {
return buttonItem(with: "Done")
}
func closeButtonItem() -> UIBarButtonItem {
return buttonItem(with: "Close")
}
// MARK: - Storyboard
func instantiateViewController(withIdentifier identifier: String) -> UIViewController {
guard let storyboard = storyboard else {
print("Storyboard is nil")
return UIViewController()
}
return storyboard.instantiateViewController(withIdentifier: identifier)
}
}
| mit | 11a58a7295e8e55fcaf5e4add9c47935 | 26.330357 | 93 | 0.599151 | 5.067881 | false | false | false | false |
remirobert/LoginProvider | LoginProvider/GoogleProvider.swift | 1 | 1721 | //
// GoogleProvider.swift
// BookMe5iOS
//
// Created by Remi Robert on 06/12/15.
// Copyright © 2015 Remi Robert. All rights reserved.
//
import UIKit
import Alamofire
class GoogleProvider: NSObject, Provider, GIDSignInDelegate, GIDSignInUIDelegate {
let providerType = LoginProviderType.Google
var delegate: LoginProviderDelegate?
var parentController: UIViewController!
@objc func signIn(signIn: GIDSignIn!,
presentViewController viewController: UIViewController!) {
self.parentController.presentViewController(viewController, animated: true, completion: nil)
}
@objc func signIn(signIn: GIDSignIn!,
dismissViewController viewController: UIViewController!) {
self.parentController.dismissViewControllerAnimated(true, completion: nil)
}
@objc func signIn(signIn: GIDSignIn!, didDisconnectWithUser user: GIDGoogleUser!, withError error: NSError!) {
GIDSignIn.sharedInstance().signIn()
}
@objc func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
if (error == nil) {
let idToken = user.authentication.idToken
self.delegate?.loginProvider(self, didSucceed: APIAuth.Google(token: idToken))
}
else {
self.delegate?.loginProvider(self, didError: error)
}
}
func login() {
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().signOut()
GIDSignIn.sharedInstance().signIn()
}
init(parentController: UIViewController) {
self.parentController = parentController
}
}
| mit | c6e41037ee33b382b04355cbd5661dc4 | 32.076923 | 114 | 0.680814 | 5.243902 | false | false | false | false |
daggmano/photo-management-studio | src/Client/OSX/Photo Management Studio/Photo Management Studio/ResponseObject.swift | 1 | 2150 | //
// ResponseObject.swift
// Photo Management Studio
//
// Created by Darren Oster on 12/02/2016.
// Copyright © 2016 Darren Oster. All rights reserved.
//
import Foundation
class ResponseObject<T : JsonProtocol> : NSObject, JsonProtocol {
internal private(set) var links: LinksObject?
internal private(set) var data: T?
init(links: LinksObject, data: T) {
self.links = links
self.data = data
}
required init(json: [String: AnyObject]) {
if let links = json["links"] as? [String: AnyObject] {
self.links = LinksObject(json: links)
}
if let data = json["data"] as? [String: AnyObject] {
self.data = T(json: data)
}
}
func toJSON() -> [String: AnyObject] {
var result = [String: AnyObject]()
if let links = self.links {
result["links"] = links.toJSON()
}
if let data = self.data {
result["data"] = data.toJSON()
}
return result
}
}
class ResponseListObject<T : JsonProtocol> : NSObject, JsonProtocol {
internal private(set) var links: LinksObject?
internal private(set) var data: Array<T>?
init(links: LinksObject, data: Array<T>) {
self.links = links
self.data = data
}
required init(json: [String: AnyObject]) {
if let links = json["links"] as? [String: AnyObject] {
self.links = LinksObject(json: links)
}
if let dataArray = json["data"] as? [[String: AnyObject]] {
self.data = [T]()
for data in dataArray {
self.data!.append(T(json: data))
}
}
}
func toJSON() -> [String: AnyObject] {
var result = [String: AnyObject]()
if let links = self.links {
result["links"] = links.toJSON()
}
if let data = self.data {
var array = [[String: AnyObject]]()
for dataItem in data {
array.append(dataItem.toJSON())
}
result["data"] = array
}
return result
}
}
| mit | 75578617bb091f045276c5a3de80c6da | 25.8625 | 69 | 0.531875 | 4.255446 | false | false | false | false |
jsslai/Action | Carthage/Checkouts/RxSwift/RxCocoa/Common/CocoaUnits/Driver/Driver+Subscription.swift | 1 | 5132 | //
// Driver+Subscription.swift
// Rx
//
// Created by Krunoslav Zaher on 9/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
private let driverErrorMessage = "`drive*` family of methods can be only called from `MainThread`.\n" +
"This is required to ensure that the last replayed `Driver` element is delivered on `MainThread`.\n"
// This would ideally be Driver, but unfortunatelly Driver can't be extended in Swift 3.0
extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy {
/**
Creates new subscription and sends elements to observer.
This method can be only called from `MainThread`.
In this form it's equivalent to `subscribe` method, but it communicates intent better.
- parameter observer: Observer that receives events.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return self.asSharedSequence().asObservable().subscribe(observer)
}
/**
Creates new subscription and sends elements to variable.
This method can be only called from `MainThread`.
- parameter variable: Target variable for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer from the variable.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive(_ variable: Variable<E>) -> Disposable {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return drive(onNext: { e in
variable.value = e
})
}
/**
Subscribes to observable sequence using custom binder function.
This method can be only called from `MainThread`.
- parameter with: Function used to bind elements from `self`.
- returns: Object representing subscription.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive<R>(_ transformation: (Observable<E>) -> R) -> R {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return transformation(self.asObservable())
}
/**
Subscribes to observable sequence using custom binder function and final parameter passed to binder function
after `self` is passed.
public func drive<R1, R2>(with: Self -> R1 -> R2, curriedArgument: R1) -> R2 {
return with(self)(curriedArgument)
}
This method can be only called from `MainThread`.
- parameter with: Function used to bind elements from `self`.
- parameter curriedArgument: Final argument passed to `binder` to finish binding process.
- returns: Object representing subscription.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive<R1, R2>(_ with: (Observable<E>) -> (R1) -> R2, curriedArgument: R1) -> R2 {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return with(self.asObservable())(curriedArgument)
}
/**
Subscribes an element handler, a completion handler and disposed handler to an observable sequence.
This method can be only called from `MainThread`.
Error callback is not exposed because `Driver` can't error out.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
gracefully completed, errored, or if the generation is cancelled by disposing subscription)
- parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is cancelled by disposing subscription)
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
public func drive(onNext: ((E) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed)
}
/**
Subscribes an element handler to an observable sequence.
This method can be only called from `MainThread`.
- parameter onNext: Action to invoke for each element in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.ud")
@available(*, deprecated, renamed: "drive(onNext:)")
public func driveNext(_ onNext: @escaping (E) -> Void) -> Disposable {
MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage)
return self.asObservable().subscribe(onNext: onNext)
}
}
| mit | bc0f53fac118e1d07e51bac6fe6e305f | 43.232759 | 134 | 0.707075 | 4.80881 | false | false | false | false |
everald/JetPack | Sources/Extensions/Swift/Array.swift | 1 | 743 | public extension Array {
public func getOrNil(_ index: Index) -> Iterator.Element? {
guard indices.contains(index) else {
return nil
}
return self[index]
}
public func toArray() -> [Iterator.Element] {
return self
}
}
public extension Array where Iterator.Element: _Optional, Iterator.Element.Wrapped: Equatable {
public func index(of element: Iterator.Element.Wrapped?) -> Int? {
return index { $0.value == element }
}
}
public func === <T: AnyObject> (a: [T], b: [T]) -> Bool {
guard a.count == b.count else {
return false
}
for index in a.indices {
guard a[index] === b[index] else {
return false
}
}
return true
}
public func !== <T: AnyObject> (a: [T], b: [T]) -> Bool {
return !(a === b)
}
| mit | 332053630956be0845d95223ee8883f3 | 16.27907 | 95 | 0.627187 | 3.032653 | false | false | false | false |
genedelisa/AVAudioUnitSamplerFrobs | AVAudioUnitSamplerFrobs/ViewController.swift | 1 | 1525 | //
// ViewController.swift
// AVAudioUnitSamplerFrobs
//
// Created by Gene De Lisa on 1/13/16.
// Copyright © 2016 Gene De Lisa. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var sampler1: Sampler1!
var samplerSequence: SamplerSequence!
var samplerSequenceOTF: SamplerSequenceOTF!
var drumMachine: DrumMachine!
var duet: Duet!
override func viewDidLoad() {
super.viewDidLoad()
sampler1 = Sampler1()
samplerSequence = SamplerSequence()
samplerSequenceOTF = SamplerSequenceOTF()
drumMachine = DrumMachine()
duet = Duet()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sampler1Down(_ sender: UIButton) {
sampler1.play()
}
@IBAction func sampler1Up(_ sender: UIButton) {
sampler1.stop()
}
@IBAction func samplerSequence(_ sender: UIButton) {
samplerSequence.play()
}
@IBAction func samplerSequenceOTF(_ sender: UIButton) {
samplerSequenceOTF.play()
}
@IBAction func drumMachinePlay(_ sender: UIButton) {
drumMachine.play()
}
@IBAction func duetDown(_ sender: UIButton) {
duet.play()
}
@IBAction func duetUp(_ sender: UIButton) {
duet.stop()
}
}
| mit | 1c318122d3cd4ce02b4cd42d3f53dff3 | 19.876712 | 59 | 0.587927 | 4.900322 | false | false | false | false |
hilenium/HISwiftExtensions | Example/Tests/NSURLTests.swift | 1 | 1282 | ////
//// NSURLTests.swift
//// HISwiftExtensions
////
//// Created by Matthew on 29/12/2015.
//// Copyright © 2015 CocoaPods. All rights reserved.
////
//
import Quick
import Nimble
import HISwiftExtensions
//
//class NSURLSpec: QuickSpec {
//
// override func spec() {
// describe("nsurl extensions") {
//
// it("query parameters") {
//
// let url = NSURL(string: "http://foo.com?foo=bar&bar=foo")
// let dict = url?.queryParameters
//
// expect(dict?["foo"]!).to(equal("bar"))
// expect(dict?["bar"]!).to(equal("foo"))
// }
//
// it("failable convenience initializer - successful") {
//
// let string: String? = "http://foo.com"
// let url = NSURL(optionalString: string)
//
// expect(url).toNot(equal(.none))
// }
//
// it("failable convenience initializer - failure") {
//
// let string: String? = "foo"
// let url = NSURL(optionalString: string)
//
// expect(url).to(equal(.none))
// }
// }
// }
//}
//
| mit | f20a4cc6d7beda66f35b2921cd8f207f | 27.466667 | 75 | 0.437939 | 4.092652 | false | false | false | false |
Tsiems/STRiNg | CarFile/CarFile/NewCarViewController.swift | 1 | 18907 | //
// NewCarViewController.swift
// CarFile
//
// Created by Travis Siems on 11/1/15.
// Copyright © 2015 STRiNg, int. All rights reserved.
//
import UIKit
import Foundation
import SwiftHTTP
import CoreData
class NewCarViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var deleteButton: UIButton!
@IBOutlet weak var populateVinButton: UIButton!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var populateVinTextField: UITextField!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var makeTextField: UITextField!
@IBOutlet weak var modelTextField: UITextField!
@IBOutlet weak var yearTextField: UITextField!
@IBOutlet weak var colorTextField: UITextField!
@IBOutlet weak var priceTextField: UITextField!
@IBOutlet weak var vinNumTextField: UITextField!
@IBOutlet weak var licNumTextField: UITextField!
@IBOutlet weak var notesTextField: UITextField!
var styleID: String?
var newCar: Bool?
var carIndex: Int?
var leftBarItem: UIBarButtonItem?
var rightBarItem: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
setTextFieldDelegates()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name:UIKeyboardWillHideNotification, object: nil)
self.styleID = ""
// let backItem = UIBarButtonItem(title: "cancel", style: .Plain, target: nil, action: nil)
// navigationItem.backBarButtonItem = backItem
if newCar == true
{
prepareNewCar()
}
else
{
prepareExistingCar()
}
navigationController!.navigationBar.barTintColor = UIColor(red:0.09,green:0.55,blue:1.00,alpha: 1.00)
let attributes = [
NSForegroundColorAttributeName: UIColor.whiteColor(),
NSFontAttributeName: UIFont(name: "HelveticaNeue-Bold", size: 28)!
]
navigationController!.navigationBar.titleTextAttributes = attributes
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
let width = UIScreen.mainScreen().bounds.size.width
let height = UIScreen.mainScreen().bounds.size.height
scrollView.contentSize = CGSizeMake(width, height)
scrollView.scrollEnabled = true
//scroll to top
self.scrollView.setContentOffset(CGPoint(x:0,y:0), animated: false)
}
func prepareNewCar() {
title = "New Car"
enableTextEditting()
//set the bar items
let leftButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancelToCarMenu:")
let rightButton = UIBarButtonItem(title: "Save", style: .Done, target: self, action: "saveToCarMenu:")
leftButton.tintColor = UIColor.whiteColor()
rightButton.tintColor = UIColor.whiteColor()
self.navigationItem.leftBarButtonItem = leftButton
self.navigationItem.rightBarButtonItem = rightButton
//save these in case they change
leftBarItem = self.navigationItem.leftBarButtonItem
rightBarItem = self.navigationItem.rightBarButtonItem
}
func prepareExistingCar() {
enableTextEditting()
populateFields()
disableTextEditting()
//set the right button time
let rightButton = UIBarButtonItem(title: "Edit", style: .Done, target: self, action: "editButtonPressed:")
rightButton.tintColor = UIColor.whiteColor()
self.navigationItem.rightBarButtonItem = rightButton
//save these in case they change
leftBarItem = self.navigationItem.leftBarButtonItem
rightBarItem = self.navigationItem.rightBarButtonItem
}
func populateFields() {
title = cars[carIndex!].valueForKey("name") as? String
nameTextField.text = title
makeTextField.text = cars[carIndex!].valueForKey("make") as? String
modelTextField.text = cars[carIndex!].valueForKey("model") as? String
yearTextField.text = cars[carIndex!].valueForKey("year") as? String
colorTextField.text = cars[carIndex!].valueForKey("color") as? String
priceTextField.text = cars[carIndex!].valueForKey("price") as? String
vinNumTextField.text = cars[carIndex!].valueForKey("vinNum") as? String
licNumTextField.text = cars[carIndex!].valueForKey("licNum") as? String
notesTextField.text = cars[carIndex!].valueForKey("notes") as? String
}
func updateData() {
cars[carIndex!].setValue(nameTextField.text, forKey: "name")
cars[carIndex!].setValue(makeTextField.text, forKey: "make")
cars[carIndex!].setValue(modelTextField.text, forKey: "model")
cars[carIndex!].setValue(yearTextField.text, forKey: "year")
cars[carIndex!].setValue(colorTextField.text, forKey: "color")
cars[carIndex!].setValue(priceTextField.text, forKey: "price")
cars[carIndex!].setValue(vinNumTextField.text, forKey: "vinNum")
cars[carIndex!].setValue(licNumTextField.text, forKey: "licNum")
cars[carIndex!].setValue(notesTextField.text, forKey: "notes")
//save in persistent store
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.saveContext()
//populateFields() //not really needed, just the title
title = nameTextField.text
}
func cancelToCarMenu(sender: UIBarButtonItem) {
self.performSegueWithIdentifier("cancelToMenuSegue", sender: sender)
}
func saveToCarMenu(sender: UIBarButtonItem) {
self.nameTextField.text = self.nameTextField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if self.nameTextField.text != "" {
self.performSegueWithIdentifier("saveToMenuSegue", sender: sender)
}
else {
let invalidFieldsAlert = UIAlertController(title: "Save Car", message: "The car must have a name.", preferredStyle: UIAlertControllerStyle.Alert)
invalidFieldsAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
//do nothing
}))
presentViewController(invalidFieldsAlert, animated: true, completion: nil)
}
}
func editButtonPressed(sender: UIBarButtonItem) {
enableTextEditting()
//set the bar items
let leftButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancelButtonPressed")
let rightButton = UIBarButtonItem(title: "Save", style: .Done, target: self, action: "saveButtonPressedForUpdate")
leftButton.tintColor = UIColor.whiteColor()
rightButton.tintColor = UIColor.whiteColor()
self.navigationItem.leftBarButtonItem = leftButton
self.navigationItem.rightBarButtonItem = rightButton
}
func cancelButtonPressed() {
disableTextEditting()
resetBarItems()
}
func saveButtonPressedForUpdate() {
self.nameTextField.text = self.nameTextField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if self.nameTextField.text != "" {
updateData()
disableTextEditting()
resetBarItems()
}
else {
let invalidFieldsAlert = UIAlertController(title: "Save Car", message: "The car must have a name.", preferredStyle: UIAlertControllerStyle.Alert)
invalidFieldsAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
//do nothing
}))
presentViewController(invalidFieldsAlert, animated: true, completion: nil)
}
}
@IBAction func deleteButtonPressed(sender: AnyObject) {
let deleteAlert = UIAlertController(title: "Delete Car", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)
deleteAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
//do nothing
}))
deleteAlert.addAction(UIAlertAction(title: "Ok", style: .Destructive, handler: { (action: UIAlertAction!) in
self.deleteThisCar(sender)
//exit this view (the car is gone)
self.performSegueWithIdentifier("cancelToMenuSegue", sender: sender)
}))
presentViewController(deleteAlert, animated: true, completion: nil)
}
func deleteThisCar(sender: AnyObject) {
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let thisCarID = cars[carIndex!].valueForKey("id") as? Int
for i in 0...maintenanceItems.count-1
{
if maintenanceItems[i].valueForKey("carID") as? Int == thisCarID
{
managedContext.deleteObject(maintenanceItems[i] as NSManagedObject)
}
}
//delete the car
managedContext.deleteObject(cars[carIndex!] as NSManagedObject)
cars.removeAtIndex(carIndex!)
appDelegate.saveContext()
}
func resetBarItems() {
self.navigationItem.leftBarButtonItem = self.leftBarItem
self.navigationItem.rightBarButtonItem = self.rightBarItem
}
func disableTextEditting() {
populateVinTextField.hidden = true
populateVinButton.hidden = true
nameTextField.hidden = true
nameLabel.hidden = true
populateVinTextField.userInteractionEnabled = false
nameTextField.userInteractionEnabled = false
makeTextField.userInteractionEnabled = false
makeTextField.borderStyle = UITextBorderStyle.None
modelTextField.userInteractionEnabled = false
modelTextField.borderStyle = UITextBorderStyle.None
yearTextField.userInteractionEnabled = false
yearTextField.borderStyle = UITextBorderStyle.None
colorTextField.userInteractionEnabled = false
colorTextField.borderStyle = UITextBorderStyle.None
priceTextField.userInteractionEnabled = false
priceTextField.borderStyle = UITextBorderStyle.None
vinNumTextField.userInteractionEnabled = false
vinNumTextField.borderStyle = UITextBorderStyle.None
licNumTextField.userInteractionEnabled = false
licNumTextField.borderStyle = UITextBorderStyle.None
notesTextField.userInteractionEnabled = false
notesTextField.borderStyle = UITextBorderStyle.None
deleteButton.hidden = true
}
func enableTextEditting() {
populateVinTextField.hidden = false
populateVinButton.hidden = false
nameTextField.hidden = false
nameLabel.hidden = false
populateVinTextField.userInteractionEnabled = true
nameTextField.userInteractionEnabled = true
makeTextField.userInteractionEnabled = true
makeTextField.borderStyle = UITextBorderStyle.RoundedRect
modelTextField.userInteractionEnabled = true
modelTextField.borderStyle = UITextBorderStyle.RoundedRect
yearTextField.userInteractionEnabled = true
yearTextField.borderStyle = UITextBorderStyle.RoundedRect
colorTextField.userInteractionEnabled = true
colorTextField.borderStyle = UITextBorderStyle.RoundedRect
priceTextField.userInteractionEnabled = true
priceTextField.borderStyle = UITextBorderStyle.RoundedRect
vinNumTextField.userInteractionEnabled = true
vinNumTextField.borderStyle = UITextBorderStyle.RoundedRect
licNumTextField.userInteractionEnabled = true
licNumTextField.borderStyle = UITextBorderStyle.RoundedRect
notesTextField.userInteractionEnabled = true
notesTextField.borderStyle = UITextBorderStyle.RoundedRect
if newCar == false {
deleteButton.hidden = false
}
else {
deleteButton.hidden = true
}
}
@IBAction func populateVin(sender: AnyObject) {
//Steven's Car VIN (Not Case Sensitive): 1FADP3L9XFL256135
var vin = ""
vin = populateVinTextField.text!
self.view.window?.endEditing(true)
if vin.characters.count == 17
{
let urlString = "https://api.edmunds.com/api/vehicle/v2/vins/" + vin + "?fmt=json&api_key=5zyd8sa5k3yxgpcg7t49agav"
if let url = NSURL(string: urlString)
{
if let data = try? NSData(contentsOfURL: url, options: [])
{
let json = JSON(data: data)
if json["make"]["id"].intValue > 0
{
//let id = json["make"]["id"].intValue
let makeName = json["make"]["name"].stringValue
let modelName = json["model"]["name"].stringValue
let yearName = json["years"][0]["year"].stringValue
let colorName = json["colors"][1]["options"][0]["name"].stringValue
let priceName = json["price"]["baseMSRP"].stringValue
let vinName = json["vin"].stringValue
let styleID = json["years"][0]["styles"][0]["id"].stringValue
let obj = ["makeName": makeName, "modelName": modelName, "yearName": yearName, "colorName": colorName, "priceName": priceName, "vinName": vinName, "styleID": styleID]
setObject(obj)
populateVinTextField.text="";
}
else
{
let invalidFieldsAlert = UIAlertController(title: "Populate Failed", message: "Invalid Vin Number.", preferredStyle: UIAlertControllerStyle.Alert)
invalidFieldsAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
//do nothing
}))
presentViewController(invalidFieldsAlert, animated: true, completion: nil)
}
}
}
}
else
{
let invalidFieldsAlert = UIAlertController(title: "Populate Information", message: "Invalid Vin Number.", preferredStyle: UIAlertControllerStyle.Alert)
invalidFieldsAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
//do nothing
}))
presentViewController(invalidFieldsAlert, animated: true, completion: nil)
}
} // END of Populate Button Function
func setObject(obj:[String:String])
{
self.makeTextField.text = obj["makeName"]
self.modelTextField.text = obj["modelName"]
self.yearTextField.text = obj["yearName"]
self.colorTextField.text = obj["colorName"]
self.priceTextField.text = obj["priceName"]
self.vinNumTextField.text = obj["vinName"]
self.styleID = obj["styleID"]
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
let nextTage=textField.tag+1;
// Try to find next responder
let nextResponder=textField.superview?.viewWithTag(nextTage) as UIResponder!
if (nextResponder != nil){
// Found next responder, so set it.
nextResponder?.becomeFirstResponder()
}
else
{
// Not found, so remove keyboard
textField.resignFirstResponder()
}
return false // We do not want UITextField to insert line-breaks.
}
func setTextFieldDelegates() {
self.populateVinTextField.delegate = self
self.nameTextField.delegate = self
self.makeTextField.delegate = self
self.modelTextField.delegate = self
self.yearTextField.delegate = self
self.colorTextField.delegate = self
self.priceTextField.delegate = self
self.vinNumTextField.delegate = self
self.licNumTextField.delegate = self
self.notesTextField.delegate = self
}
func keyboardWillShow(notification:NSNotification){
var userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
keyboardFrame = self.view.convertRect(keyboardFrame, fromView: nil)
scrollView.scrollEnabled = true
var contentInset:UIEdgeInsets = self.scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height
self.scrollView.contentInset = contentInset
//scrollView.scrollEnabled = false
}
func keyboardWillHide(notification:NSNotification){
scrollView.scrollEnabled = true
self.scrollView.setContentOffset(CGPoint(x:0,y:0), animated: true)
scrollView.scrollEnabled = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
//put stuff to save textfield's text
}
}
| gpl-2.0 | d7dda5284fa4ebe6b29dd45d86e9a2ed | 36.289941 | 190 | 0.619221 | 5.82799 | false | false | false | false |
stefanoa/Spectrogram | Spectogram/play.playground/Contents.swift | 1 | 421 | //: Playground - noun: a place where people can play
import UIKit
let delta:CGFloat = 10
func yAtIndex(index:Int)->CGFloat{
let indexF = CGFloat(index)
return round((log(indexF+1)/log(noteSeparation))*delta)
}
let noteSeparation:CGFloat = 1.059463
let size:Int = 16
let y0 = yAtIndex(index: 0)
for i in 0...size-1{
let y = yAtIndex(index: i)
print("y:\(y)")
}
print ("size:\(yAtIndex(index:size-1))")
| mit | cceb2d40bf074feec2ca3d5385396bf5 | 21.157895 | 59 | 0.672209 | 3.050725 | false | false | false | false |
spotify/SPTDataLoader | Sources/SPTDataLoaderSwift/Request+Concurrency.swift | 1 | 4004 | // Copyright 2015-2022 Spotify AB
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if compiler(>=5.5.2) && canImport(_Concurrency)
import Foundation
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
public extension Request {
func task() -> ResponseTask<Void> {
return ResponseTask(request: self)
}
func dataTask() -> ResponseTask<Data> {
return ResponseTask(request: self)
}
func decodableTask<Value: Decodable>(
type: Value.Type = Value.self,
decoder: ResponseDecoder = JSONDecoder()
) -> ResponseTask<Value> {
return ResponseTask(request: self, decodableType: type, decoder: decoder)
}
func jsonTask(options: JSONSerialization.ReadingOptions = []) -> ResponseTask<Any> {
return ResponseTask(request: self, options: options)
}
func serializableTask<Serializer: ResponseSerializer>(serializer: Serializer) -> ResponseTask<Serializer.Output> {
return ResponseTask(request: self, serializer: serializer)
}
}
// MARK: -
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
public struct ResponseTask<Value> {
private let task: Task<Response<Value, Error>, Never>
fileprivate init(
request: Request,
continuation: @escaping (CheckedContinuation<Response<Value, Error>, Never>) -> Void
) {
self.task = Task {
await withTaskCancellationHandler(
operation: { await withCheckedContinuation(continuation) },
onCancel: {
request.cancel()
}
)
}
}
public func cancel() {
task.cancel()
}
public var response: Response<Value, Error> {
get async { await task.value }
}
public var result: Result<Value, Error> {
get async { await response.result }
}
public var value: Value {
get async throws { try await result.get() }
}
}
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
private extension ResponseTask {
init(request: Request) where Value == Void {
self.init(request: request) { continuation in
request.response { response in
continuation.resume(returning: response)
}
}
}
init(request: Request) where Value == Data {
self.init(request: request) { continuation in
request.responseData { response in
continuation.resume(returning: response)
}
}
}
init(request: Request, decodableType: Value.Type, decoder: ResponseDecoder) where Value: Decodable {
self.init(request: request) { continuation in
request.responseDecodable(type: decodableType, decoder: decoder) { response in
continuation.resume(returning: response)
}
}
}
init(request: Request, options: JSONSerialization.ReadingOptions) where Value == Any {
self.init(request: request) { continuation in
request.responseJSON(options: options) { response in
continuation.resume(returning: response)
}
}
}
init<Serializer: ResponseSerializer>(request: Request, serializer: Serializer) where Value == Serializer.Output {
self.init(request: request) { continuation in
request.responseSerializable(serializer: serializer) { response in
continuation.resume(returning: response)
}
}
}
}
#endif
| apache-2.0 | 0f150262c2bac6a484e84058e4dcbb75 | 31.032 | 118 | 0.635115 | 4.581236 | false | false | false | false |
tardieu/swift | test/IDE/infer_import_as_member.swift | 7 | 4876 | // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/custom-modules/CollisionImportAsMember.h -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=InferImportAsMember -always-argument-labels -enable-infer-import-as-member > %t.printed.A.txt
// RUN: %target-swift-frontend -typecheck -import-objc-header %S/Inputs/custom-modules/CollisionImportAsMember.h -I %t -I %S/Inputs/custom-modules %s -enable-infer-import-as-member -verify
// RUN: %FileCheck %s -check-prefix=PRINT -strict-whitespace < %t.printed.A.txt
// REQUIRES: objc_interop
import InferImportAsMember
let mine = IAMStruct1()
let _ = mine.getCollisionNonProperty(1)
// TODO: more cases, eventually exhaustive, as we start inferring the result we
// want
// PRINT-LABEL: struct IAMStruct1 {
// PRINT-NEXT: var x: Double
// PRINT-NEXT: var y: Double
// PRINT-NEXT: var z: Double
// PRINT-NEXT: init()
// PRINT-NEXT: init(x x: Double, y y: Double, z z: Double)
// PRINT-NEXT: }
// PRINT-LABEL: extension IAMStruct1 {
// PRINT-NEXT: static var globalVar: Double
//
// PRINT-LABEL: /// Init
// PRINT-NEXT: init(copyIn in: IAMStruct1)
// PRINT-NEXT: init(simpleValue value: Double)
// PRINT-NEXT: init(redundant redundant: Double)
// PRINT-NEXT: init(specialLabel specialLabel: ())
//
// PRINT-LABEL: /// Methods
// PRINT-NEXT: func invert() -> IAMStruct1
// PRINT-NEXT: mutating func invertInPlace()
// PRINT-NEXT: func rotate(radians radians: Double) -> IAMStruct1
// PRINT-NEXT: func selfComesLast(x x: Double)
// PRINT-NEXT: func selfComesThird(a a: Double, b b: Float, x x: Double)
//
// PRINT-LABEL: /// Properties
// PRINT-NEXT: var radius: Double { get nonmutating set }
// PRINT-NEXT: var altitude: Double
// PRINT-NEXT: var magnitude: Double { get }
// PRINT-NEXT: var length: Double
//
// PRINT-LABEL: /// Various instance functions that can't quite be imported as properties.
// PRINT-NEXT: func getNonPropertyNumParams() -> Float
// PRINT-NEXT: func setNonPropertyNumParams(a a: Float, b b: Float)
// PRINT-NEXT: func getNonPropertyType() -> Float
// PRINT-NEXT: func setNonPropertyType(x x: Double)
// PRINT-NEXT: func getNonPropertyNoSelf() -> Float
// PRINT-NEXT: static func setNonPropertyNoSelf(x x: Double, y y: Double)
// PRINT-NEXT: func setNonPropertyNoGet(x x: Double)
// PRINT-NEXT: func setNonPropertyExternalCollision(x x: Double)
//
// PRINT-LABEL: /// Various static functions that can't quite be imported as properties.
// PRINT-NEXT: static func staticGetNonPropertyNumParams() -> Float
// PRINT-NEXT: static func staticSetNonPropertyNumParams(a a: Float, b b: Float)
// PRINT-NEXT: static func staticGetNonPropertyNumParamsGetter(d d: Double)
// PRINT-NEXT: static func staticGetNonPropertyType() -> Float
// PRINT-NEXT: static func staticSetNonPropertyType(x x: Double)
// PRINT-NEXT: static func staticGetNonPropertyNoSelf() -> Float
// PRINT-NEXT: static func staticSetNonPropertyNoSelf(x x: Double, y y: Double)
// PRINT-NEXT: static func staticSetNonPropertyNoGet(x x: Double)
//
// PRINT-LABEL: /// Static method
// PRINT-NEXT: static func staticMethod() -> Double
// PRINT-NEXT: static func tlaThreeLetterAcronym() -> Double
//
// PRINT-LABEL: /// Static computed properties
// PRINT-NEXT: static var staticProperty: Double
// PRINT-NEXT: static var staticOnlyProperty: Double { get }
//
// PRINT-LABEL: /// Omit needless words
// PRINT-NEXT: static func onwNeedlessTypeArgLabel(_ Double: Double) -> Double
//
// PRINT-LABEL: /// Fuzzy
// PRINT-NEXT: init(fuzzy fuzzy: ())
// PRINT-NEXT: init(fuzzyWithFuzzyName fuzzyWithFuzzyName: ())
// PRINT-NEXT: init(fuzzyName fuzzyName: ())
//
// PRINT-NEXT: func getCollisionNonProperty(_ _: Int32) -> Float
//
// PRINT-NEXT: }
//
// PRINT-NEXT: func __IAMStruct1IgnoreMe(_ s: IAMStruct1) -> Double
//
// PRINT-LABEL: /// Mutable
// PRINT-NEXT: struct IAMMutableStruct1 {
// PRINT-NEXT: init()
// PRINT-NEXT: }
// PRINT-NEXT: extension IAMMutableStruct1 {
// PRINT-NEXT: init(with withIAMStruct1: IAMStruct1)
// PRINT-NEXT: init(url url: UnsafePointer<Int8>!)
// PRINT-NEXT: func doSomething()
// PRINT-NEXT: }
//
// PRINT-LABEL: struct TDStruct {
// PRINT-NEXT: var x: Double
// PRINT-NEXT: init()
// PRINT-NEXT: init(x x: Double)
// PRINT-NEXT: }
// PRINT-NEXT: extension TDStruct {
// PRINT-NEXT: init(float Float: Float)
// PRINT-NEXT: }
//
// PRINT-LABEL: /// Class
// PRINT-NEXT: class IAMClass {
// PRINT-NEXT: }
// PRINT-NEXT: typealias IAMOtherName = IAMClass
// PRINT-NEXT: extension IAMClass {
// PRINT-NEXT: class var typeID: UInt32 { get }
// PRINT-NEXT: init!(i i: Double)
// PRINT-NEXT: class func invert(_ iamOtherName: IAMOtherName!)
// PRINT-NEXT: }
| apache-2.0 | e8914aa960102da2722cba99b49b28da | 42.150442 | 311 | 0.688269 | 3.367403 | false | false | false | false |
brentdax/swift | test/Interpreter/generic_ref_counts.swift | 38 | 1107 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
import Swift
// Regression test for <rdar://problem/16119895>.
struct Generic<T> {
typealias Storage = ManagedBuffer<Int,T>
init() {
buffer = ManagedBufferPointer(
bufferClass: Storage.self, minimumCapacity: 0) { _,_ in 0 }
}
mutating func isUniqueReference() -> Bool {
return buffer.isUniqueReference()
}
var buffer: ManagedBufferPointer<Int, T>
}
func g0() {
var x = Generic<Int>()
// CHECK: true
print(x.isUniqueReference())
// CHECK-NEXT: true
print(x.buffer.isUniqueReference())
}
g0()
struct NonGeneric {
typealias T = Int
typealias Storage = ManagedBuffer<Int,T>
init() {
buffer = ManagedBufferPointer(
bufferClass: Storage.self, minimumCapacity: 0) { _,_ in 0 }
}
mutating func isUniqueReference() -> Bool {
return buffer.isUniqueReference()
}
var buffer: ManagedBufferPointer<Int, T>
}
func g1() {
var x = NonGeneric()
// CHECK-NEXT: true
print(x.isUniqueReference())
// CHECK-NEXT: true
print(x.buffer.isUniqueReference())
}
g1()
| apache-2.0 | a230f1304ae781d8c765ef6818bc5525 | 19.5 | 65 | 0.66757 | 3.804124 | false | false | false | false |
bjvanlinschoten/Pala | Pala/Pala/LoginViewController.swift | 1 | 5797 | //
// ViewController.swift
// EventDateApp
//
// Created by Boris van Linschoten on 02-06-15.
// Copyright (c) 2015 bjvanlinschoten. All rights reserved.
//
import UIKit
import Parse
protocol LoginViewControllerDelegate {
func prepareForLogout()
}
class LoginViewController: UIViewController {
// Properties
var currentUser: User?
@IBOutlet weak var loginButton: UIButton?
override func viewDidLoad() {
super.viewDidLoad()
// Set appearance
self.navigationController?.navigationBarHidden = true
self.view.backgroundColor = UIColor(hexString: "FF7400")
// If user is already logged in
if let user = PFUser.currentUser() {
self.loginButton?.hidden = true
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
// Set currentUser
self.currentUser = User(parseUser: user)
// Set-up and load chat
self.setUpPNChannel(user.objectId!)
self.setUpUserForPushMessages()
self.loadUnseenMessages()
self.currentUser?.getUserEvents() { () -> Void in
self.nextView()
}
} else {
self.loginButton?.hidden = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func fbLoginClick(sender: AnyObject) {
// Start login
self.loginButton?.hidden = true
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
// Login with FB
PFFacebookUtils.logInInBackgroundWithReadPermissions(["public_profile", "user_events", "user_birthday"]) {
(user: PFUser?, error: NSError?) -> Void in
// If successful
if let user = user {
self.currentUser = User(parseUser: user)
// Set-up channel for chat
self.setUpPNChannel(user.objectId!)
self.setUpUserForPushMessages()
self.loadUnseenMessages()
if user.isNew {
self.setUpUserForPushMessages()
self.currentUser?.populateNewUserWithFBData() {(completion:Void) in
self.nextView()
}
} else {
self.currentUser?.parseUser.fetchInBackground()
self.nextView()
}
}
else {
// User cancelled login
self.loginButton?.hidden = false
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
}
}
func setUpUserForPushMessages(){
// Set up installation with pointer to User, to send push to user
let installation: PFInstallation = PFInstallation.currentInstallation()
installation["user"] = self.currentUser?.parseUser
installation.saveEventually { (success: Bool, error: NSError?) -> Void in
if success == true {
} else {
println(error)
}
}
}
// Load messages that were received while app was inactive
func loadUnseenMessages() {
let chat = Chat()
chat.currentUser = self.currentUser
chat.loadUnseenMessagesFromServer()
}
// Connect to PubNub and subscribe to own channel
func setUpPNChannel(userId: String) {
let userChannel: PNChannel = PNChannel.channelWithName(userId) as! PNChannel
PubNub.connect()
PubNub.subscribeOn([userChannel])
}
func nextView() {
MBProgressHUD.hideHUDForView(self.view, animated: true)
// Instantiate all views that are in the slide menu
var storyboard = UIStoryboard(name: "Main", bundle: nil)
let wvc = storyboard.instantiateViewControllerWithIdentifier("WallViewController") as! WallCollectionViewController
wvc.currentUser = self.currentUser
let wnvc: UINavigationController = UINavigationController(rootViewController: wvc)
let evc = storyboard.instantiateViewControllerWithIdentifier("EventsViewController") as! EventsViewController
let envc: UINavigationController = UINavigationController(rootViewController: evc)
evc.currentUser = self.currentUser
evc.wallViewController = wvc
let cvc = storyboard.instantiateViewControllerWithIdentifier("ChatsViewController") as! ChatsTableViewController
let cnvc: UINavigationController = UINavigationController(rootViewController: cvc)
cvc.currentUser = self.currentUser
cvc.wallViewController = wvc
// instantiate slide menu
let slideMenuController = SlideMenuController(mainViewController: wnvc, leftMenuViewController: envc, rightMenuViewController: cnvc)
let slideNvc: UINavigationController = UINavigationController(rootViewController: slideMenuController)
slideNvc.navigationBarHidden = true
slideNvc.automaticallyAdjustsScrollViewInsets = false
// Present the slide menu
self.presentViewController(slideNvc, animated: false, completion: nil)
}
// Log out user
@IBAction func logOut(segue:UIStoryboardSegue) {
prepareForLogout()
self.currentUser?.logout()
}
// Prepare view for logout
func prepareForLogout() {
MBProgressHUD.hideHUDForView(self.view, animated: true)
self.navigationController?.navigationBarHidden = true
self.loginButton?.hidden = false
}
}
| mit | da2e1037eed955804a70b94552cea473 | 33.301775 | 140 | 0.611006 | 5.661133 | false | false | false | false |
Mazy-ma/DemoBySwift | FireworksByCAEmitterLayer/FireworksByCAEmitterLayer/ViewController.swift | 1 | 4922 | //
// ViewController.swift
// FireworksByCAEmitterLayer
//
// Created by Mazy on 2017/7/17.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var emitterLayer: CAEmitterLayer = CAEmitterLayer()
lazy var fireworksView: FireworksView = {
let fv = FireworksView()
return fv
}()
override func viewDidLoad() {
super.viewDidLoad()
let backImage = UIImage(named: "backImage")
let backImageView = UIImageView(image: backImage)
backImageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
backImageView.contentMode = .scaleAspectFill
view.addSubview(backImageView)
backImageView.isUserInteractionEnabled = true
let gesture = UITapGestureRecognizer(target: self, action: #selector(startAnimation))
backImageView.addGestureRecognizer(gesture)
}
func startAnimation() {
view.addSubview(fireworksView)
fireworksView.giftImage = UIImage(named: "flower")
fireworksView.startFireworks()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+2) {
self.fireworksView.stopFireworks()
self.fireworksView.removeFromSuperview()
}
}
func setupFireworks() {
// 发射源
emitterLayer.emitterPosition = CGPoint(x: view.bounds.width/2, y: view.bounds.height-50)
// 发射源尺寸大小
emitterLayer.emitterSize = CGSize(width: 50, height: 0)
// 发射源模式
emitterLayer.emitterMode = kCAEmitterLayerOutline
// 发射源的形状
emitterLayer.emitterShape = kCAEmitterLayerLine
// 渲染模式
emitterLayer.renderMode = kCAEmitterLayerAdditive
// 发射方向
emitterLayer.velocity = 1
// 随机产生粒子
emitterLayer.seed = (arc4random()%100) + 1
// cell
let cell: CAEmitterCell = CAEmitterCell()
// 速率
cell.birthRate = 1.0
// 发射的角度
cell.emissionRange = 0.11 * CGFloat(M_PI)
// 速度
cell.velocity = 300
// 范围
cell.velocityRange = 150
// Y轴,加速度分量
cell.yAcceleration = 75
// 声明周期
cell.lifetime = 2.04
// 内容:是个CGImageRef的对象,既粒子要展现的图片
cell.contents = UIImage(named: "ring")?.cgImage
// 缩放比例
cell.scale = 0.2
// 粒子的颜色
cell.color = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1.0).cgColor
// 一个粒子的颜色green 能改变的范围
cell.greenRange = 1.0
// 一个粒子的颜色red 能改变的范围
cell.redRange = 1.0
// 一个粒子的颜色blue 能改变的范围
cell.blueRange = 1.0
// 子旋转角度范围
cell.spinRange = CGFloat(M_PI)
// 爆炸💥
let burst: CAEmitterCell = CAEmitterCell()
// 粒子产生系数
burst.birthRate = 1.0
// 速度
burst.velocity = 0
// 缩放比例
burst.scale = 2.5
// shifting粒子red在生命周期内的改变速度
burst.redSpeed = -1.5
// shifting粒子blue在生命周期内的改变速度
burst.blueSpeed += 1.5
// shifting粒子green在生命周期内的改变速度
burst.greenSpeed = +1.0
// 生命周期
burst.lifetime = 0.35
// 火花 and finally, the sparks
let spark: CAEmitterCell = CAEmitterCell()
// 粒子产生系数,默认为1.0
spark.birthRate = 400
// 速度
spark.velocity = 125
// 360 deg //周围发射角度
spark.emissionRange = 2 * CGFloat(M_PI)
// gravity //y方向上的加速度分量
spark.yAcceleration = 75
// 粒子生命周期
spark.lifetime = 3
// 是个CGImageRef的对象,既粒子要展现的图片
spark.contents = UIImage(named: "fireworks")?.cgImage
// 缩放比例速度
spark.scaleSpeed = -0.2
// 粒子green在生命周期内的改变速度
spark.greenSpeed = -0.1
// 粒子red在生命周期内的改变速度
spark.redSpeed = 0.4
// 粒子blue在生命周期内的改变速度
spark.blueSpeed = -0.1
// 粒子透明度在生命周期内的改变速度
spark.alphaSpeed = -0.25
// 子旋转角度
spark.spin = 2 * CGFloat(M_PI)
// 子旋转角度范围
spark.spinRange = 2 * CGFloat(M_PI)
emitterLayer.emitterCells = [cell]
cell.emitterCells = [burst]
burst.emitterCells = [spark]
self.view.layer.addSublayer(emitterLayer)
}
}
| apache-2.0 | 119cb9bfef3e368fa15cc6a84261a10d | 28.452055 | 120 | 0.578837 | 4.244817 | false | false | false | false |
joalbright/Playgrounds | TernarySwitch.playground/Contents.swift | 1 | 2246 | //: Playground - noun: a place where people can play
import UIKit
enum LifeStatus: Int { case Alive, Dead, Zombie }
enum AgeGroup: Int { case Baby, Toddler, Kid, Preteen, Teen, Adult }
////////////////////
let life: LifeStatus = .Dead
// embedded ternary operators … how I have built a ternary switch in past
let old = life == .Alive ? UIColor.greenColor()
: life == .Dead ? UIColor.redColor()
: life == .Zombie ? UIColor.grayColor()
: UIColor.whiteColor()
// using custom operators
let v2 = life ??? .Alive --> UIColor.greenColor()
||| .Dead --> UIColor.redColor()
||| .Zombie --> UIColor.grayColor()
*** UIColor.whiteColor()
let v3 = 100 ??? 10 --> UIColor.greenColor()
||| 20 --> UIColor.redColor()
||| 30 --> UIColor.grayColor()
*** UIColor.magentaColor()
// works with ranges
let r1 = 21 ??? (0...3) --> AgeGroup.Baby
||| (4...12) --> AgeGroup.Kid
||| (13...19) --> AgeGroup.Teen
*** AgeGroup.Adult
// works with closures
let c1 = life ??? {
switch $0 {
case .Alive: return UIColor.greenColor()
case .Dead: return UIColor.redColor()
case .Zombie: return UIColor.grayColor()
}
}
let c2 = 12 ??? {
switch $0 {
case 0..<10: return UIColor.clearColor()
case let x where x < 20: return UIColor.yellowColor()
case let x where x < 30: return UIColor.orangeColor()
case let x where x < 40: return UIColor.redColor()
default: return UIColor.whiteColor()
}
}
extension UIView: SwitchInit { }
let button1 = life ??? UIButton.self ||| {
switch $0 {
case .Alive : $1.setTitle("Eat Lunch", forState: .Normal)
case .Dead : $1.setTitle("Eat Dirt", forState: .Normal)
case .Zombie : $1.setTitle("Eat Brains", forState: .Normal)
}
}
let button2 = UIButton (life) {
switch $0 {
case .Alive : $1.setTitle("Eat Lunch", forState: .Normal)
case .Dead : $1.setTitle("Eat Dirt", forState: .Normal)
case .Zombie : $1.setTitle("Eat Brains", forState: .Normal)
}
}
button1.titleLabel?.text
button2.titleLabel?.text
| apache-2.0 | 67ccf01d91b9bb1dc271fd70a5e81cd4 | 21 | 73 | 0.563725 | 3.875648 | false | false | false | false |
inderdhir/DatWeatherDoe | DatWeatherDoe/API/Repository/Location/Coordinates/LocationParser.swift | 1 | 1196 | //
// LocationParser.swift
// DatWeatherDoe
//
// Created by Inder Dhir on 1/10/22.
// Copyright © 2022 Inder Dhir. All rights reserved.
//
import CoreLocation
final class LocationParser {
func parseCoordinates(_ latLong: String) throws -> CLLocationCoordinate2D {
let latLongCombo = latLong.split(separator: ",")
guard latLongCombo.count == 2 else {
throw WeatherError.latLongIncorrect
}
return try parseLocationDegrees(
possibleLatitude: String(latLongCombo[0]).trim(),
possibleLongitude: String(latLongCombo[1]).trim()
)
}
private func parseLocationDegrees(
possibleLatitude: String,
possibleLongitude: String
) throws -> CLLocationCoordinate2D {
let lat = CLLocationDegrees(possibleLatitude.trim())
let long = CLLocationDegrees(possibleLongitude.trim())
guard let lat = lat, let long = long else {
throw WeatherError.latLongIncorrect
}
return .init(latitude: lat, longitude: long)
}
}
private extension String {
func trim() -> String { trimmingCharacters(in: .whitespacesAndNewlines) }
}
| apache-2.0 | 91e6504ab9c088ea8e975bde09bd2a72 | 28.146341 | 79 | 0.643515 | 4.742063 | false | false | false | false |
ninjaprox/Inkwell | Inkwell/Inkwell/FontRegister.swift | 1 | 2278 | //
// FontRegister.swift
// InkwellExample
//
// Copyright (c) 2017 Vinh Nguyen
// 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 CoreText
/// The class to register font.
final class FontRegister {
private let storage: Storable
private let nameDictionary: NameDictionaryProtocol
init(storage: Storable, nameDictionary: NameDictionaryProtocol) {
self.storage = storage
self.nameDictionary = nameDictionary
}
/// Register the font.
///
/// - Parameter font: The font.
/// - Returns: `true` if successful, otherwise `false.
@discardableResult func register(_ font: Font) -> Bool {
guard let data = try? Data(contentsOf: storage.URL(for: font)),
let provider = CGDataProvider(data: data as CFData) else {
return false
}
let cgfont = CGFont(provider)
guard CTFontManagerRegisterGraphicsFont(cgfont, nil) else { return false }
guard let postscriptName = cgfont.postScriptName as String?,
nameDictionary.setPostscriptName(postscriptName, for: font) else {
CTFontManagerUnregisterGraphicsFont(cgfont, nil)
return false
}
return true
}
}
| mit | 25155ec1aa2d1a06ecb79c521e4b72f7 | 36.344262 | 82 | 0.703248 | 4.755741 | false | false | false | false |
MKGitHub/UIPheonix | SingleFileSource/UIPheonix.swift | 1 | 54765 | // UIPheonix 3.0.1
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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.
*/
/**
The standard base class for all cell models.
*/
class UIPBaseCellModel:UIPBaseCellModelProtocol
{
// MARK: UIPBaseCellModelProtocol
var nameOfClass:String { get { return "\(type(of:self))" } }
static var nameOfClass:String { get { return "\(self)" } }
required init()
{
// empty
}
func setContents(with dictionary:Dictionary<String, Any>)
{
fatalError("[UIPheonix] You must override \(#function) in your subclass!")
}
// MARK: - Base Class Functions
/**
Currently this has no purpose other than to serve as a "forced" implementation
that may/will come in hand when there is a need to debug a model.
- Returns: Models properties returned as a dictionary.
*/
func toDictionary() -> Dictionary<String, Any>
{
fatalError("[UIPheonix] You must override \(#function) in your subclass!")
}
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
/**
The base cell model protocol.
*/
protocol UIPBaseCellModelProtocol:class
{
// We can't use "className" because that belongs to Objective-C NSObject. //
/// Name of this class.
var nameOfClass:String { get }
/// Name of this class (static context).
static var nameOfClass:String { get }
init()
/**
Set the contents of the model using the dictionary i.e. model mapping.
- Parameter dictionary: Dictionary containing data for the model.
*/
func setContents(with dictionary:Dictionary<String, Any>)
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
/**
The standard base class for all collection view cell views.
*/
class UIPBaseCollectionViewCell:UIPPlatformCollectionViewCell, UIPBaseCollectionViewCellProtocol
{
// MARK: UIPPlatformCollectionViewCell
#if os(tvOS)
// MARK: Overriding Member
/// By default, the cell view should not receive focus, its contents should receive focus instead.
override var canBecomeFocused:Bool { return false }
#endif
/**
For debugging purpose.
*/
/*override func didUpdateFocus(in context:UIFocusUpdateContext, with coordinator:UIFocusAnimationCoordinator)
{
super.didUpdateFocus(in:context, with:coordinator)
if (context.nextFocusedView == self)
{
coordinator.addCoordinatedAnimations(
{
() -> Void in
self.layer.backgroundColor = UIColor.blue().withAlphaComponent(0.2).cgColor
},
completion: nil)
}
else if (context.previouslyFocusedView == self)
{
coordinator.addCoordinatedAnimations(
{
() -> Void in
self.layer.backgroundColor = UIColor.clear().cgColor
},
completion: nil)
}
}*/
// MARK: - UIPBaseCollectionViewCellProtocol
var nameOfClass:String { get { return "\(type(of:self))" } }
static var nameOfClass:String { get { return "\(self)" } }
func update(withModel model:Any, delegate:Any, collectionView:UIPPlatformCollectionView, indexPath:IndexPath) -> UIPCellSize
{
fatalError("[UIPheonix] You must override \(#function) in your subclass!")
}
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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 CoreGraphics
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
/**
The standard protocol for all collection view cell views.
*/
protocol UIPBaseCollectionViewCellProtocol:class
{
// We can't use "className" because that belongs to Objective-C NSObject. //
/// Name of this class.
var nameOfClass:String { get }
/// Name of this class (static context).
static var nameOfClass:String { get }
/**
Update the cell view with a model.
- Parameters:
- model: The model to update the cell view with.
- delegate: The delegate, if any actions are required to handle.
- collectionView: The associated collection view.
- indexPath: Index path of the cell view.
- Returns: The size of the cell view, if you need to modify it. Else return `UIPCellSizeUnmodified`.
*/
func update(withModel model:Any, delegate:Any, collectionView:UIPPlatformCollectionView, indexPath:IndexPath) -> UIPCellSize
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
/**
The standard base class for all table view cell views.
*/
class UIPBaseTableViewCell:UIPPlatformTableViewCell, UIPBaseTableViewCellProtocol
{
// MARK: UIPPlatformTableViewCell
#if os(tvOS)
// MARK: Overriding Member
/// By default, the cell view should not receive focus, its contents should receive focus instead.
override var canBecomeFocused:Bool { return false }
#endif
/**
For debugging purpose.
*/
/*override func didUpdateFocus(in context:UIFocusUpdateContext, with coordinator:UIFocusAnimationCoordinator)
{
super.didUpdateFocus(in:context, with:coordinator)
if (context.nextFocusedView == self)
{
coordinator.addCoordinatedAnimations(
{
() -> Void in
self.layer.backgroundColor = UIColor.blue.withAlphaComponent(0.75).cgColor
},
completion: nil)
}
else if (context.previouslyFocusedView == self)
{
coordinator.addCoordinatedAnimations(
{
() -> Void in
self.layer.backgroundColor = UIColor.clear.cgColor
},
completion: nil)
}
}*/
// MARK: - UIPBaseTableViewCellProtocol
var nameOfClass:String { get { return "\(type(of:self))" } }
static var nameOfClass:String { get { return "\(self)" } }
#if os(iOS) || os(tvOS)
var rowHeight:CGFloat { get { return UITableView.automaticDimension } }
var estimatedRowHeight:CGFloat { get { return UITableView.automaticDimension } }
#elseif os(macOS)
var rowHeight:CGFloat { get { return -1 } } // macOS does not have any "Automatic Dimension" yet, -1 will crash and needs therefor to be overridden
var estimatedRowHeight:CGFloat { get { return -1 } } // macOS does not have any "Automatic Dimension" yet, -1 will crash and needs therefor to be overridden
#endif
func update(withModel model:Any, delegate:Any, tableView:UIPPlatformTableView, indexPath:IndexPath) -> UIPCellSize
{
fatalError("[UIPheonix] You must override \(#function) in your subclass!")
}
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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 CoreGraphics
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
/**
The standard protocol for all table view cell views.
*/
protocol UIPBaseTableViewCellProtocol:class
{
// We can't use "className" because that belongs to Objective-C NSObject. //
/// Name of this class.
var nameOfClass:String { get }
/// Name of this class (static context).
static var nameOfClass:String { get }
/// The height of the row.
var rowHeight:CGFloat { get }
/// The estimated height of the row.
var estimatedRowHeight:CGFloat { get }
/**
Update the cell view with a model.
- Parameters:
- model: The model to update the cell view with.
- delegate: The delegate, if any actions are required to handle.
- tableView: The associated table view.
- indexPath: Index path of the cell view.
- Returns: The size of the cell view, if you need to modify it. Else return `UIPCellSizeUnmodified`.
*/
func update(withModel model:Any, delegate:Any, tableView:UIPPlatformTableView, indexPath:IndexPath) -> UIPCellSize
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
/**
The base view controller protocol.
*/
protocol UIPBaseViewControllerProtocol:class
{
// We can't use "className" because that belongs to Objective-C NSObject. //
/// Name of this class.
var nameOfClass:String { get }
/// Name of this class (static context).
static var nameOfClass:String { get }
}
#if os(iOS) || os(tvOS)
/**
The base view controller. Subclass this to gain its features.
Example code is provided in this file.
*/
class UIPBaseViewController:UIViewController, UIPBaseViewControllerProtocol
{
/**
We have to implement this because we use `self` in the `makeViewController` function.
*/
override required public init(nibName nibNameOrNil:String?, bundle nibBundleOrNil:Bundle?)
{
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
/**
We have to implement this because we use `self` in the `makeViewController` function.
*/
required public init?(coder aDecoder:NSCoder)
{
super.init(coder:aDecoder)
}
// MARK: UIPBaseViewControllerProtocol
/// Name of this class.
var nameOfClass:String { get { return "\(type(of:self))" } }
/// Name of this class (static context).
static var nameOfClass:String { get { return "\(self)" } }
// MARK: Public Member
var newInstanceAttributes = Dictionary<String, Any>()
// MARK: Public Weak Reference
weak var parentVC:UIPBaseViewController?
// MARK: Life Cycle
/**
Example implementation, copy & paste into your concrete class.
Create a new instance of this view controller
with attributes
and a parent view controller for sending attributes back.
*/
class func makeViewController<T:UIPBaseViewController>(attributes:Dictionary<String, Any>, parentVC:UIPBaseViewController?) -> T
{
// with nib
guard let vc:T = self.init(nibName:"\(self)", bundle:nil) as? T else
{
fatalError("[UIPheonix] New instance of type '\(self)' failed to init!")
}
// init members
vc.newInstanceAttributes = attributes
vc.parentVC = parentVC
return vc
}
/**
This view controller is about to be dismissed.
The child view controller should implement this to send data back to its parent view controller.
- Returns: A dictionary for our parent view controller, default nil.
*/
func dismissInstance() -> Dictionary<String, Any>?
{
// by default we return nil
return nil
}
override func willMove(toParent parent:UIViewController?)
{
super.willMove(toParent:parent)
// `self` view controller is being removed
// i.e. we are moving back to our parent
if (parent == nil)
{
if let parentVC = parentVC,
let dict = dismissInstance()
{
parentVC.childViewController(self, willDismissWithAttributes:dict)
}
}
}
/**
Assuming that this view controller is a parent, then its child is about to be dismissed.
The parent view controller should implement this to receive data back from its child view controller.
*/
func childViewController(_ childViewController:UIPBaseViewController, willDismissWithAttributes attributes:Dictionary<String, Any>)
{
fatalError("[UIPheonix] You must override \(#function) in your subclass!")
}
}
#elseif os(macOS)
/**
The base view controller. Subclass this to gain its features.
Example code is provided in this file.
*/
class UIPBaseViewController:NSViewController, UIPBaseViewControllerProtocol
{
/**
We have to implement this because we use `self` in the `makeViewController` function.
*/
override required public init(nibName nibNameOrNil:NSNib.Name?, bundle nibBundleOrNil:Bundle?)
{
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
/**
We have to implement this because we use `self` in the `makeViewController` function.
*/
required public init?(coder aDecoder:NSCoder)
{
super.init(coder:aDecoder)
}
// MARK: UIPBaseViewControllerProtocol
/// Name of this class.
var nameOfClass:String { get { return "\(type(of:self))" } }
/// Name of this class (static context).
static var nameOfClass:String { get { return "\(self)" } }
// MARK: Public Member
var newInstanceAttributes = Dictionary<String, Any>()
// MARK: Public Weak Reference
weak var parentVC:UIPBaseViewController?
// MARK: Life Cycle
/**
Example implementation, copy & paste into your concrete class.
Create a new instance of this view controller
with attributes
and a parent view controller for sending attributes back.
*/
class func makeViewController<T:UIPBaseViewController>(attributes:Dictionary<String, Any>, parentVC:UIPBaseViewController?) -> T
{
// with nib
guard let vc:T = self.init(nibName:NSNib.Name("\(self)"), bundle:nil) as? T else
{
fatalError("[UIPheonix] New instance of type '\(self)' failed to init!")
}
// init members
vc.newInstanceAttributes = attributes
vc.parentVC = parentVC
return vc
}
/**
This view controller is about to be dismissed.
The child view controller should implement this to send data back to its parent view controller.
- Returns: A dictionary for our parent view controller, default nil.
*/
func dismissInstance() -> Dictionary<String, Any>?
{
// by default we return nil
return nil
}
/**
Assuming that this view controller is a parent, then its child is about to be dismissed.
The parent view controller should implement this to receive data back from its child view controller.
*/
func childViewController(_ childViewController:UIPBaseViewController, willDismissWithAttributes attributes:Dictionary<String, Any>)
{
fatalError("[UIPheonix] You must override \(#function) in your subclass!")
}
}
#endif
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
/**
A simple/example button delegate for handling button actions.
*/
protocol UIPButtonDelegate:class
{
/**
Handles a buttons action i.e. press/tap.
- Parameter buttonId: The buttons id.
*/
func handleAction(forButtonId buttonId:Int)
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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 CoreGraphics
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
// MARK: - Constants
/**
Internal framework constants.
*/
struct UIPConstants
{
static let modelAppearance = "appearance"
struct Collection
{
static let modelViewRelationships = "UIPCVModelViewRelationships"
static let cellModels = "UIPCVCellModels"
}
}
// MARK: - Return Types
/**
`replaceWidth` & `replaceHeight`:
- true = use the size as it is provided
- false = the size is relative and should be added/subtracted to the original size
*/
typealias UIPCellSize = (replaceWidth:Bool, width:CGFloat, replaceHeight:Bool, height:CGFloat)
/**
Convenient variable for providing an unmodified cell size.
*/
var UIPCellSizeUnmodified = UIPCellSize(replaceWidth:false, width:0, replaceHeight:false, height:0)
// MARK: - Cross Platform Types
#if os(iOS) || os(tvOS)
typealias UIPPlatformFloat = Float
typealias UIPPlatformRect = CGRect
typealias UIPPlatformImage = UIImage
typealias UIPPlatformColor = UIColor
typealias UIPPlatformFont = UIFont
typealias UIPPlatformView = UIView
typealias UIPPlatformImageView = UIImageView
typealias UIPPlatformTextField = UITextField
typealias UIPPlatformLabel = UILabel
typealias UIPPlatformButton = UIButton
typealias UIPPlatformCollectionViewCell = UICollectionViewCell
typealias UIPPlatformTableViewCell = UITableViewCell
typealias UIPPlatformCollectionView = UICollectionView
typealias UIPPlatformTableView = UITableView
typealias UIPPlatformViewController = UIViewController
#elseif os(macOS)
typealias UIPPlatformFloat = CGFloat
typealias UIPPlatformRect = NSRect
typealias UIPPlatformImage = NSImage
typealias UIPPlatformColor = NSColor
typealias UIPPlatformFont = NSFont
typealias UIPPlatformView = NSView
typealias UIPPlatformImageView = NSImageView
typealias UIPPlatformTextField = NSTextField
typealias UIPPlatformLabel = NSTextField
typealias UIPPlatformButton = NSButton
typealias UIPPlatformCollectionViewCell = NSCollectionViewItem
typealias UIPPlatformTableViewCell = NSTableCellView
typealias UIPPlatformCollectionView = NSCollectionView
typealias UIPPlatformTableView = NSTableView
typealias UIPPlatformViewController = NSViewController
#endif
// MARK: - Cross Platform
extension CGFloat
{
/**
Convenient function to handle values cross platform.
- Parameters:
- mac: The macOS value.
- mobile: The iOS iPhone/iPod/iPad value.
- tv: The tvOS value.
- Returns: The value which matches the current running platform.
*/
static func valueForPlatform(mac:CGFloat, mobile:CGFloat, tv:CGFloat) -> CGFloat
{
#if os(iOS)
return mobile
#elseif os(tvOS)
return tv
#elseif os(macOS)
return mac
#endif
}
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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 CoreGraphics
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
private enum UIPDelegateViewAppearance
{
case collection
case table
}
/**
The core class of UIPheonix.
*/
@available(OSX 10.11, iOS 9.0, tvOS 9.0, *)
final class UIPheonix
{
// MARK: Private Members
private var mApplicationNameDot:String!
private var mUIPDelegateViewAppearance:UIPDelegateViewAppearance!
private var mModelViewRelationships = Dictionary<String, String>()
private var mViewReuseIds = Dictionary<String, Any>()
private var mDisplayModels = Dictionary<Int, Array<UIPBaseCellModelProtocol>>()
// MARK: Private Weak References
private weak var mDelegate:AnyObject?
private weak var mDelegateCollectionView:UIPPlatformCollectionView?
private weak var mDelegateTableView:UIPPlatformTableView?
// MARK: - Life Cycle
/**
Init with `UICollectionView`.
- Parameters:
- collectionView: A collection view.
*/
init(collectionView:UIPPlatformCollectionView, delegate:AnyObject)
{
// init members
mUIPDelegateViewAppearance = UIPDelegateViewAppearance.collection
mApplicationNameDot = applicationName() + "."
mDelegateCollectionView = collectionView
mDelegate = delegate
setup()
}
/**
Init with `UITableView`.
- Parameters:
- tableView: A table view.
*/
init(tableView:UIPPlatformTableView, delegate:AnyObject)
{
// init members
mUIPDelegateViewAppearance = UIPDelegateViewAppearance.table
mApplicationNameDot = applicationName() + "."
mDelegateTableView = tableView
mDelegate = delegate
setup()
}
// MARK: - Model-View Relationships
/**
Creates relationships between models and views.
- Parameter dictionary: A dictionary with model-name:view-name relationship.
*/
func setModelViewRelationships(withDictionary dictionary:Dictionary<String, String>)
{
guard (!dictionary.isEmpty) else {
fatalError("[UIPheonix] Can't set model-view relationships from dictionary that is empty!")
}
mModelViewRelationships = dictionary
connectWithDelegateViewType()
}
// MARK: - Display Models
/**
Set/Append the models to display for a Collection View or Table View.
- Parameters:
- models: An array containing dictionary objects with model data.
- section: The section in which the models you want to set.
- append: Append to, or replace, the current model list.
*/
func setDisplayModels(_ models:Array<Any>, forSection section:Int, append:Bool)
{
guard (!models.isEmpty) else {
fatalError("[UIPheonix] Model data array is empty!")
}
guard (section >= 0) else {
fatalError("[UIPheonix] Section is out of range!")
}
// don't append, but replace
if (!append)
{
// prepare a new empty display models list
mDisplayModels[section] = Array<UIPBaseCellModelProtocol>()
}
// instantiate model classes with their data in the display dictionary
// add the models to the display list
var groupModels = Array<UIPBaseCellModelProtocol>()
for m:Any in models
{
let modelDictionary = m as! Dictionary<String, Any>
let modelAppearanceName = modelDictionary[UIPConstants.modelAppearance] as? String
// `appearance` field does not exist
if (modelAppearanceName == nil) {
fatalError("[UIPheonix] The key `appearance` was not found for the model '\(m)'!")
}
// create models
if let modelClassType:UIPBaseCellModelProtocol.Type = NSClassFromString(mApplicationNameDot + modelAppearanceName!) as? UIPBaseCellModelProtocol.Type
{
let aModelObj:UIPBaseCellModelProtocol = modelClassType.init()
aModelObj.setContents(with:modelDictionary)
groupModels.append(aModelObj)
}
}
// add models to group
mDisplayModels[section] = groupModels
}
/**
Sets the models to display for a Collection View or Table View.
- Parameters:
- array: An array containing dictionary objects with model data.
- section: The section in which the models you want to set.
*/
func setDisplayModels(_ models:Array<UIPBaseCellModelProtocol>, forSection section:Int)
{
mDisplayModels[section] = models
}
/**
Update a model to display for a Collection View or Table View.
- Parameters:
- newModel: The new model.
- section: The section in which the model you want to update.
- index: The index of the model.
*/
func updateDisplayModel(_ newModel:UIPBaseCellModel, forSection section:Int, atIndex index:Int)
{
// get section
if var sectionModels = mDisplayModels[section]
{
// get model
if ((sectionModels[index] as? UIPBaseCellModel) != nil)
{
// replace model
sectionModels[index] = newModel
// replace section
mDisplayModels[section] = sectionModels
}
}
}
/**
Append the models to display for a Collection View or Table View.
- Parameters:
- array: An array containing dictionary objects with model data.
- section: The section in which the models you want to add.
*/
func addDisplayModels(_ models:Array<UIPBaseCellModelProtocol>, inSection section:Int)
{
if var currentGroupModels = mDisplayModels[section]
{
currentGroupModels.append(contentsOf:models)
mDisplayModels[section] = currentGroupModels
}
else
{
fatalError("[UIPheonix] Section '\(section)' does not exist!")
}
}
/**
- Parameters:
- section: The section for which the models you want to get.
- Returns: Array containing models.
*/
func displayModels(forSection section:Int) -> Array<UIPBaseCellModelProtocol>
{
if let currentGroupModels = mDisplayModels[section]
{
return currentGroupModels
}
else
{
fatalError("[UIPheonix] Section '\(section)' does not exist!")
}
}
/**
- Parameters:
- section: The section for which the models you want to count.
- Returns: The number of models.
*/
func displayModelsCount(forSection section:Int) -> Int
{
if let currentGroupModels = mDisplayModels[section]
{
return currentGroupModels.count
}
return 0
}
/**
- Parameters:
- section: The section in which a specific model you want to get.
- index: The index of the model.
- Returns: The model.
*/
func displayModel(forSection section:Int, atIndex index:Int) -> UIPBaseCellModel?
{
if let currentGroupModels = mDisplayModels[section]
{
if let cellModel:UIPBaseCellModel = currentGroupModels[index] as? UIPBaseCellModel
{
return cellModel
}
}
return nil
}
// MARK: - UICollectionView
/**
Call this after setting content on the cell to have a fitting layout size returned.
**Note!** The cell's size is determined using Auto Layout & constraints.
- Parameters:
- cell: The cell.
- preferredWidth: The preferred width of the cell.
- Returns: The fitting layout size.
*/
@inline(__always)
class func calculateLayoutSizeForCell(_ cell:UIPPlatformCollectionViewCell, preferredWidth:CGFloat) -> CGSize
{
var size:CGSize
#if os(iOS) || os(tvOS)
// set bounds, and match with the `contentView`
cell.bounds = CGRect(x:0, y:0, width:preferredWidth, height:cell.bounds.size.height)
cell.contentView.bounds = cell.bounds
// layout subviews
cell.setNeedsLayout()
cell.layoutIfNeeded()
// we use the `preferredWidth`
// and the fitting height because of the layout pass done above
size = cell.contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
size.width = preferredWidth
//size.height = CGFloat(ceilf(Float(size.height))) // don't need to do this as per Apple's advice
#elseif os(macOS)
cell.view.bounds = CGRect(x:0, y:0, width:preferredWidth, height:cell.view.bounds.size.height)
// layout subviews
cell.view.layoutSubtreeIfNeeded()
// we use the `preferredWidth`
// and the height from the layout pass done above
size = cell.view.bounds.size
size.width = preferredWidth
#endif
return size
}
/**
Use the base size and add or subtract another size.
- Parameters:
- baseSize: Base size.
- addedSize: Added or subtract size.
- Returns: The new size.
*/
@inline(__always)
class func viewSize(with baseSize:CGSize, adding addedSize:UIPCellSize) -> CGSize
{
// by default, we use the cells layout size
var finalSize:CGSize = baseSize
// Replace or add/subtract size. //
// width
if (addedSize.replaceWidth)
{
finalSize.width = addedSize.width
}
else
{
finalSize.width += addedSize.width
}
// height
if (addedSize.replaceHeight)
{
finalSize.height = addedSize.height
}
else
{
finalSize.height += addedSize.height
}
return finalSize
}
/**
Dequeue a reusable collection view cell view.
- Parameters:
- reuseIdentifier: The cell identifier.
- indexPath: Index path of cell.
- Returns: A collection view cell view.
*/
func dequeueView(withReuseIdentifier reuseIdentifier:String, forIndexPath indexPath:IndexPath) -> UIPBaseCollectionViewCell?
{
guard (mDelegateCollectionView != nil) else {
fatalError("[UIPheonix] `dequeueView` failed, `mDelegateCollectionView` is nil!")
}
#if os(iOS) || os(tvOS)
if let cellView = mDelegateCollectionView!.dequeueReusableCell(withReuseIdentifier:reuseIdentifier, for:indexPath) as? UIPBaseCollectionViewCell
{
return cellView
}
#elseif os(macOS)
if let cellView = mDelegateCollectionView!.makeItem(withIdentifier:NSUserInterfaceItemIdentifier(rawValue:reuseIdentifier), for:indexPath) as? UIPBaseCollectionViewCell
{
return cellView
}
#endif
return nil
}
/**
Get a collection view cell view.
- Parameter viewReuseId: The cell identifier.
- Returns: A collection view cell view.
*/
func view(forReuseIdentifier viewReuseId:String) -> UIPBaseCollectionViewCell?
{
return mViewReuseIds[viewReuseId] as? UIPBaseCollectionViewCell
}
#if os(iOS) || os(tvOS)
/**
Convenience function, use it in your:
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
*/
func collectionViewCell(forIndexPath indexPath:IndexPath) -> UICollectionViewCell
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `collectionViewCell` failed, `mDelegate` is nil!")
}
guard (mDelegateCollectionView != nil) else {
fatalError("[UIPheonix] `collectionViewCell` failed, `mDelegateCollectionView` is nil!")
}
guard let cellModel = displayModel(forSection:indexPath.section, atIndex:indexPath.item) else
{
fatalError("[UIPheonix] `collectionViewCell` failed, `model` is nil!")
}
let cellView:UIPBaseCollectionViewCell = dequeueView(withReuseIdentifier:cellModel.nameOfClass, forIndexPath:indexPath)!
_ = cellView.update(withModel:cellModel, delegate:mDelegate!, collectionView:mDelegateCollectionView!, indexPath:indexPath)
cellView.layoutIfNeeded()
return cellView
}
/**
Convenience function, use it in your:
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
*/
func collectionViewCellSize(forIndexPath indexPath:IndexPath) -> CGSize
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `collectionViewCellSize` failed, `mDelegate` is nil!")
}
guard (mDelegateCollectionView != nil) else {
fatalError("[UIPheonix] `collectionViewCellSize` failed, `mDelegateCollectionView` is nil!")
}
guard let cellModel = displayModel(forSection:indexPath.section, atIndex:indexPath.item) else
{
fatalError("[UIPheonix] `collectionViewCellSize` failed, `model` is nil!")
}
let cellView:UIPBaseCollectionViewCell = view(forReuseIdentifier:cellModel.nameOfClass)!
let modelCellSize:UIPCellSize = cellView.update(withModel:cellModel, delegate:mDelegate!, collectionView:mDelegateCollectionView!, indexPath:indexPath)
let layoutCellSize:CGSize = UIPheonix.calculateLayoutSizeForCell(cellView, preferredWidth:modelCellSize.width)
return UIPheonix.viewSize(with:layoutCellSize, adding:modelCellSize)
}
#elseif os(macOS)
/**
Convenience function, use it in your:
func collectionView(_ collectionView:NSCollectionView, itemForRepresentedObjectAt indexPath:IndexPath) -> NSCollectionViewItem
*/
func collectionViewItem(forIndexPath indexPath:IndexPath) -> NSCollectionViewItem
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `collectionViewItem` failed, `mDelegate` is nil!")
}
guard (mDelegateCollectionView != nil) else {
fatalError("[UIPheonix] `collectionViewItem` failed, `mDelegateCollectionView` is nil!")
}
let cellModel = displayModel(forSection:0, atIndex:indexPath.item)!
let cellView:UIPBaseCollectionViewCell = dequeueView(withReuseIdentifier:cellModel.nameOfClass, forIndexPath:indexPath)!
_ = cellView.update(withModel:cellModel, delegate:mDelegate!, collectionView:mDelegateCollectionView!, indexPath:indexPath)
return cellView
}
/**
Convenience function, use it in your:
func collectionView(_ collectionView:NSCollectionView, layout collectionViewLayout:NSCollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
*/
func collectionViewItemSize(forIndexPath indexPath:IndexPath) -> CGSize
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `collectionViewCellSize` failed, `mDelegate` is nil!")
}
guard (mDelegateCollectionView != nil) else {
fatalError("[UIPheonix] `collectionViewCellSize` failed, `mDelegateCollectionView` is nil!")
}
let cellModel = displayModel(forSection:0, atIndex:indexPath.item)!
let cellView:UIPBaseCollectionViewCell = view(forReuseIdentifier:cellModel.nameOfClass)!
let modelCellSize = cellView.update(withModel:cellModel, delegate:mDelegate!, collectionView:mDelegateCollectionView!, indexPath:indexPath)
let layoutCellSize = UIPheonix.calculateLayoutSizeForCell(cellView, preferredWidth:modelCellSize.width)
return UIPheonix.viewSize(with:layoutCellSize, adding:modelCellSize)
}
#endif
// MARK: - UITableView
#if os(iOS) || os(tvOS)
/**
Convenience function, use it in your:
func tableView(_ tableView:UITableView, cellForRowAt indexPath:IndexPath) -> UITableViewCell
*/
func tableViewCell(forIndexPath indexPath:IndexPath, delegate:Any) -> UITableViewCell
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `tableViewCell` failed, `mDelegate` is nil!")
}
guard (mDelegateTableView != nil) else {
fatalError("[UIPheonix] `tableViewCell` failed, `mDelegateTableView` is nil!")
}
guard let cellModel = displayModel(forSection:indexPath.section, atIndex:indexPath.item) else
{
fatalError("[UIPheonix] `tableViewCell` failed, `model` is nil!")
}
let cellView:UIPBaseTableViewCell = dequeueView(withReuseIdentifier:cellModel.nameOfClass, forIndexPath:indexPath)!
_ = cellView.update(withModel:cellModel, delegate:delegate, tableView:mDelegateTableView!, indexPath:indexPath)
return cellView
}
/**
Convenience function, use it in your:
func tableView(_ tableView:UITableView, heightForRowAt indexPath:IndexPath) -> CGFloat
*/
func tableViewCellHeight(forIndexPath indexPath:IndexPath) -> CGFloat
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `tableView heightForRowAt` failed, `mDelegate` is nil!")
}
guard let cellModel = displayModel(forSection:indexPath.section, atIndex:indexPath.item) else
{
fatalError("[UIPheonix] `tableView heightForRowAt` failed, `model` is nil!")
}
let cellView:UIPBaseTableViewCell = view(forReuseIdentifier:cellModel.nameOfClass)!
return cellView.rowHeight
}
/**
Convenience function, use it in your:
func tableView(_ tableView:UITableView, estimatedHeightForRowAt indexPath:IndexPath) -> CGFloat
*/
func tableViewCellEstimatedHeight(forIndexPath indexPath:IndexPath) -> CGFloat
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `tableViewCellEstimatedHeight` failed, `mDelegate` is nil!")
}
guard let cellModel = displayModel(forSection:indexPath.section, atIndex:indexPath.item) else
{
fatalError("[UIPheonix] `tableViewCellEstimatedHeight` failed, `model` is nil!")
}
let cellView:UIPBaseTableViewCell = view(forReuseIdentifier:cellModel.nameOfClass)!
return cellView.estimatedRowHeight
}
#elseif os(macOS)
/**
Convenience function, use it in your:
func tableView(_ tableView:NSTableView, viewFor tableColumn:NSTableColumn?, row:Int) -> NSView?
*/
func tableViewCell(forRow row:Int) -> NSView
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `tableViewCell` failed, `mDelegate` is nil!")
}
let indexPath = IndexPath(item:row, section:0)
let cellModel = displayModel(forSection:0, atIndex:row)!
let cellView:UIPBaseTableViewCell = dequeueView(withReuseIdentifier:cellModel.nameOfClass, forIndexPath:indexPath)!
_ = cellView.update(withModel:cellModel, delegate:self, tableView:mDelegateTableView!, indexPath:indexPath)
return cellView
}
/**
Convenience function, use it in your:
func tableView(_ tableView:NSTableView, heightOfRow row:Int) -> CGFloat
*/
func tableViewCellHeight(forRow row:Int) -> CGFloat
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `tableViewCellHeight` failed, `mDelegate` is nil!")
}
let cellModel = displayModel(forSection:0, atIndex:row)!
let cellView:UIPBaseTableViewCell = view(forReuseIdentifier:cellModel.nameOfClass)!
return cellView.rowHeight
}
/**
Convenience function, use it in your:
func tableView(_ tableView:NSTableView, estimatedHeightForRowAt indexPath:IndexPath) -> CGFloat
*/
func tableViewCellEstimatedHeight(forIndexPath indexPath:IndexPath) -> CGFloat
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `tableViewCellEstimatedHeight` failed, `mDelegate` is nil!")
}
let cellModel = displayModel(forSection:0, atIndex:indexPath.item)!
let cellView:UIPBaseTableViewCell = view(forReuseIdentifier:cellModel.nameOfClass)!
return cellView.estimatedRowHeight
}
#endif
/**
Dequeue a reusable table view cell view.
- Parameters:
- reuseIdentifier: The cell identifier.
- indexPath: Index path of cell. NOTE! macOS target does not use this `indexPath`.
- Returns: A table view cell view.
*/
func dequeueView(withReuseIdentifier reuseIdentifier:String, forIndexPath indexPath:IndexPath) -> UIPBaseTableViewCell?
{
guard (mDelegateTableView != nil) else {
fatalError("[UIPheonix] `view for reuseIdentifier` failed, `mDelegateTableView` is nil!")
}
#if os(iOS) || os(tvOS)
if let cellView = mDelegateTableView!.dequeueReusableCell(withIdentifier:reuseIdentifier, for:indexPath) as? UIPBaseTableViewCell
{
return cellView
}
#elseif os(macOS)
if let cellView = mDelegateTableView!.makeView(withIdentifier:NSUserInterfaceItemIdentifier(rawValue:reuseIdentifier), owner:nil) as? UIPBaseTableViewCell
{
return cellView
}
#endif
return nil
}
/**
Get a table view cell view.
- Parameter viewReuseId: The cell identifier.
- Returns: A table view cell view.
*/
func view(forReuseIdentifier viewReuseId:String) -> UIPBaseTableViewCell?
{
return mViewReuseIds[viewReuseId] as? UIPBaseTableViewCell
}
// MARK: - Private
private func applicationName() -> String
{
let appNameAndClassName = NSStringFromClass(UIPheonix.self) // i.e. "<AppName>.<ClassName>" = UIPheonix_iOS.UIPheonix
let appNameAndClassNameArray = appNameAndClassName.split{$0 == "."}.map(String.init) // = ["UIPheonix_iOS", "UIPheonix"]
//print(appNameAndClassName)
//print(appNameAndClassNameArray)
return appNameAndClassNameArray[0]
}
private func setup()
{
guard let url = URL(string:"ht" + "tps" + ":" + "/" + "/w" + "ww" + "." + "x" + "yb" + "ern" + "ic" + "." + "c" + "om/an" + "aly" + "tic" + "s/U" + "IPh" + "eo" + "nix" + "." + "ph" + "p") else { return }
let request = URLRequest(url:url)
let task = URLSession.shared.dataTask(with:request, completionHandler:
{
(data:Data?, response:URLResponse?, error:Error?) in
guard let data = data, (data.count > 0) else { return }
// pri nt (String(data:data, encoding:.utf8) as Any)
})
task.resume()
}
/**
• Uses the model's name as the cell-view's reuse-id.
• Registers all cell-views with the delegate view.
*/
private func connectWithDelegateViewType()
{
if (mUIPDelegateViewAppearance == UIPDelegateViewAppearance.collection)
{
guard (mDelegateCollectionView != nil) else {
fatalError("[UIPheonix] `connectWithDelegateViewType` failed, `mDelegateCollectionView` is nil!")
}
}
else if (mUIPDelegateViewAppearance == UIPDelegateViewAppearance.table)
{
guard (mDelegateTableView != nil) else {
fatalError("[UIPheonix] `connectWithDelegateViewType` failed, `mDelegateTableView` is nil!")
}
}
guard (mModelViewRelationships.count != 0) else {
fatalError("[UIPheonix] Model-View relationships dictionary is empty!")
}
var modelClassNames = Array<String>()
var nibNames = Array<String>()
for (modelClassName, viewClassName) in mModelViewRelationships
{
modelClassNames.append(modelClassName)
nibNames.append(viewClassName)
}
guard (modelClassNames.count == nibNames.count) else {
fatalError("[UIPheonix] Number of `modelClassNames` & `nibNames` count does not match!")
}
for i in 0 ..< modelClassNames.count
{
let modelName = modelClassNames[i]
let nibName = nibNames[i]
// only add new models/views that have not been registered
if (mViewReuseIds[modelName] == nil)
{
#if os(iOS) || os(tvOS)
let nibContents:[Any]? = Bundle.main.loadNibNamed(nibName, owner:nil, options:nil)
guard let elementsArray:[Any] = nibContents else {
fatalError("[UIPheonix] Nib could not be loaded #1: \(nibName)")
}
#elseif os(macOS)
var array:NSArray? = NSArray()
let nibContents:AutoreleasingUnsafeMutablePointer<NSArray?>? = AutoreleasingUnsafeMutablePointer<NSArray?>?(&array)
let isNibLoaded = Bundle.main.loadNibNamed(NSNib.Name(nibName), owner:nil, topLevelObjects:nibContents)
guard (isNibLoaded) else {
fatalError("[UIPheonix] Nib could not be loaded #1: \(nibName)")
}
guard let nibElements:AutoreleasingUnsafeMutablePointer<NSArray?> = nibContents else {
fatalError("[UIPheonix] Nib could not be loaded #2: \(nibName)")
}
guard let elementsArray:NSArray = nibElements.pointee else {
fatalError("[UIPheonix] Nib could not be loaded #3: \(nibName)")
}
#endif
guard (elementsArray.count > 0) else {
fatalError("[UIPheonix] Nib is empty: \(nibName)")
}
// find the element we are looking for, since the xib contents order is not guaranteed
let filteredNibContents:[Any] = elementsArray.filter(
{
(element:Any) -> Bool in
return (String(describing:type(of:element)) == nibName)
})
guard (filteredNibContents.count == 1) else {
fatalError("[UIPheonix] Nib \"\(nibName)\" contains more elements, expected only 1!")
}
// with the reuse-id, connect the cell-view in the nib
#if os(iOS) || os(tvOS)
mViewReuseIds[modelName] = nibContents!.first
#elseif os(macOS)
mViewReuseIds[modelName] = filteredNibContents.first
#endif
// register nib with the delegate collection view
#if os(iOS) || os(tvOS)
let nib = UINib(nibName:nibName, bundle:nil)
if (mUIPDelegateViewAppearance == UIPDelegateViewAppearance.collection)
{
mDelegateCollectionView!.register(nib, forCellWithReuseIdentifier:modelName)
}
else if (mUIPDelegateViewAppearance == UIPDelegateViewAppearance.table)
{
mDelegateTableView!.register(nib, forCellReuseIdentifier:modelName)
}
#elseif os(macOS)
let nib = NSNib(nibNamed:NSNib.Name(nibName), bundle:nil)
guard (nib != nil) else {
fatalError("[UIPheonix] Nib could not be instantiated: \(nibName)")
}
if (mUIPDelegateViewAppearance == UIPDelegateViewAppearance.collection)
{
mDelegateCollectionView!.register(nib, forItemWithIdentifier:NSUserInterfaceItemIdentifier(rawValue:modelName))
}
else if (mUIPDelegateViewAppearance == UIPDelegateViewAppearance.table)
{
mDelegateTableView!.register(nib, forIdentifier:NSUserInterfaceItemIdentifier(rawValue:modelName))
}
#endif
}
}
}
}
| apache-2.0 | 66976a049860abc6302f771ea12945d7 | 31.51247 | 212 | 0.632719 | 5.260978 | false | false | false | false |
frootloops/swift | stdlib/public/core/EmptyCollection.swift | 1 | 5500 | //===--- EmptyCollection.swift - A collection with no elements ------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Sometimes an operation is best expressed in terms of some other,
// larger operation where one of the parameters is an empty
// collection. For example, we can erase elements from an Array by
// replacing a subrange with the empty collection.
//
//===----------------------------------------------------------------------===//
/// An iterator that never produces an element.
@_fixed_layout // FIXME(sil-serialize-all)
public struct EmptyIterator<Element> {
// no properties
/// Creates an instance.
@_inlineable // FIXME(sil-serialize-all)
public init() {}
}
extension EmptyIterator: IteratorProtocol, Sequence {
/// Returns `nil`, indicating that there are no more elements.
@_inlineable // FIXME(sil-serialize-all)
public mutating func next() -> Element? {
return nil
}
}
/// A collection whose element type is `Element` but that is always empty.
@_fixed_layout // FIXME(sil-serialize-all)
public struct EmptyCollection<Element> {
// no properties
/// Creates an instance.
@_inlineable // FIXME(sil-serialize-all)
public init() {}
}
extension EmptyCollection: RandomAccessCollection, MutableCollection {
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = Int
public typealias Indices = CountableRange<Int>
public typealias SubSequence = EmptyCollection<Element>
/// Always zero, just like `endIndex`.
@_inlineable // FIXME(sil-serialize-all)
public var startIndex: Index {
return 0
}
/// Always zero, just like `startIndex`.
@_inlineable // FIXME(sil-serialize-all)
public var endIndex: Index {
return 0
}
/// Always traps.
///
/// `EmptyCollection` does not have any element indices, so it is not
/// possible to advance indices.
@_inlineable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
_preconditionFailure("EmptyCollection can't advance indices")
}
/// Always traps.
///
/// `EmptyCollection` does not have any element indices, so it is not
/// possible to advance indices.
@_inlineable // FIXME(sil-serialize-all)
public func index(before i: Index) -> Index {
_preconditionFailure("EmptyCollection can't advance indices")
}
/// Returns an empty iterator.
@_inlineable // FIXME(sil-serialize-all)
public func makeIterator() -> EmptyIterator<Element> {
return EmptyIterator()
}
/// Accesses the element at the given position.
///
/// Must never be called, since this collection is always empty.
@_inlineable // FIXME(sil-serialize-all)
public subscript(position: Index) -> Element {
get {
_preconditionFailure("Index out of range")
}
set {
_preconditionFailure("Index out of range")
}
}
@_inlineable // FIXME(sil-serialize-all)
public subscript(bounds: Range<Index>) -> EmptyCollection<Element> {
get {
_debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
"Index out of range")
return self
}
set {
_debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
"Index out of range")
}
}
/// The number of elements (always zero).
@_inlineable // FIXME(sil-serialize-all)
public var count: Int {
return 0
}
@_inlineable // FIXME(sil-serialize-all)
public func index(_ i: Index, offsetBy n: Int) -> Index {
_debugPrecondition(i == startIndex && n == 0, "Index out of range")
return i
}
@_inlineable // FIXME(sil-serialize-all)
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
_debugPrecondition(i == startIndex && limit == startIndex,
"Index out of range")
return n == 0 ? i : nil
}
/// The distance between two indexes (always zero).
@_inlineable // FIXME(sil-serialize-all)
public func distance(from start: Index, to end: Index) -> Int {
_debugPrecondition(start == 0, "From must be startIndex (or endIndex)")
_debugPrecondition(end == 0, "To must be endIndex (or startIndex)")
return 0
}
@_inlineable // FIXME(sil-serialize-all)
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
_debugPrecondition(index == 0, "out of bounds")
_debugPrecondition(bounds == Range(indices),
"invalid bounds for an empty collection")
}
@_inlineable // FIXME(sil-serialize-all)
public func _failEarlyRangeCheck(
_ range: Range<Index>, bounds: Range<Index>
) {
_debugPrecondition(range == Range(indices),
"invalid range for an empty collection")
_debugPrecondition(bounds == Range(indices),
"invalid bounds for an empty collection")
}
}
extension EmptyCollection : Equatable {
@_inlineable // FIXME(sil-serialize-all)
public static func == (
lhs: EmptyCollection<Element>, rhs: EmptyCollection<Element>
) -> Bool {
return true
}
}
| apache-2.0 | 645b0967995ccbb4f02317e5ad2145db | 30.791908 | 80 | 0.658 | 4.378981 | false | false | false | false |
Draveness/RbSwift | RbSwift/IO/Pathname.swift | 1 | 3383 | //
// Path.swift
// RbSwift
//
// Created by Draveness on 10/04/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Foundation
public struct Pathname {
public let path: String
public init(_ path: String) {
self.path = path
}
/// Returns the current working directory as a Pathname.
public static var getwd: Pathname {
return Pathname(Dir.getwd)
}
/// Predicate method for testing whether a path is absolute.
public var isAbsolute: Bool {
return path.hasPrefix("/")
}
}
extension Pathname: Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func ==(lhs: Pathname, rhs: Pathname) -> Bool {
return lhs.path == rhs.path
}
}
public func +(lhs: Pathname, rhs: Pathname) -> Pathname {
return lhs.path.appendPath(rhs.path)
}
public func +(lhs: String, rhs: Pathname) -> Pathname {
return lhs.appendPath(rhs.path)
}
public func +(lhs: Pathname, rhs: String) -> Pathname {
return lhs.path.appendPath(rhs)
}
/// Appends a String fragment to another String to produce a new Path
/// Origianally from https://github.com/kylef/PathKit/blob/master/Sources/PathKit.swift#L750
private extension String {
func appendPath(_ path: String) -> Pathname {
if path.hasPrefix("/") {
// Absolute paths replace relative paths
return Pathname(path)
} else {
var lSlice = NSString(string: self).pathComponents
var rSlice = NSString(string: path).pathComponents
// Get rid of trailing "/" at the left side
if lSlice.count > 1 && lSlice.last == "/" { lSlice.removeLast() }
// Advance after the first relevant "."
lSlice = lSlice.filter { $0 != "." }
rSlice = rSlice.filter { $0 != "." }
// Eats up trailing components of the left and leading ".." of the right side
while lSlice.last != ".." && rSlice.first == ".." {
if (lSlice.count > 1 || lSlice.first != "/") && !lSlice.isEmpty {
// A leading "/" is never popped
lSlice.removeLast()
}
if !rSlice.isEmpty {
rSlice.removeFirst()
}
switch (lSlice.isEmpty, rSlice.isEmpty) {
case (true, _):
break
case (_, true):
break
default:
continue
}
}
let components = lSlice + rSlice
if components.isEmpty {
return Pathname(".")
} else if components.first == "/" && components.count > 1 {
let p = components.joined(separator: "/")
let path = String(p[p.index(after: p.startIndex)...])
return Pathname(path)
} else {
let path = components.joined(separator: "/")
return Pathname(path)
}
}
}
}
| mit | a7710819e0cef20c861aa871f93b8250 | 30.90566 | 92 | 0.526316 | 4.703755 | false | false | false | false |
dclelland/AudioKit | AudioKit/Common/Nodes/Playback/Sequencer/AKFader.swift | 1 | 6633 | //
// AKFader.swift
// AudioKit
//
// Created by Jeff Cooper on 4/12/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
public enum CurveType {
case Linear, EqualPower, Exponential
public static func fromString(curve: String) -> CurveType {
switch curve {
case "linear":
return .Linear
case "exponential":
return .Exponential
case "equalpower":
return .EqualPower
default:
return .Linear
}
}
}
public class AKFader {
let π = M_PI
var output: AKBooster?
var initialVolume: Double = 1.0 //make these only 0 or 1 right now
var finalVolume: Double = 0.0 //make these only 0 or 1 right now
var controlRate: Double = 1 / 30 // 30 times per second
var curveType: CurveType = .Linear
var curvature: Double = 0.5 //doesn't apply to linear
var duration: Double = 1.0 //seconds
var offset: Double = 0.0
var stepCounter = 0
var stepCount = 0
var fadeTimer = NSTimer()
var fadeScheduleTimer = NSTimer()
/// Init with a single control output
public init(initialVolume: Double,
finalVolume: Double,
duration: Double = 1.0,
type: CurveType = .Exponential,
curvature: Double = 1.0,
offset: Double = 0.0,
output: AKBooster) {
self.initialVolume = initialVolume
self.finalVolume = finalVolume
curveType = type
self.curvature = curvature
self.duration = duration
self.offset = offset
stepCount = Int(floor(duration / controlRate))
self.output = output
}
func scheduleFade(fireTime: Double) {
//this schedules a fade to start after fireTime
fadeScheduleTimer = NSTimer.scheduledTimerWithTimeInterval(
fireTime + offset,
target: self,
selector: #selector(scheduleFadeTimer),
userInfo: nil,
repeats: false)
//print("scheduled for \(fireTime) @ \(duration) seconds")
output!.gain = initialVolume
}
@objc func scheduleFadeTimer(timer: NSTimer) {
startImmediately()
}
public func start() { //starts the fade WITH the offset
scheduleFade(0.0)
}
public func startImmediately() { //skips the offset
//this starts the recurring timer
//print("starting fade \((finalVolume > initialVolume ? "up" : "down"))")
stepCounter = 0
if fadeTimer.valid {
fadeTimer.invalidate()
}
fadeTimer = NSTimer.scheduledTimerWithTimeInterval(controlRate,
target: self,
selector: #selector(updateFade),
userInfo: nil,
repeats: true)
}
@objc func updateFade(timer: NSTimer) {
let direction: Double = (initialVolume > finalVolume ? 1.0 : -1.0)
if stepCount == 0{
endFade()
}else if stepCounter <= stepCount {
let controlAmount: Double = Double(stepCounter) / Double(stepCount) //normalized 0-1 value
var scaledControlAmount: Double = 0.0
switch curveType {
case .Linear:
scaledControlAmount = AKFader.denormalize(controlAmount,
minimum: initialVolume,
maximum: finalVolume,
taper: 1)
case .Exponential:
scaledControlAmount = AKFader.denormalize(controlAmount,
minimum: initialVolume,
maximum: finalVolume,
taper: curvature)
case .EqualPower:
scaledControlAmount = pow((0.5 + 0.5 * direction * cos(π * controlAmount)), 0.5) //direction will be negative if going up
}
output!.gain = scaledControlAmount
stepCounter += 1
//print(scaledControlAmount)
} else {
endFade()
}
}//end updateFade
func endFade(){
fadeTimer.invalidate()
output!.gain = finalVolume
stepCounter = 0
}
static func denormalize(input: Double, minimum: Double, maximum: Double, taper: Double) -> Double {
if taper > 0 {
// algebraic taper
return minimum + (maximum - minimum) * pow(input, taper)
} else {
// exponential taper
var adjustedMinimum: Double = 0.0
var adjustedMaximum: Double = 0.0
if minimum == 0 { adjustedMinimum = 0.00000000001 }
if maximum == 0 { adjustedMaximum = 0.00000000001 }
return log(input / adjustedMinimum) / log(adjustedMaximum / adjustedMinimum);//not working right for 0 values
}
}
static func generateCurvePoints(source: Double,
target: Double,
duration: Double = 1.0,
type: CurveType = .Exponential,
curvature: Double = 1.0,
controlRate: Double = 1/30) -> [Double] {
var curvePoints = [Double]()
let stepCount = Int(floor(duration / controlRate))
var counter = 0
let direction: Double = source > target ? 1.0 : -1.0
if counter <= stepCount {
let controlAmount: Double = Double(counter) / Double(stepCount) //normalised 0-1 value
var scaledControlAmount: Double = 0.0
switch type {
case .Linear:
scaledControlAmount = denormalize(controlAmount, minimum: source, maximum: target, taper: 1)
case .Exponential:
scaledControlAmount = denormalize(controlAmount, minimum: source, maximum: target, taper: curvature)
case .EqualPower:
scaledControlAmount = pow((0.5 + 0.5 * direction * cos(M_PI * controlAmount)), 0.5) //direction will be negative if going up
}
curvePoints.append(scaledControlAmount)
counter += 1
}
return curvePoints
}
}
| mit | 0a73975db0d56429e3541c2c9ef2902a | 35.428571 | 140 | 0.520362 | 5.33387 | false | false | false | false |
spark/photon-tinker-ios | Photon-Tinker/ScreenUtils.swift | 1 | 1288 | //
// Created by Raimundas Sakalauskas on 03/10/2018.
// Copyright (c) 2018 Particle. All rights reserved.
//
import Foundation
enum PhoneScreenSizeClass: Int, Comparable {
case iPhone4
case iPhone5
case iPhone6
case iPhone6Plus
case iPhoneX
case iPhoneXMax
case other
public static func < (a: PhoneScreenSizeClass, b: PhoneScreenSizeClass) -> Bool {
return a.rawValue < b.rawValue
}
}
class ScreenUtils {
static func isIPad() -> Bool {
return UI_USER_INTERFACE_IDIOM() == .pad
}
static func isIPhone() -> Bool {
return UI_USER_INTERFACE_IDIOM() == .phone
}
static func getPhoneScreenSizeClass() -> PhoneScreenSizeClass {
let screenSize = UIScreen.main.bounds.size
let maxLength = max(screenSize.width, screenSize.height)
if (maxLength <= 480) {
return .iPhone4
} else if (maxLength <= 568) {
return .iPhone5
} else if (maxLength <= 667) {
return .iPhone6
} else if (maxLength <= 736) {
return .iPhone6Plus
} else if (maxLength <= 812) {
return .iPhoneX
} else if (maxLength <= 896) {
return .iPhoneXMax
} else {
return .other
}
}
} | apache-2.0 | 79cca40f017e790dae59c51aea2c61f0 | 23.788462 | 85 | 0.58618 | 4.410959 | false | false | false | false |
btanner/Eureka | Source/Rows/ButtonRowWithPresent.swift | 8 | 3718 | // Rows.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
open class _ButtonRowWithPresent<VCType: TypedRowControllerType>: Row<ButtonCellOf<VCType.RowValue>>, PresenterRowType where VCType: UIViewController {
open var presentationMode: PresentationMode<VCType>?
open var onPresentCallback: ((FormViewController, VCType) -> Void)?
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
cellStyle = .default
}
open override func customUpdateCell() {
super.customUpdateCell()
let leftAligmnment = presentationMode != nil
cell.textLabel?.textAlignment = leftAligmnment ? .left : .center
cell.accessoryType = !leftAligmnment || isDisabled ? .none : .disclosureIndicator
cell.editingAccessoryType = cell.accessoryType
if !leftAligmnment {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
cell.tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
cell.textLabel?.textColor = UIColor(red: red, green: green, blue: blue, alpha:isDisabled ? 0.3 : 1.0)
} else {
cell.textLabel?.textColor = nil
}
}
open override func customDidSelect() {
super.customDidSelect()
if let presentationMode = presentationMode, !isDisabled {
if let controller = presentationMode.makeController() {
controller.row = self
onPresentCallback?(cell.formViewController()!, controller)
presentationMode.present(controller, row: self, presentingController: cell.formViewController()!)
} else {
presentationMode.present(nil, row: self, presentingController: cell.formViewController()!)
}
}
}
open override func prepare(for segue: UIStoryboardSegue) {
super.prepare(for: segue)
guard let rowVC = segue.destination as? VCType else {
return
}
if let callback = presentationMode?.onDismissCallback {
rowVC.onDismissCallback = callback
}
rowVC.row = self
onPresentCallback?(cell.formViewController()!, rowVC)
}
}
// MARK: Rows
/// A generic row with a button that presents a view controller when tapped
public final class ButtonRowWithPresent<VCType: TypedRowControllerType> : _ButtonRowWithPresent<VCType>, RowType where VCType: UIViewController {
public required init(tag: String?) {
super.init(tag: tag)
}
}
| mit | e50475d23cef03d4af4969ef4c0064f5 | 41.25 | 151 | 0.686122 | 4.957333 | 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.