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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mikelikespie/swiftled
|
src/main/swift/Swiftlights/AppDelegate.swift
|
1
|
1204
|
//
// AppDelegate.swift
// SwiftledMobile
//
// Created by Michael Lewis on 12/29/15.
// Copyright © 2015 Lolrus Industries. All rights reserved.
//
import UIKit
import Cleanse
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var root: Root!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
root = try! Root()
window = root.window
window?.makeKeyAndVisible()
return true
}
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.
let backgroundTask = application.beginBackgroundTask(withName: "controlling-leds", expirationHandler: nil)
_ = backgroundTask
}
}
|
mit
|
c32a2512524cdecf7a381f56c20c0cc5
| 29.846154 | 218 | 0.703242 | 5.418919 | false | false | false | false |
Killectro/RxGrailed
|
RxGrailed/Pods/AlgoliaSearch-Client-Swift/Source/Network.swift
|
1
|
7812
|
//
// Copyright (c) 2015 Algolia
// http://www.algolia.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
/// HTTP method definitions.
internal enum HTTPMethod: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case DELETE = "DELETE"
}
/// Abstraction of `NSURLSession`.
/// Only for the sake of unit tests.
internal protocol URLSession {
func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
}
// Convince the compiler that NSURLSession does implements our custom protocol.
extension Foundation.URLSession: URLSession {
}
#if os(iOS) && DEBUG
import CoreTelephony
import SystemConfiguration
/// Wrapper around an `NSURLSession`, adding logging facilities.
///
internal class URLSessionLogger: NSObject, URLSession {
static var epoch: Date = Date()
struct RequestStat {
// TODO: Log network type.
let startTime: Date
let host: String
var networkType: String?
var responseTime: TimeInterval?
var cancelled: Bool = false
var dataSize: Int?
var statusCode: Int?
init(startTime: Date, host: String) {
self.startTime = startTime
self.host = host
}
var description: String {
var description = "@\(Int(startTime.timeIntervalSince(URLSessionLogger.epoch) * 1000))ms; \(host); \(networkType != nil ? networkType! : "?")"
if let responseTime = responseTime, let dataSize = dataSize, let statusCode = statusCode {
description += "; \(Int(responseTime * 1000))ms; \(dataSize)B; \(statusCode)"
}
return description
}
}
/// The wrapped session.
let session: URLSession
/// Stats.
private(set) var stats: [RequestStat] = []
/// Queue used to serialize concurrent accesses to this object.
private let queue = DispatchQueue(label: "URLSessionLogger.lock")
/// Temporary stats under construction (ongoing requests).
private var tmpStats: [URLSessionTask: RequestStat] = [:]
/// Used to determine overall network type.
private let defaultRouteReachability: SCNetworkReachability
/// Used to get the mobile data network type.
private let networkInfo = CTTelephonyNetworkInfo()
init(session: URLSession) {
self.session = session
var zeroAddress: sockaddr_in = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
let zeroAddressAsSockaddr = UnsafePointer<sockaddr>(OpaquePointer($0))
return SCNetworkReachabilityCreateWithAddress(nil, zeroAddressAsSockaddr)!
}
// Reset the (global) epoch for logging.
URLSessionLogger.epoch = Date()
}
func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
var task: URLSessionDataTask!
let startTime = Date()
let networkType = getNetworkType()
task = session.dataTask(with: request, completionHandler: completionHandler)
self.queue.sync {
self.tmpStats[task] = RequestStat(startTime: startTime, host: request.url!.host!)
self.tmpStats[task]?.networkType = networkType
}
task.addObserver(self, forKeyPath: "state", options: .new, context: nil)
return task
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let task = object as? URLSessionTask {
if keyPath == "state" {
if task.state == .canceling {
self.queue.sync {
self.tmpStats[task]!.cancelled = true
}
}
if task.state == .completed {
let stopTime = NSDate()
self.queue.sync {
var stat = self.tmpStats[task]!
stat.responseTime = stopTime.timeIntervalSince(stat.startTime)
stat.dataSize = Int(task.countOfBytesReceived)
if let response = task.response as? HTTPURLResponse {
stat.statusCode = response.statusCode
} else if let error = task.error as? NSError {
stat.statusCode = error.code
}
self.stats.append(stat)
self.tmpStats.removeValue(forKey: task)
}
task.removeObserver(self, forKeyPath: "state")
dump()
}
}
}
}
func dump() {
self.queue.sync {
for stat in self.stats {
print("[NET] \(stat.description)")
}
self.stats.removeAll()
}
}
// MARK: Network status
/// Return the current network type as a human-friendly string.
///
private func getNetworkType() -> String? {
var flags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
if flags.contains(.isWWAN) {
if let technology = networkInfo.currentRadioAccessTechnology {
return URLSessionLogger.description(radioAccessTechnology: technology)
}
} else {
return "WIFI"
}
}
return nil
}
/// Convert one of the enum-like `CTRadioAccessTechnology*` constants into a human-friendly string.
///
static func description(radioAccessTechnology: String) -> String {
switch (radioAccessTechnology) {
case CTRadioAccessTechnologyGPRS: return "GPRS"
case CTRadioAccessTechnologyEdge: return "EDGE"
case CTRadioAccessTechnologyWCDMA: return "WCDMA"
case CTRadioAccessTechnologyHSDPA: return "HSDPA"
case CTRadioAccessTechnologyHSUPA: return "HSUPA"
case CTRadioAccessTechnologyCDMA1x: return "CDMA(1x)"
case CTRadioAccessTechnologyCDMAEVDORev0: return "CDMA(EVDORev0)"
case CTRadioAccessTechnologyCDMAEVDORevA: return "CDMA(EVDORevA)"
case CTRadioAccessTechnologyCDMAEVDORevB: return "CDMA(EVDORevB)"
case CTRadioAccessTechnologyeHRPD: return "HRPD"
case CTRadioAccessTechnologyLTE: return "LTE"
default: return "?"
}
}
}
#endif // DBEUG
|
mit
|
fd2c584efcd38986911eabbce2893ff3
| 38.06 | 154 | 0.625448 | 4.96 | false | false | false | false |
kaojohnny/CoreStore
|
Sources/Convenience/NSProgress+Convenience.swift
|
1
|
4146
|
//
// NSProgress+Convenience.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// 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
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - NSProgress
public extension NSProgress {
/**
Sets a closure that the `NSProgress` calls whenever its `fractionCompleted` changes. You can use this instead of setting up KVO.
- parameter closure: the closure to execute on progress change
*/
@nonobjc
public func setProgressHandler(closure: ((progress: NSProgress) -> Void)?) {
self.progressObserver.progressHandler = closure
}
// MARK: Private
private struct PropertyKeys {
static var progressObserver: Void?
}
@nonobjc
private var progressObserver: ProgressObserver {
get {
let object: ProgressObserver? = cs_getAssociatedObjectForKey(&PropertyKeys.progressObserver, inObject: self)
if let observer = object {
return observer
}
let observer = ProgressObserver(self)
cs_setAssociatedRetainedObject(
observer,
forKey: &PropertyKeys.progressObserver,
inObject: self
)
return observer
}
}
}
// MARK: - ProgressObserver
@objc
private final class ProgressObserver: NSObject {
private unowned let progress: NSProgress
private var progressHandler: ((progress: NSProgress) -> Void)? {
didSet {
let progressHandler = self.progressHandler
if (progressHandler == nil) == (oldValue == nil) {
return
}
if let _ = progressHandler {
self.progress.addObserver(
self,
forKeyPath: "fractionCompleted",
options: [.Initial, .New],
context: nil
)
}
else {
self.progress.removeObserver(self, forKeyPath: "fractionCompleted")
}
}
}
private init(_ progress: NSProgress) {
self.progress = progress
super.init()
}
deinit {
if let _ = self.progressHandler {
self.progressHandler = nil
self.progress.removeObserver(self, forKeyPath: "fractionCompleted")
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard let progress = object as? NSProgress where progress == self.progress && keyPath == "fractionCompleted" else {
return
}
GCDQueue.Main.async { [weak self] () -> Void in
self?.progressHandler?(progress: progress)
}
}
}
|
mit
|
dd93e15c7eab290611412daff90e274a
| 29.036232 | 157 | 0.590109 | 5.475561 | false | false | false | false |
intelygenz/Kommander-iOS
|
Source/Kommand.swift
|
2
|
7480
|
//
// Kommand.swift
// Kommander
//
// Created by Alejandro Ruperez Hernando on 26/1/17.
// Copyright © 2017 Intelygenz. All rights reserved.
//
import Foundation
/// Generic Kommand
open class Kommand<Result> {
/// Kommand<Result> state
public indirect enum State: Equatable {
/// Uninitialized state
case uninitialized
/// Ready state
case ready
/// Executing state
case running
/// Succeeded state
case succeeded(Result)
/// Failed state
case failed(Swift.Error)
/// Cancelled state
case cancelled
public static func ==(lhs: State, rhs: State) -> Bool {
switch (lhs, rhs) {
case (.uninitialized, .uninitialized):
return true
case (.ready, .ready):
return true
case (.running, .running):
return true
case (.succeeded, .succeeded):
return true
case (.failed, .failed):
return true
case (.cancelled, .cancelled):
return true
default:
return false
}
}
}
/// Action closure type
public typealias ActionClosure = () throws -> Result
/// Success closure type
public typealias SuccessClosure = (_ result: Result) -> Void
/// Error closure type
public typealias ErrorClosure = (_ error: Swift.Error?) -> Void
/// Retry closure type
public typealias RetryClosure = (_ error: Swift.Error?, _ executionCount: UInt) -> Bool
/// Kommand<Result> state
internal(set) public final var state = State.uninitialized
/// Deliverer
private final weak var deliverer: Dispatcher?
/// Executor
private final weak var executor: Dispatcher?
/// Action closure
private(set) final var actionClosure: ActionClosure?
/// Success closure
private(set) final var successClosure: SuccessClosure?
/// Error closure
private(set) final var errorClosure: ErrorClosure?
/// Retry closure
private(set) final var retryClosure: RetryClosure?
/// Execution count
internal(set) final var executionCount: UInt
/// Operation to cancel
internal(set) final weak var operation: Operation?
/// Kommand<Result> instance with deliverer, executor and actionClosure returning generic and throwing errors
public required init(deliverer: Dispatcher = .current, executor: Dispatcher = .default, actionClosure: @escaping ActionClosure) {
self.deliverer = deliverer
self.executor = executor
self.actionClosure = actionClosure
executionCount = 0
state = .ready
}
/// Release all resources
deinit {
operation = nil
deliverer = nil
executor = nil
actionClosure = nil
successClosure = nil
errorClosure = nil
retryClosure = nil
}
/// Specify Kommand<Result> success closure
@discardableResult open func success(_ success: @escaping SuccessClosure) -> Self {
self.successClosure = success
return self
}
/// Specify Kommand<Result> error closure
@discardableResult open func error(_ error: @escaping ErrorClosure) -> Self {
self.errorClosure = error
return self
}
/// Specify Kommand<Result> error closure
@discardableResult open func error<Reason: Swift.Error>(_ type: Reason.Type, _ error: @escaping (_ error: Reason) -> Void) -> Self {
self.errorClosure = {
guard let reason = $0 as? Reason else {
assertionFailure("Unexpected error thrown. \(Reason.self) expected, \($0.debugDescription) thrown.")
return
}
error(reason)
}
return self
}
/// Specify Kommand<Result> retry closure
@discardableResult open func retry(_ retry: @escaping RetryClosure) -> Self {
self.retryClosure = retry
return self
}
/// Specify Kommand<Result> error closure
@discardableResult open func retry<Reason: Swift.Error>(_ type: Reason.Type, _ retry: @escaping (_ error: Reason?, _ executionCount: UInt) -> Bool) -> Self {
self.retryClosure = {
guard let reason = $0 as? Reason else {
return retry(nil, $1)
}
return retry(reason, $1)
}
return self
}
open var result: Result? {
guard case .succeeded(let result) = state else {
return nil
}
return result
}
open var error: Error? {
guard case .failed(let error) = state else {
return nil
}
return error
}
/// Execute Kommand<Result> after delay
@discardableResult open func execute(after delay: DispatchTimeInterval) -> Self {
executor?.execute(after: delay, closure: {
self.execute()
})
return self
}
/// Execute Kommand<Result>
@discardableResult open func execute() -> Self {
guard state == .ready else {
return self
}
operation = executor?.execute {
do {
if let actionClosure = self.actionClosure {
self.state = .running
self.executionCount += 1
let result = try actionClosure()
guard self.state == .running else {
return
}
self.deliverer?.execute {
self.state = .succeeded(result)
self.successClosure?(result)
}
}
} catch {
guard self.state == .running else {
return
}
self.deliverer?.execute {
self.state = .failed(error)
if self.retryClosure?(error, self.executionCount) == true {
self.state = .ready
self.execute()
} else {
self.errorClosure?(error)
}
}
}
}
return self
}
/// Cancel Kommand<Result> after delay
@discardableResult open func cancel(_ throwingError: Bool = false, after delay: DispatchTimeInterval) -> Self {
executor?.execute(after: delay, closure: {
self.cancel(throwingError)
})
return self
}
/// Cancel Kommand<Result>
@discardableResult open func cancel(_ throwingError: Bool = false) -> Self {
guard state == .ready || state == .running else {
return self
}
self.deliverer?.execute {
if throwingError {
self.errorClosure?(KommandCancelledError(self))
}
}
if let operation = operation, !operation.isFinished {
operation.cancel()
}
state = .cancelled
return self
}
/// Retry Kommand<Result> after delay
@discardableResult open func retry(after delay: DispatchTimeInterval) -> Self {
executor?.execute(after: delay, closure: {
self.retry()
})
return self
}
/// Retry Kommand<Result>
@discardableResult open func retry() -> Self {
guard state == .cancelled else {
return self
}
state = .ready
return execute()
}
}
|
mit
|
f62af90c6ee8fce745656def88183393
| 30.1625 | 161 | 0.555288 | 5.09816 | false | false | false | false |
aerisweather/Aeris-iOS-Library
|
Demo/AerisSwiftDemo/Source/Devices/iPhone/DetailedWeatherViewController.swift
|
1
|
10177
|
//
// DetailedWeatherViewController.swift
// AerisSwiftDemo
//
// Created by Nicholas Shipes on 12/29/17.
// Copyright © 2017 AerisWeather. All rights reserved.
//
import UIKit
class DetailedWeatherViewController: UIViewController {
var obsView: AWFObservationView!
var advisoriesView: AWFObservationAdvisoriesView!
var todayView: AWFForecastDetailView!
var tonightView: AWFForecastDetailView!
var hourlyCollectionView: UICollectionView!
fileprivate var hourlyPeriods: [AWFForecastPeriod]?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = AWFCascadingStyle().viewControllerBackgroundColor
obsView = AWFObservationView()
obsView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(obsView)
advisoriesView = AWFObservationAdvisoriesView()
advisoriesView.translatesAutoresizingMaskIntoConstraints = false
advisoriesView.alpha = 0
view.addSubview(advisoriesView)
let obsKeyline = UIView()
obsKeyline.translatesAutoresizingMaskIntoConstraints = false
obsKeyline.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
view.addSubview(obsKeyline)
todayView = AWFForecastDetailView()
todayView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(todayView)
tonightView = AWFForecastDetailView()
tonightView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tonightView)
let forecastKeyline = UIView()
forecastKeyline.translatesAutoresizingMaskIntoConstraints = false
forecastKeyline.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
view.addSubview(forecastKeyline)
let hourlyCollectionViewLayout = UICollectionViewFlowLayout()
hourlyCollectionViewLayout.scrollDirection = .horizontal
hourlyCollectionViewLayout.minimumInteritemSpacing = 0
hourlyCollectionViewLayout.minimumLineSpacing = 0
hourlyCollectionViewLayout.itemSize = CGSize(width: 80.0, height: 50.0)
hourlyCollectionView = UICollectionView(frame: .zero, collectionViewLayout: hourlyCollectionViewLayout)
hourlyCollectionView.translatesAutoresizingMaskIntoConstraints = false
hourlyCollectionView.backgroundColor = AWFCascadingStyle().viewControllerBackgroundColor
hourlyCollectionView.dataSource = self
hourlyCollectionView.delegate = self
hourlyCollectionView.register(AWFCollectionViewHourlyBasicCell.self, forCellWithReuseIdentifier: AWFCollectionViewHourlyBasicCell.defaultReuseIdentifier())
view.addSubview(hourlyCollectionView)
// layout
NSLayoutConstraint.activate([
obsView.topAnchor.constraint(equalTo: view.topAnchor),
obsView.leftAnchor.constraint(equalTo: view.leftAnchor),
obsView.rightAnchor.constraint(equalTo: view.rightAnchor),
obsKeyline.topAnchor.constraint(equalTo: obsView.bottomAnchor),
obsKeyline.leftAnchor.constraint(equalTo: view.leftAnchor),
obsKeyline.rightAnchor.constraint(equalTo: view.rightAnchor),
obsKeyline.heightAnchor.constraint(equalToConstant: 2.0),
todayView.topAnchor.constraint(equalTo: obsKeyline.bottomAnchor),
todayView.leftAnchor.constraint(equalTo: view.leftAnchor),
todayView.rightAnchor.constraint(equalTo: view.centerXAnchor),
tonightView.topAnchor.constraint(equalTo: todayView.topAnchor),
tonightView.leftAnchor.constraint(equalTo: view.centerXAnchor),
tonightView.rightAnchor.constraint(equalTo: view.rightAnchor),
forecastKeyline.topAnchor.constraint(equalTo: todayView.bottomAnchor),
forecastKeyline.leftAnchor.constraint(equalTo: view.leftAnchor),
forecastKeyline.rightAnchor.constraint(equalTo: view.rightAnchor),
forecastKeyline.heightAnchor.constraint(equalToConstant: 2.0),
hourlyCollectionView.topAnchor.constraint(equalTo: forecastKeyline.bottomAnchor),
hourlyCollectionView.leftAnchor.constraint(equalTo: view.leftAnchor),
hourlyCollectionView.rightAnchor.constraint(equalTo: view.rightAnchor),
hourlyCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let hourlyCollectionViewLayout = UICollectionViewFlowLayout()
hourlyCollectionViewLayout.scrollDirection = .horizontal
hourlyCollectionViewLayout.minimumInteritemSpacing = 0
hourlyCollectionViewLayout.minimumLineSpacing = 0
hourlyCollectionViewLayout.itemSize = CGSize(width: 80.0, height: view.frame.height - hourlyCollectionView.frame.minY)
hourlyCollectionView.collectionViewLayout = hourlyCollectionViewLayout
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let style = Preferences.sharedInstance().preferredStyle() {
view.backgroundColor = style.viewControllerBackgroundColor
hourlyCollectionView.backgroundColor = style.viewControllerBackgroundColor
obsView.apply(style)
todayView.apply(style)
tonightView.apply(style)
hourlyCollectionView.reloadData()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let place = UserLocationsManager.shared().defaultLocation() {
loadData(forPlace: place)
}
}
private func loadData(forPlace place: AWFPlace) {
obsView.locationTextLabel.text = place.formattedNameFull
// load latest observation data for place
AWFObservations.sharedService().get(forPlace: place, options: nil) { [weak self] (result) in
guard let results = result?.results else { print("Observation data failed to load - \(String(describing: result?.error))"); return }
if let obs = results.first as? AWFObservation {
// determine winds string
let windSpeed = obs.windSpeedMPH
var windStr = "\(String(describing: obs.windDirection)) \(windSpeed) mph"
if windSpeed == 0 {
windStr = "Calm"
}
self?.obsView.tempTextLabel.text = "\(obs.tempF)deg"
self?.obsView.weatherTextLabel.text = obs.weather
self?.obsView.feelslikeTextLabel.text = "Feels Like: \(obs.feelslikeF)deg"
self?.obsView.windsTextLabel.text = windStr
self?.obsView.dewpointTextLabel.text = "\(obs.dewpointF)deg"
self?.obsView.humidityTextLabel.text = "\(obs.humidity)%"
self?.obsView.pressureTextLabel.text = "\(obs.pressureIN) in"
if let wxicon = obs.icon {
self?.obsView.iconImageView.image = UIImage(named: wxicon)
} else {
self?.obsView.iconImageView.image = nil
}
}
}
// load 24-hour forecast
let forecastOptions = AWFWeatherRequestOptions()
forecastOptions.limit = 2
forecastOptions.filterString = "\(AWFForecastFilter.dayNight)"
AWFForecasts.sharedService().get(forPlace: place, options: forecastOptions) { [weak self] (result) in
guard let results = result?.results else { print("24-hour forecast data failed to load - \(String(describing: result?.error))"); return }
if let forecast = results.first as? AWFForecast {
forecast.periods?.enumerated().forEach({ (index, period) in
// determine which view to set the data on
let forecastView = index == 1 ? self?.tonightView : self?.todayView
forecastView?.tempTextLabel.text = period.isDay ? "\(period.maxTempF)" : "\(period.minTempF)"
forecastView?.weatherTextLabel.text = period.weather
if let direction = period.windDirection, let speedRange = period.windSpeedRangeMPH {
forecastView?.windsTextLabel.text = "\(direction) \(speedRange) mph"
}
if let wxicon = period.icon {
forecastView?.iconImageView.image = UIImage(named: wxicon)
}
// need to set the proper default timezone to use when formatting this location's date/time/day
if period.timestamp != nil {
// forecastView?.periodTextLabel.text = timestamp.
//[period.timestamp awf_dayNameRelativeToNow:YES timeZone:period.timeZone];
}
// show snow instead of precip if snow is forecast
if let weather = period.weather {
if weather.lowercased().contains("snow") {
forecastView?.precipTextLabel.text = "Snow"
forecastView?.precipTextLabel.text = "\(period.snowIN) in"
} else {
forecastView?.precipTextLabel.text = "Precip"
forecastView?.precipTextLabel.text = "\(period.precipIN) in"
}
}
})
}
}
// load hourly forecast
let hourlyOptions = AWFWeatherRequestOptions()
hourlyOptions.limit = 9
hourlyOptions.filterString = "\(AWFForecastFilter.filter3Hour)"
AWFForecasts.sharedService().get(forPlace: place, options: hourlyOptions) { [weak self] (result) in
guard let results = result?.results else { print("Hourly forecast data failed to load - \(String(describing: result?.error))"); return }
if let forecast = results.first as? AWFForecast {
self?.hourlyPeriods = forecast.periods
} else {
self?.hourlyPeriods = nil
}
self?.hourlyCollectionView.reloadData()
}
// load advisories
AWFAdvisories.sharedService().get(forPlace: place, options: nil) { [weak self] (result) in
guard let results = result?.results else { print("Advisory data failed to load - \(String(describing: result?.error))"); return }
if let advisories = results as? [AWFAdvisory], results.count > 0 {
self?.advisoriesView.advisories = advisories
UIView.animate(withDuration: 0.2, animations: {
self?.advisoriesView.alpha = 1.0
})
} else {
UIView.animate(withDuration: 0.2, animations: {
self?.advisoriesView.alpha = 0
})
}
}
}
}
extension DetailedWeatherViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return hourlyPeriods?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AWFCollectionViewHourlyBasicCell.defaultReuseIdentifier(), for: indexPath)
if let hourlyCell = cell as? AWFCollectionViewHourlyBasicCell, let period = hourlyPeriods?[indexPath.row] {
hourlyCell.configure(with: period)
if let style = obsView.style {
hourlyCell.weatherView.apply(style)
}
}
return cell
}
}
extension DetailedWeatherViewController: UICollectionViewDelegate {
}
|
bsd-3-clause
|
89c4448d8a6ac5c10bb64144a25490b2
| 37.839695 | 157 | 0.75452 | 4.126521 | false | false | false | false |
bykoianko/omim
|
iphone/Maps/Bookmarks/Categories/Category settings/CategorySettingsViewController.swift
|
1
|
5129
|
@objc
protocol CategorySettingsViewControllerDelegate: AnyObject {
func categorySettingsController(_ viewController: CategorySettingsViewController,
didEndEditing categoryId: MWMMarkGroupID)
func categorySettingsController(_ viewController: CategorySettingsViewController,
didDelete categoryId: MWMMarkGroupID)
}
class CategorySettingsViewController: MWMTableViewController {
@objc var categoryId = MWMFrameworkHelper.invalidCategoryId()
@objc var maxCategoryNameLength: UInt = 60
@objc var minCategoryNameLength: UInt = 0
private var changesMade = false
var manager: MWMBookmarksManager {
return MWMBookmarksManager.shared()
}
@objc weak var delegate: CategorySettingsViewControllerDelegate?
@IBOutlet private weak var nameTextField: UITextField!
@IBOutlet private weak var descriptionTextView: UITextView!
@IBOutlet private weak var descriptionCell: UITableViewCell!
@IBOutlet private weak var saveButton: UIBarButtonItem!
@IBOutlet private weak var deleteListButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
title = L("list_settings")
assert(categoryId != MWMFrameworkHelper.invalidCategoryId(), "must provide category info")
deleteListButton.isEnabled = (manager.groupsIdList().count > 1)
nameTextField.text = manager.getCategoryName(categoryId)
descriptionTextView.text = manager.getCategoryDescription(categoryId)
navigationItem.rightBarButtonItem = saveButton
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if isMovingFromParentViewController && !changesMade {
Statistics.logEvent(kStatBookmarkSettingsCancel)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
// if there are no bookmarks in category, hide 'sharing options' row
return MWMBookmarksManager.shared().isCategoryNotEmpty(categoryId) ? 2 : 1
default:
return 1
}
}
@IBAction func deleteListButtonPressed(_ sender: Any) {
guard categoryId != MWMFrameworkHelper.invalidCategoryId() else {
assert(false)
return
}
manager.deleteCategory(categoryId)
delegate?.categorySettingsController(self, didDelete: categoryId)
Statistics.logEvent(kStatBookmarkSettingsClick,
withParameters: [kStatOption : kStatDelete])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationVC = segue.destination as? BookmarksSharingViewController {
destinationVC.categoryId = categoryId
Statistics.logEvent(kStatBookmarkSettingsClick,
withParameters: [kStatOption : kStatSharingOptions])
}
}
@IBAction func onSave(_ sender: Any) {
guard categoryId != MWMFrameworkHelper.invalidCategoryId(),
let newName = nameTextField.text,
!newName.isEmpty else {
assert(false)
return
}
manager.setCategory(categoryId, name: newName)
manager.setCategory(categoryId, description: descriptionTextView.text)
changesMade = true
delegate?.categorySettingsController(self, didEndEditing: categoryId)
Statistics.logEvent(kStatBookmarkSettingsConfirm)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
}
extension CategorySettingsViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
let size = textView.bounds.size
let newSize = textView.sizeThatFits(CGSize(width: size.width,
height: CGFloat.greatestFiniteMagnitude))
// Resize the cell only when cell's size is changed
if abs(size.height - newSize.height) >= 1 {
UIView.setAnimationsEnabled(false)
tableView.beginUpdates()
tableView.endUpdates()
UIView.setAnimationsEnabled(true)
if let thisIndexPath = tableView.indexPath(for: descriptionCell) {
tableView?.scrollToRow(at: thisIndexPath, at: .bottom, animated: false)
}
}
}
func textViewDidBeginEditing(_ textView: UITextView) {
Statistics.logEvent(kStatBookmarkSettingsClick,
withParameters: [kStatOption : kStatAddDescription])
}
}
extension CategorySettingsViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let currentText = textField.text ?? ""
guard let stringRange = Range(range, in: currentText) else { return false }
let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
saveButton.isEnabled = updatedText.count > minCategoryNameLength
if updatedText.count > maxCategoryNameLength { return false }
return true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
saveButton.isEnabled = false
return true
}
}
|
apache-2.0
|
61f1543657efc5ce18127c80314bf8ae
| 35.899281 | 101 | 0.717294 | 5.444798 | false | false | false | false |
patchthecode/JTAppleCalendar
|
Sources/JTAppleCalendar/CalendarStructs.swift
|
1
|
17575
|
//
// CalendarStructs.swift
//
// Copyright (c) 2016-2020 JTAppleCalendar (https://github.com/patchthecode/JTAppleCalendar)
//
// 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
/// Describes which month the cell belongs to
/// - ThisMonth: Cell belongs to the current month
/// - PreviousMonthWithinBoundary: Cell belongs to the previous month.
/// Previous month is included in the date boundary you have set in your
/// delegate - PreviousMonthOutsideBoundary: Cell belongs to the previous
/// month. Previous month is not included in the date boundary you have set
/// in your delegate - FollowingMonthWithinBoundary: Cell belongs to the
/// following month. Following month is included in the date boundary you have
/// set in your delegate - FollowingMonthOutsideBoundary: Cell belongs to the
/// following month. Following month is not included in the date boundary you
/// have set in your delegate You can use these cell states to configure how
/// you want your date cells to look. Eg. you can have the colors belonging
/// to the month be in color black, while the colors of previous months be in
/// color gray.
public struct CellState {
/// returns true if a cell is selected
public let isSelected: Bool
/// returns the date as a string
public let text: String
/// returns the a description of which month owns the date
public let dateBelongsTo: DateOwner
/// returns the date
public let date: Date
/// returns the day
public let day: DaysOfWeek
/// returns the row in which the date cell appears visually
public let row: () -> Int
/// returns the column in which the date cell appears visually
public let column: () -> Int
/// returns the section the date cell belongs to
public let dateSection: () -> (range: (start: Date, end: Date), month: Int, rowCount: Int)
/// returns the position of a selection in the event you wish to do range selection
public let selectedPosition: () -> SelectionRangePosition
/// returns the cell.
/// Useful if you wish to display something at the cell's frame/position
public var cell: () -> JTACDayCell?
/// Shows if a cell's selection/deselection was done either programatically or by the user
/// This variable is guranteed to be non-nil inside of a didSelect/didDeselect function
public var selectionType: SelectionType? = nil
}
/// Defines the parameters which configures the calendar.
public struct ConfigurationParameters {
/// The start date boundary of your calendar
var startDate: Date
/// The end-date boundary of your calendar
var endDate: Date
/// Number of rows you want to calendar to display per date section
var numberOfRows: Int
/// Your calendar() Instance
var calendar: Calendar
/// Describes the types of in-date cells to be generated.
var generateInDates: InDateCellGeneration
/// Describes the types of out-date cells to be generated.
var generateOutDates: OutDateCellGeneration
/// Sets the first day of week
var firstDayOfWeek: DaysOfWeek
/// Determine if dates of a month should stay in its section
/// or if it can flow into another months section. This value is ignored
/// if your calendar has registered headers
var hasStrictBoundaries: Bool
/// init-function
public init(startDate: Date,
endDate: Date,
numberOfRows: Int = 6,
calendar: Calendar = Calendar.current,
generateInDates: InDateCellGeneration = .forAllMonths,
generateOutDates: OutDateCellGeneration = .tillEndOfGrid,
firstDayOfWeek: DaysOfWeek? = nil,
hasStrictBoundaries: Bool? = nil) {
self.startDate = startDate
self.endDate = endDate
if numberOfRows > 0 && numberOfRows < 7 {
self.numberOfRows = numberOfRows
} else {
self.numberOfRows = 6
}
if let nonNilHasStrictBoundaries = hasStrictBoundaries {
self.hasStrictBoundaries = nonNilHasStrictBoundaries
} else {
self.hasStrictBoundaries = self.numberOfRows > 1 ? true : false
}
self.calendar = calendar
self.generateInDates = generateInDates
self.generateOutDates = generateOutDates
if let firstDayOfWeek = firstDayOfWeek {
self.firstDayOfWeek = firstDayOfWeek
} else {
self.firstDayOfWeek = DaysOfWeek(rawValue: calendar.firstWeekday) ?? .sunday
}
}
}
public struct MonthSize {
var defaultSize: CGFloat
var months: [CGFloat:[MonthsOfYear]]?
var dates: [CGFloat: [Date]]?
public init(defaultSize: CGFloat, months: [CGFloat:[MonthsOfYear]]? = nil, dates: [CGFloat: [Date]]? = nil) {
self.defaultSize = defaultSize
self.months = months
self.dates = dates
}
}
struct CalendarData {
var months: [Month]
var totalSections: Int
var sectionToMonthMap: [Int: Int]
var totalDays: Int
}
/// Defines a month structure.
public struct Month {
/// Index of the month
let index: Int
/// Start index day for the month.
/// The start is total number of days of previous months
let startDayIndex: Int
/// Start cell index for the month.
/// The start is total number of cells of previous months
let startCellIndex: Int
/// The total number of items in this array are the total number
/// of sections. The actual number is the number of items in each section
let sections: [Int]
/// Number of inDates for this month
public let inDates: Int
/// Number of outDates for this month
public let outDates: Int
/// Maps a section to the index in the total number of sections
let sectionIndexMaps: [Int: Int]
/// Number of rows for the month
public let rows: Int
/// Name of the month
public let name: MonthsOfYear
// Return the total number of days for the represented month
public let numberOfDaysInMonth: Int
// Return the total number of day cells
// to generate for the represented month
var numberOfDaysInMonthGrid: Int {
return numberOfDaysInMonth + inDates + outDates
}
var startSection: Int {
return sectionIndexMaps.keys.min()!
}
// Return the section in which a day is contained
func indexPath(forDay number: Int) -> IndexPath? {
let sectionInfo = sectionFor(day: number)
let externalSection = sectionInfo.externalSection
let internalSection = sectionInfo.internalSection
let dateOfStartIndex = sections[0..<internalSection].reduce(0, +) - inDates + 1
let itemIndex = number - dateOfStartIndex
return IndexPath(item: itemIndex, section: externalSection)
}
private func sectionFor(day: Int) -> (externalSection: Int, internalSection: Int) {
var variableNumber = day
let possibleSection = sections.firstIndex {
let retval = variableNumber + inDates <= $0
variableNumber -= $0
return retval
}!
return (sectionIndexMaps.key(for: possibleSection)!, possibleSection)
}
// Return the number of rows for a section in the month
func numberOfRows(for section: Int, developerSetRows: Int) -> Int {
var retval: Int
guard let theSection = sectionIndexMaps[section] else {
return 0
}
let fullRows = rows / developerSetRows
let partial = sections.count - fullRows
if theSection + 1 <= fullRows {
retval = developerSetRows
} else if fullRows == 0 && partial > 0 {
retval = rows
} else {
retval = 1
}
return retval
}
// Returns the maximum number of a rows for a completely full section
func maxNumberOfRowsForFull(developerSetRows: Int) -> Int {
var retval: Int
let fullRows = rows / developerSetRows
if fullRows < 1 {
retval = rows
} else {
retval = developerSetRows
}
return retval
}
func boundaryIndicesFor(section: Int) -> (startIndex: Int, endIndex: Int)? {
// Check internal sections to see
if !(0..<sections.count ~= section) {
return nil
}
let startIndex = section == 0 ? inDates : 0
var endIndex = sections[section] - 1
if section + 1 == sections.count {
endIndex -= inDates + 1
}
return (startIndex: startIndex, endIndex: endIndex)
}
}
class JTAppleDateConfigGenerator {
static let shared = JTAppleDateConfigGenerator()
private init() {}
func setupMonthInfoDataForStartAndEndDate(_ parameters: ConfigurationParameters)
-> (months: [Month], monthMap: [Int: Int], totalSections: Int, totalDays: Int) {
let differenceComponents = parameters.calendar.dateComponents([.month], from: parameters.startDate, to: parameters.endDate)
let numberOfMonths = differenceComponents.month! + 1
// if we are for example on the same month
// and the difference is 0 we still need 1 to display it
var monthArray: [Month] = []
var monthIndexMap: [Int: Int] = [:]
var section = 0
var startIndexForMonth = 0
var startCellIndexForMonth = 0
var totalDays = 0
let numberOfRowsPerSectionThatUserWants = parameters.numberOfRows
// Section represents # of months. section is used as an offset
// to determine which month to calculate
// Track the month name index
var monthNameIndex = parameters.calendar.component(.month, from: parameters.startDate) - 1
let allMonthsOfYear = MonthsOfYear.allCases
for monthIndex in 0 ..< numberOfMonths {
if let currentMonthDate = parameters.calendar.date(byAdding: .month, value: monthIndex, to: parameters.startDate) {
var numberOfDaysInMonthVariable = parameters.calendar.range(of: .day, in: .month, for: currentMonthDate)!.count
let numberOfDaysInMonthFixed = numberOfDaysInMonthVariable
var numberOfRowsToGenerateForCurrentMonth = 0
var numberOfPreDatesForThisMonth = 0
let predatesGeneration = parameters.generateInDates
if predatesGeneration != .off {
numberOfPreDatesForThisMonth = numberOfInDatesForMonth(currentMonthDate, firstDayOfWeek: parameters.firstDayOfWeek, calendar: parameters.calendar)
numberOfDaysInMonthVariable += numberOfPreDatesForThisMonth
if predatesGeneration == .forFirstMonthOnly && monthIndex != 0 {
numberOfDaysInMonthVariable -= numberOfPreDatesForThisMonth
numberOfPreDatesForThisMonth = 0
}
}
if parameters.generateOutDates == .tillEndOfGrid {
numberOfRowsToGenerateForCurrentMonth = maxNumberOfRowsPerMonth
} else {
let actualNumberOfRowsForThisMonth = Int(ceil(Float(numberOfDaysInMonthVariable) / Float(maxNumberOfDaysInWeek)))
numberOfRowsToGenerateForCurrentMonth = actualNumberOfRowsForThisMonth
}
var numberOfPostDatesForThisMonth = 0
let postGeneration = parameters.generateOutDates
switch postGeneration {
case .tillEndOfGrid, .tillEndOfRow:
numberOfPostDatesForThisMonth =
maxNumberOfDaysInWeek * numberOfRowsToGenerateForCurrentMonth - (numberOfDaysInMonthFixed + numberOfPreDatesForThisMonth)
numberOfDaysInMonthVariable += numberOfPostDatesForThisMonth
default:
break
}
var sectionsForTheMonth: [Int] = []
var sectionIndexMaps: [Int: Int] = [:]
for index in 0..<6 {
// Max number of sections in the month
if numberOfDaysInMonthVariable < 1 {
break
}
monthIndexMap[section] = monthIndex
sectionIndexMaps[section] = index
var numberOfDaysInCurrentSection = numberOfRowsPerSectionThatUserWants * maxNumberOfDaysInWeek
if numberOfDaysInCurrentSection > numberOfDaysInMonthVariable {
numberOfDaysInCurrentSection = numberOfDaysInMonthVariable
// assert(false)
}
totalDays += numberOfDaysInCurrentSection
sectionsForTheMonth.append(numberOfDaysInCurrentSection)
numberOfDaysInMonthVariable -= numberOfDaysInCurrentSection
section += 1
}
monthArray.append(Month(
index: monthIndex,
startDayIndex: startIndexForMonth,
startCellIndex: startCellIndexForMonth,
sections: sectionsForTheMonth,
inDates: numberOfPreDatesForThisMonth,
outDates: numberOfPostDatesForThisMonth,
sectionIndexMaps: sectionIndexMaps,
rows: numberOfRowsToGenerateForCurrentMonth,
name: allMonthsOfYear[monthNameIndex],
numberOfDaysInMonth: numberOfDaysInMonthFixed
))
startIndexForMonth += numberOfDaysInMonthFixed
startCellIndexForMonth += numberOfDaysInMonthFixed + numberOfPreDatesForThisMonth + numberOfPostDatesForThisMonth
// Increment month name
monthNameIndex += 1
if monthNameIndex > 11 { monthNameIndex = 0 }
}
}
return (monthArray, monthIndexMap, section, totalDays)
}
private func numberOfInDatesForMonth(_ date: Date, firstDayOfWeek: DaysOfWeek, calendar: Calendar) -> Int {
let firstDayCalValue: Int
switch firstDayOfWeek {
case .monday: firstDayCalValue = 6
case .tuesday: firstDayCalValue = 5
case .wednesday: firstDayCalValue = 4
case .thursday: firstDayCalValue = 10
case .friday: firstDayCalValue = 9
case .saturday: firstDayCalValue = 8
default: firstDayCalValue = 7
}
var firstWeekdayOfMonthIndex = calendar.component(.weekday, from: date)
firstWeekdayOfMonthIndex -= 1
// firstWeekdayOfMonthIndex should be 0-Indexed
// push it modularly so that we take it back one day so that the
// first day is Monday instead of Sunday which is the default
return (firstWeekdayOfMonthIndex + firstDayCalValue) % maxNumberOfDaysInWeek
}
}
/// Contains the information for visible dates of the calendar.
public struct DateSegmentInfo {
/// Visible pre-dates
public let indates: [(date: Date, indexPath: IndexPath)]
/// Visible month-dates
public let monthDates: [(date: Date, indexPath: IndexPath)]
/// Visible post-dates
public let outdates: [(date: Date, indexPath: IndexPath)]
}
struct SelectedCellData {
let indexPath: IndexPath
let date: Date
var counterIndexPath: IndexPath?
let cellState: CellState
enum DateOwnerCategory {
case inDate, outDate, monthDate
}
var dateBelongsTo: DateOwnerCategory {
switch cellState.dateBelongsTo {
case .thisMonth: return .monthDate
case .previousMonthOutsideBoundary, .previousMonthWithinBoundary: return .inDate
case .followingMonthWithinBoundary, .followingMonthOutsideBoundary: return .outDate
}
}
init(indexPath: IndexPath, counterIndexPath: IndexPath? = nil, date: Date, cellState: CellState) {
self.indexPath = indexPath
self.date = date
self.cellState = cellState
self.counterIndexPath = counterIndexPath
}
}
|
mit
|
a1bb832e45cc0e7f3f6508deb1da3510
| 41.97066 | 170 | 0.634139 | 5.263552 | false | false | false | false |
brentdax/swift
|
validation-test/Evolution/test_protocol_add_requirements.swift
|
1
|
3818
|
// RUN: %target-resilience-test --no-backward-deployment
// REQUIRES: executable_test
import StdlibUnittest
import protocol_add_requirements
var ProtocolAddRequirementsTest = TestSuite("ProtocolAddRequirements")
struct Halogen : ElementProtocol {
var x: Int
func increment() -> Halogen {
return Halogen(x: x + 1)
}
}
func ==(h1: Halogen, h2: Halogen) -> Bool {
return h1.x == h2.x
}
struct AddMethods : AddMethodsProtocol {
func importantOperation() -> Halogen {
return Halogen(x: 0)
}
#if AFTER
func unimportantOperation() -> Halogen {
return Halogen(x: 10)
}
#endif
}
ProtocolAddRequirementsTest.test("AddMethodRequirements") {
let result = doSomething(AddMethods())
#if BEFORE
let expected = [0, 1, 2].map(Halogen.init)
#else
let expected = [0, 10, 11].map(Halogen.init)
#endif
}
struct AddConstructors : AddConstructorsProtocol, Equatable {
var name: String
init(name: String) {
self.name = name
}
}
func ==(a1: AddConstructors, a2: AddConstructors) -> Bool {
return a1.name == a2.name
}
ProtocolAddRequirementsTest.test("AddConstructorsProtocol") {
// Would be nice if [T?] was Equatable...
if getVersion() == 0 {
let result = testConstructorProtocol(AddConstructors.self)
expectEqual(result.count, 1)
expectEqual(result[0], AddConstructors(name: "Puff"))
} else {
let result = testConstructorProtocol(AddConstructors.self)
expectEqual(result.count, 3)
expectEqual(result[0], AddConstructors(name: "Meow meow"))
expectEqual(result[1], nil)
expectEqual(result[2], AddConstructors(name: "Robster the Lobster"))
}
}
class Box<T> {
var value: T
init(value: T) {
self.value = value
}
}
struct AddProperties : AddPropertiesProtocol {
var speedBox: Box<Int> = Box<Int>(value: 160)
var gearBox: Box<Int> = Box<Int>(value: 8000)
var topSpeed: Int {
get {
return speedBox.value
}
nonmutating set {
speedBox.value = newValue
}
}
var maxRPM: Int {
get {
return gearBox.value
}
set {
gearBox.value = newValue
}
}
}
ProtocolAddRequirementsTest.test("AddPropertyRequirements") {
var x = AddProperties()
do {
let expected = (getVersion() == 0
? [160, 8000]
: [160, 8000, 80, 40, 6000])
expectEqual(getProperties(&x), expected)
}
setProperties(&x)
do {
let expected = (getVersion() == 0
? [320, 15000]
: [320, 15000, 160, 80, 13000])
expectEqual(getProperties(&x), expected)
}
}
struct AddSubscript<Key : Hashable, Value> : AddSubscriptProtocol {
var dict: [Key : Value] = [:]
func get(key key: Key) -> Value {
return dict[key]!
}
mutating func set(key key: Key, value: Value) {
dict[key] = value
}
}
ProtocolAddRequirementsTest.test("AddSubscriptRequirements") {
var t = AddSubscript<String, Int>()
t.set(key: "B", value: 20)
doSomething(&t, k1: "A", k2: "B")
expectEqual(t.get(key: "A"), 20)
}
struct AddAssociatedType<T> : AddAssocTypesProtocol { }
ProtocolAddRequirementsTest.test("AddAssociatedTypeRequirements") {
let addString = AddAssociatedType<String>()
let stringResult = doSomethingWithAssocTypes(addString)
if getVersion() == 0 {
expectEqual("there are no associated types yet", stringResult)
} else {
expectEqual("Wrapper<AddAssociatedType<String>>", stringResult)
}
}
ProtocolAddRequirementsTest.test("AddAssociatedConformanceRequirements") {
let addString = AddAssociatedType<String>()
let stringResult = doSomethingWithAssocConformances(addString)
if getVersion() == 0 {
expectEqual("there are no associated conformances yet", stringResult)
} else {
expectEqual("I am a wrapper for AddAssociatedType<String>", stringResult)
}
}
runAllTests()
|
apache-2.0
|
9afa775a409c8312153355a76d313711
| 21.591716 | 77 | 0.668413 | 3.618957 | false | true | false | false |
ming1016/SMCheckProject
|
SMCheckProject/File.swift
|
1
|
5005
|
//
// File.swift
// SMCheckProject
//
// Created by daiming on 2016/10/20.
// Copyright © 2016年 Starming. All rights reserved.
//
import Cocoa
enum FileType {
case FileH,FileM,FileSwift
}
//文件
class File: NSObject {
public var path = "" {
didSet {
if path.hasSuffix(".h") {
type = FileType.FileH
} else if path.hasSuffix(".m") {
type = FileType.FileM
} else if path.hasSuffix(".swift") {
type = FileType.FileSwift
}
name = (path.components(separatedBy: "/").last)!
}
}
public var type = FileType.FileH
public var name = ""
public var content = ""
public var methods = [Method]() //所有方法
public var imports = [Import]() //一级引入
public var recursionImports = [Import]() //递归所有层级引入
public var importObjects = [String:Object]() //所有引入的对象
public var usedObjects = [String:Object]() //已经使用过的对象,无用的引入可以通过对比self.imports里的文件里的定义的objects求差集得到
public var objects = [String:Object]() //文件里定义的所有类
public var macros = [String:Macro]() //文件里定义的宏,全局的也会有一份
public var protocols = [String:Protocol]() //Todo:还没用,作为性能提升用
func des() -> String {
var str = ""
str += "文件路径:\(path)\n"
str += "文件名:\(name)\n"
str += "方法数量:\(methods.count)\n"
str += "方法列表:\n"
for aMethod in methods {
var showStr = "- (\(aMethod.returnType)) "
showStr = showStr.appending(File.desDefineMethodParams(paramArr: aMethod.params))
str += "\n\(showStr)\n"
if aMethod.usedMethod.count > 0 {
str += "用过的方法----------\n"
showStr = ""
for aUsedMethod in aMethod.usedMethod {
showStr = ""
showStr = showStr.appending(File.desUsedMethodParams(paramArr: aUsedMethod.params))
str += "\(showStr)\n"
}
str += "------------------\n"
}
}
//Todo: 添加更多详细的文件里的信息。比如说object里的和新加的marcos等。
return str
}
//类方法
//打印定义方法参数
class func desDefineMethodParams(paramArr:[MethodParam]) -> String {
var showStr = ""
for aParam in paramArr {
if aParam.type == "" {
showStr = showStr.appending("\(aParam.name);")
} else {
showStr = showStr.appending("\(aParam.name):(\(aParam.type))\(aParam.iName);")
}
}
return showStr
}
class func desUsedMethodParams(paramArr:[MethodParam]) -> String {
var showStr = ""
for aUParam in paramArr {
showStr = showStr.appending("\(aUParam.name):")
}
return showStr
}
}
//#import "file.h"
struct Import {
public var fileName = ""
public var libName = ""
public var file = File() //这样记录所有递归出的引用类时就能够直接获取File里的详细信息了
}
//#define REDCOLOR [UIColor HexString:@"000000"]
struct Macro {
public var name = ""
public var tokens = [String]()
}
//@protocol DCOrderListViewDelegate <NSObject>
struct Protocol {
public var name = ""
public var methods = [Method]()
}
//对象
class Object {
public var name = ""
public var superName = ""
public var category = ""
public var usingProtocols = [String]() //协议
public var properties = [Property]() //对象里定义的属性
public var methods = [Method]() //定义的方法
public var protocols = [String:Protocol]() //Todo:还没用,根据属性和来看看那些属性地方会用什么protocol
}
struct Property {
public var name = ""
public var type = ""
public var sets = [String]() //nonatomic strong
}
struct Method {
public var classMethodTf = false //+ or -
public var returnType = ""
public var returnTypePointTf = false
public var returnTypeBlockTf = false
public var params = [MethodParam]()
public var tokens = [String]() //方法内容token
public var usedMethod = [Method]()
public var tmpObjects = [Object]() //临时变量集
public var filePath = "" //定义方法的文件路径,方便修改文件使用
public var pnameId = "" //唯一标识,便于快速比较
}
class MethodParam: NSObject {
public var name = ""
public var type = ""
public var typePointTf = false //是否是指针类型
public var iName = ""
}
class Type: NSObject {
//todo:更多类型
public var name = ""
public var type = 0 //0是值类型 1是指针
}
|
mit
|
28e200fd86dd9168cf1a57c66fdd45bd
| 28.25 | 104 | 0.558704 | 3.862728 | false | false | false | false |
filestack/filestack-ios
|
Sources/Filestack/UI/Internal/PhotoPicker/PhotoAlbumRepository.swift
|
1
|
1090
|
//
// PhotoAlbumRepository.swift
// Filestack
//
// Created by Mihály Papp on 29/05/2018.
// Copyright © 2018 Filestack. All rights reserved.
//
import Photos
struct Album {
let title: String
let elements: [PHAsset]
}
class PhotoAlbumRepository {
private var cachedAlbums: [Album]?
init() {
fetchAndCacheAlbums(completion: nil)
}
func getAlbums(completion: @escaping ([Album]) -> Void) {
if let cachedAlbums = cachedAlbums {
completion(cachedAlbums)
}
fetchAndCacheAlbums(completion: completion)
}
private func fetchAndCacheAlbums(completion: (([Album]) -> Void)?) {
DispatchQueue.global(qos: .default).async {
let collections = PHAssetCollection.allCollections(types: [.smartAlbum, .album])
let allAlbums = collections.map { Album(title: $0.localizedTitle ?? "", elements: $0.allAssets) }
let nonEmptyAlbums = allAlbums.filter { !$0.elements.isEmpty }
self.cachedAlbums = nonEmptyAlbums
completion?(nonEmptyAlbums)
}
}
}
|
mit
|
db140f2cd9d56cef00af53f603d52a9f
| 26.897436 | 109 | 0.637868 | 4.266667 | false | false | false | false |
HongliYu/firefox-ios
|
Storage/SQL/BrowserDB.swift
|
1
|
8895
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import XCGLogger
import Deferred
import Shared
private let log = Logger.syncLogger
public typealias Args = [Any?]
open class BrowserDB {
fileprivate let db: SwiftData
// SQLITE_MAX_VARIABLE_NUMBER = 999 by default. This controls how many ?s can
// appear in a query string.
public static let MaxVariableNumber = 999
public init(filename: String, schema: Schema, files: FileAccessor) {
log.debug("Initializing BrowserDB: \(filename).")
let file = URL(fileURLWithPath: (try! files.getAndEnsureDirectory())).appendingPathComponent(filename).path
self.db = SwiftData(filename: file, schema: schema, files: files)
}
// Returns the SQLite version for debug purposes.
public func sqliteVersion() -> Deferred<Maybe<String>> {
return withConnection { connection -> String in
let result = connection.executeQueryUnsafe("SELECT sqlite_version()", factory: { row -> String in
return row[0] as? String ?? ""
}, withArgs: nil)
return result.asArray().first ?? ""
}
}
// Returns the SQLite compile_options for debug purposes.
public func sqliteCompileOptions() -> Deferred<Maybe<[String]>> {
return withConnection { connection -> [String] in
let result = connection.executeQueryUnsafe("PRAGMA compile_options", factory: { row -> String in
return row[0] as? String ?? ""
}, withArgs: nil)
return result.asArray().filter({ !$0.isEmpty })
}
}
// For testing purposes or other cases where we want to ensure that this `BrowserDB`
// instance has been initialized (schema is created/updated).
public func touch() -> Success {
return withConnection { connection -> Void in
guard let _ = connection as? ConcreteSQLiteDBConnection else {
throw DatabaseError(description: "Could not establish a database connection")
}
}
}
/*
* Opening a WAL-using database with a hot journal cannot complete in read-only mode.
* The supported mechanism for a read-only query against a WAL-using SQLite database is to use PRAGMA query_only,
* but this isn't all that useful for us, because we have a mixed read/write workload.
*/
@discardableResult func withConnection<T>(flags: SwiftData.Flags = .readWriteCreate, _ callback: @escaping (_ connection: SQLiteDBConnection) throws -> T) -> Deferred<Maybe<T>> {
return db.withConnection(flags, callback)
}
func transaction<T>(_ callback: @escaping (_ connection: SQLiteDBConnection) throws -> T) -> Deferred<Maybe<T>> {
return db.transaction(callback)
}
@discardableResult func vacuum() -> Success {
log.debug("Vacuuming a BrowserDB.")
return withConnection({ connection -> Void in
try connection.vacuum()
})
}
@discardableResult func checkpoint() -> Success {
log.debug("Checkpointing a BrowserDB.")
return transaction { connection in
connection.checkpoint()
}
}
public class func varlist(_ count: Int) -> String {
return "(" + Array(repeating: "?", count: count).joined(separator: ", ") + ")"
}
enum InsertOperation: String {
case Insert = "INSERT"
case Replace = "REPLACE"
case InsertOrIgnore = "INSERT OR IGNORE"
case InsertOrReplace = "INSERT OR REPLACE"
case InsertOrRollback = "INSERT OR ROLLBACK"
case InsertOrAbort = "INSERT OR ABORT"
case InsertOrFail = "INSERT OR FAIL"
}
/**
* Insert multiple sets of values into the given table.
*
* Assumptions:
* 1. The table exists and contains the provided columns.
* 2. Every item in `values` is the same length.
* 3. That length is the same as the length of `columns`.
* 4. Every value in each element of `values` is non-nil.
*
* If there are too many items to insert, multiple individual queries will run
* in sequence.
*
* A failure anywhere in the sequence will cause immediate return of failure, but
* will not roll back — use a transaction if you need one.
*/
func bulkInsert(_ table: String, op: InsertOperation, columns: [String], values: [Args]) -> Success {
// Note that there's a limit to how many ?s can be in a single query!
// So here we execute 999 / (columns * rows) insertions per query.
// Note that we can't use variables for the column names, so those don't affect the count.
if values.isEmpty {
log.debug("No values to insert.")
return succeed()
}
let variablesPerRow = columns.count
// Sanity check.
assert(values[0].count == variablesPerRow)
let cols = columns.joined(separator: ", ")
let queryStart = "\(op.rawValue) INTO \(table) (\(cols)) VALUES "
let varString = BrowserDB.varlist(variablesPerRow)
let insertChunk: ([Args]) -> Success = { vals -> Success in
let valuesString = Array(repeating: varString, count: vals.count).joined(separator: ", ")
let args: Args = vals.flatMap { $0 }
return self.run(queryStart + valuesString, withArgs: args)
}
let rowCount = values.count
if (variablesPerRow * rowCount) < BrowserDB.MaxVariableNumber {
return insertChunk(values)
}
log.debug("Splitting bulk insert across multiple runs. I hope you started a transaction!")
let rowsPerInsert = (999 / variablesPerRow)
let chunks = chunk(values, by: rowsPerInsert)
log.debug("Inserting in \(chunks.count) chunks.")
// There's no real reason why we can't pass the ArraySlice here, except that I don't
// want to keep fighting Swift.
return walk(chunks, f: { insertChunk(Array($0)) })
}
func write(_ sql: String, withArgs args: Args? = nil) -> Deferred<Maybe<Int>> {
return withConnection { connection -> Int in
try connection.executeChange(sql, withArgs: args)
let modified = connection.numberOfRowsModified
log.debug("Modified rows: \(modified).")
return modified
}
}
public func forceClose() {
db.forceClose()
}
public func reopenIfClosed() {
db.reopenIfClosed()
}
public func run(_ sql: String, withArgs args: Args? = nil) -> Success {
return run([(sql, args)])
}
func run(_ commands: [String]) -> Success {
return run(commands.map { (sql: $0, args: nil) })
}
/**
* Runs an array of SQL commands. Note: These will all run in order in a transaction and will block
* the caller's thread until they've finished. If any of them fail the operation will abort (no more
* commands will be run) and the transaction will roll back, returning a DatabaseError.
*/
func run(_ commands: [(sql: String, args: Args?)]) -> Success {
if commands.isEmpty {
return succeed()
}
return transaction { connection -> Void in
for (sql, args) in commands {
try connection.executeChange(sql, withArgs: args)
}
}
}
public func runQuery<T>(_ sql: String, args: Args?, factory: @escaping (SDRow) -> T) -> Deferred<Maybe<Cursor<T>>> {
return withConnection { connection -> Cursor<T> in
connection.executeQuery(sql, factory: factory, withArgs: args)
}
}
public func runQueryConcurrently<T>(_ sql: String, args: Args?, factory: @escaping (SDRow) -> T) -> Deferred<Maybe<Cursor<T>>> {
return withConnection(flags: .readOnly) { connection -> Cursor<T> in
connection.executeQuery(sql, factory: factory, withArgs: args)
}
}
func runQueryUnsafe<T, U>(_ sql: String, args: Args?, factory: @escaping (SDRow) -> T, block: @escaping (Cursor<T>) throws -> U) -> Deferred<Maybe<U>> {
return withConnection { connection -> U in
let cursor = connection.executeQueryUnsafe(sql, factory: factory, withArgs: args)
defer { cursor.close() }
return try block(cursor)
}
}
func queryReturnsResults(_ sql: String, args: Args? = nil) -> Deferred<Maybe<Bool>> {
return runQuery(sql, args: args, factory: { _ in true })
>>== { deferMaybe($0[0] ?? false) }
}
func queryReturnsNoResults(_ sql: String, args: Args? = nil) -> Deferred<Maybe<Bool>> {
return runQuery(sql, args: nil, factory: { _ in false })
>>== { deferMaybe($0[0] ?? true) }
}
}
|
mpl-2.0
|
bed9459c004e20606439439009923208
| 37.834061 | 182 | 0.62105 | 4.558175 | false | false | false | false |
alvarorgtr/swift_data_structures
|
DataStructures/GraphEdge.swift
|
1
|
1214
|
//
// GraphEdge.swift
// DataStructures
//
// Created by Álvaro Rodríguez García on 23/3/17.
// Copyright © 2017 DeltaApps. All rights reserved.
//
import Foundation
public protocol GraphEdgeProtocol {
associatedtype Label: Equatable
var from: Label { get }
var to: Label { get }
var either: Label { get }
func other(endpoint: Label) -> Label
}
extension GraphEdgeProtocol {
public var either: Label {
return from
}
public func other(endpoint: Label) -> Label {
return (from == endpoint) ? to : from
}
}
public struct GraphEdge<Label: Equatable>: GraphEdgeProtocol {
public var from: Label
public var to: Label
public init(from: Label, to: Label) {
self.from = from
self.to = to
}
}
public struct DirectedGraphEdge<Label: Equatable>: GraphEdgeProtocol {
public var from: Label
public var to: Label
public init(from: Label, to: Label) {
self.from = from
self.to = to
}
}
public struct DirectedWeightedGraphEdge<Label: Equatable, Weight: Comparable>: GraphEdgeProtocol {
public var from: Label
public var to: Label
public var weight: Weight
public init(from: Label, to: Label, weight: Weight) {
self.from = from
self.to = to
self.weight = weight
}
}
|
gpl-3.0
|
137423b4dbf4e79d9b74a65a2e0855f6
| 18.836066 | 98 | 0.701653 | 3.324176 | false | false | false | false |
netyouli/WHC_Layout
|
WHC_Layout/示例demo/UILayoutGuide/LayoutGuideVC.swift
|
1
|
2396
|
//
// LayoutGuideVC.swift
// WHC_Layout
//
// Created by WHC on 2018/1/18.
// Copyright © 2018年 WHC. All rights reserved.
//
import UIKit
class LayoutGuideVC: UIViewController {
private lazy var view1 = UIView()
private lazy var view2 = UIView()
private lazy var view3 = UIView()
private lazy var guide1 = UILayoutGuide()
private lazy var guide2 = UILayoutGuide()
private lazy var guide3 = UILayoutGuide()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "UILayoutGuide, safeAreaLayoutGuide"
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.white
make()
guide1.whc_Top(0, true)
.whc_Left(10, true)
.whc_Right(10, true)
.whc_Height(30)
view1.whc_Left(10)
.whc_Top(0, toView: guide1)
.whc_Right(0)
.whc_Height(50)
guide2.whc_Left(10)
.whc_Top(0, toView: view1)
.whc_Right(10)
.whc_HeightEqual(guide1)
view2.whc_Left(10)
.whc_Right(10)
.whc_Top(0, toView: guide2)
.whc_HeightEqual(view1)
guide3.whc_Left(10)
.whc_RightEqual(guide2)
.whc_Top(0, toView: view2)
.whc_HeightEqual(guide2)
view3.whc_Left(10)
.whc_RightEqual(view2)
.whc_Top(0, toView: guide3)
.whc_HeightEqual(view2)
}
private func make() {
view1.backgroundColor = UIColor.red
view2.backgroundColor = UIColor.orange
view3.backgroundColor = UIColor.gray
self.view.addSubview(view1)
self.view.addSubview(view2)
self.view.addSubview(view3)
self.view.addLayoutGuide(guide1)
self.view.addLayoutGuide(guide2)
self.view.addLayoutGuide(guide3)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
6b96e0350743b42151f32f843f904f13
| 26.193182 | 106 | 0.611366 | 3.816587 | false | false | false | false |
alblue/swift
|
stdlib/public/core/Misc.swift
|
1
|
4136
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Extern C functions
//===----------------------------------------------------------------------===//
// FIXME: Once we have an FFI interface, make these have proper function bodies
/// Returns if `x` is a power of 2.
@_transparent
public // @testable
func _isPowerOf2(_ x: UInt) -> Bool {
if x == 0 {
return false
}
// Note: use unchecked subtraction because we have checked that `x` is not
// zero.
return x & (x &- 1) == 0
}
/// Returns if `x` is a power of 2.
@_transparent
public // @testable
func _isPowerOf2(_ x: Int) -> Bool {
if x <= 0 {
return false
}
// Note: use unchecked subtraction because we have checked that `x` is not
// `Int.min`.
return x & (x &- 1) == 0
}
#if _runtime(_ObjC)
@_transparent
public func _autorelease(_ x: AnyObject) {
Builtin.retain(x)
Builtin.autorelease(x)
}
#endif
/// Invoke `body` with an allocated, but uninitialized memory suitable for a
/// `String` value.
///
/// This function is primarily useful to call various runtime functions
/// written in C++.
internal func _withUninitializedString<R>(
_ body: (UnsafeMutablePointer<String>) -> R
) -> (R, String) {
let stringPtr = UnsafeMutablePointer<String>.allocate(capacity: 1)
let bodyResult = body(stringPtr)
let stringResult = stringPtr.move()
stringPtr.deallocate()
return (bodyResult, stringResult)
}
// FIXME(ABI)#51 : this API should allow controlling different kinds of
// qualification separately: qualification with module names and qualification
// with type names that we are nested in.
// But we can place it behind #if _runtime(_Native) and remove it from ABI on
// Apple platforms, deferring discussions mentioned above.
@_silgen_name("swift_getTypeName")
public func _getTypeName(_ type: Any.Type, qualified: Bool)
-> (UnsafePointer<UInt8>, Int)
/// Returns the demangled qualified name of a metatype.
public // @testable
func _typeName(_ type: Any.Type, qualified: Bool = true) -> String {
let (stringPtr, count) = _getTypeName(type, qualified: qualified)
return String._fromUTF8Repairing(
UnsafeBufferPointer(start: stringPtr, count: count)).0
}
/// Lookup a class given a name. Until the demangled encoding of type
/// names is stabilized, this is limited to top-level class names (Foo.bar).
public // SPI(Foundation)
func _typeByName(_ name: String) -> Any.Type? {
return _typeByMangledName(name);
}
@_silgen_name("swift_getTypeByMangledName")
internal func _getTypeByMangledName(
_ name: UnsafePointer<UInt8>,
_ nameLength: UInt,
_ numberOfLevels: UInt,
_ parametersPerLevel: UnsafePointer<UInt>,
_ substitutions: UnsafePointer<Any.Type>)
-> Any.Type?
/// Lookup a class given a mangled name. This is a placeholder while we bring
/// up this functionality.
public // TEMPORARY
func _typeByMangledName(_ name: String,
substitutions: [[Any.Type]] = []) -> Any.Type? {
// Map the substitutions to a flat representation that's easier to thread
// through to the runtime.
let numberOfLevels = UInt(substitutions.count)
var parametersPerLevel = [UInt]()
var flatSubstitutions = [Any.Type]()
for level in substitutions {
parametersPerLevel.append(UInt(level.count))
flatSubstitutions.append(contentsOf: level)
}
let nameUTF8 = Array(name.utf8)
return nameUTF8.withUnsafeBufferPointer { (nameUTF8) in
return _getTypeByMangledName(nameUTF8.baseAddress!,
UInt(nameUTF8.endIndex),
numberOfLevels,
parametersPerLevel,
flatSubstitutions)
}
}
|
apache-2.0
|
a8c3384d98de08d0cf1c07b1651a1e4b
| 33.466667 | 80 | 0.647002 | 4.30385 | false | false | false | false |
Adorkable/StoryboardKit
|
StoryboardKit/StoryboardFileVersionedParsers/3.0/StoryboardFile3_0Parser_Storyboard.swift
|
1
|
4210
|
//
// StoryboardFile3_0Parser_Storyboard.swift
// StoryboardKit
//
// Created by Ian on 6/30/15.
// Copyright (c) 2015 Adorkable. All rights reserved.
//
import Foundation
import SWXMLHash
internal extension StoryboardFile3_0Parser {
// MARK: Storyboard
internal class StoryboardInstanceParseInfo : NSObject {
// internal var fileType : String
// internal var fileVersion : String
// internal var toolsVersion : String
// internal var systemVersion : String
// internal var targetRuntime : String
// internal var propertyAccessControl : String
internal var useAutolayout : Bool
internal var useTraitCollections : Bool
internal var initialViewControllerId : String?
init(useAutolayout : Bool, useTraitCollections : Bool, initialViewControllerId : String?) {
self.useAutolayout = useAutolayout
self.useTraitCollections = useTraitCollections
self.initialViewControllerId = initialViewControllerId
super.init()
}
var scenes : [StoryboardInstanceInfo.SceneInfo] = Array<StoryboardInstanceInfo.SceneInfo>()
func add(scene scene : StoryboardInstanceInfo.SceneInfo) {
// TODO: validate that it isn't a dup
self.scenes.append(scene)
}
}
internal func createStoryboardInstance(root : XMLIndexer) -> StoryboardInstanceParseInfo? {
var result : StoryboardInstanceParseInfo?
if let document = root["document"].element
{
let useAutolayout = document.allAttributes["useAutolayout"]?.text == "YES"
let useTraitCollections = document.allAttributes["useTraitCollections"]?.text == "YES"
let initialViewControllerId = document.allAttributes["initialViewController"]?.text
let storyboardInstance = StoryboardInstanceParseInfo(useAutolayout: useAutolayout, useTraitCollections: useTraitCollections, initialViewControllerId: initialViewControllerId)
// TODO: StoryboardFileInfo
// storyboardInstance.fileType = document.attributes["type"]
// storyboardInstance.fileVersion = document.attributes["version"]
// storyboardInstance.toolsVersion = document.attributes["toolsVersion"]
// storyboardInstance.systemVersion = document.attributes["systemVersion"]
// storyboardInstance.targetRuntime = document.attributes["targetRuntime"]
// storyboardInstance.propertyAccessControl = document.attributes["propertyAccessControl"]
result = storyboardInstance
}
return result
}
internal func createStoryboardInstanceInfoFromParsed() throws -> StoryboardFileParser.ParseResult {
var result : StoryboardFileParser.ParseResult
if let storyboardInstanceParseInfo = self.storyboardInstanceParseInfo
{
var initialViewController : ViewControllerInstanceInfo?
if let initialViewControllerId = storyboardInstanceParseInfo.initialViewControllerId
{
initialViewController = self.applicationInfo.viewControllerInstanceWithId(initialViewControllerId)
}
let storyboardInstanceInfo = StoryboardInstanceInfo(useAutolayout: storyboardInstanceParseInfo.useAutolayout, useTraitCollections: storyboardInstanceParseInfo.useTraitCollections, initialViewController: initialViewController)
for sceneInfo in storyboardInstanceParseInfo.scenes
{
storyboardInstanceInfo.add(scene: sceneInfo)
}
result = (storyboardInstanceInfo, self.logs)
} else
{
throw NSError(domain: "Unable to find StoryboardInstanceParseInfo, likely cause was we were unable to parse root of Storyboard file", code: 0, userInfo: nil)
}
return result
}
}
|
mit
|
f6f93815769786990dc3508b8fc021a3
| 41.11 | 237 | 0.641568 | 6.173021 | false | false | false | false |
ericvergnaud/antlr4
|
runtime/Swift/Sources/Antlr4/misc/extension/StringExtension.swift
|
8
|
1288
|
///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
import Foundation
extension String {
func lastIndex(of target: String) -> String.Index? {
if target.isEmpty {
return nil
}
var result: String.Index? = nil
var substring = self[...]
while true {
guard let targetRange = substring.range(of: target) else {
return result
}
result = targetRange.lowerBound
let nextChar = substring.index(after: targetRange.lowerBound)
substring = self[nextChar...]
}
}
subscript(integerRange: Range<Int>) -> String {
let start = index(startIndex, offsetBy: integerRange.lowerBound)
let end = index(startIndex, offsetBy: integerRange.upperBound)
let range = start ..< end
return String(self[range])
}
}
// Implement Substring.hasPrefix, which is not currently in the Linux stdlib.
// https://bugs.swift.org/browse/SR-5627
#if os(Linux)
extension Substring {
func hasPrefix(_ prefix: String) -> Bool {
return String(self).hasPrefix(prefix)
}
}
#endif
|
bsd-3-clause
|
efa9ff903f3e98009633116230286262
| 28.953488 | 77 | 0.621118 | 4.410959 | false | false | false | false |
Ehrippura/firefox-ios
|
Client/Frontend/Browser/TabPeekViewController.swift
|
1
|
7990
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
import ReadingList
import WebKit
protocol TabPeekDelegate: class {
func tabPeekDidAddBookmark(_ tab: Tab)
@discardableResult func tabPeekDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord?
func tabPeekRequestsPresentationOf(_ viewController: UIViewController)
func tabPeekDidCloseTab(_ tab: Tab)
}
class TabPeekViewController: UIViewController, WKNavigationDelegate {
fileprivate static let PreviewActionAddToBookmarks = NSLocalizedString("Add to Bookmarks", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to add current tab to Bookmarks")
fileprivate static let PreviewActionAddToReadingList = NSLocalizedString("Add to Reading List", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to add current tab to Reading List")
fileprivate static let PreviewActionSendToDevice = NSLocalizedString("Send to Device", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to send the current tab to another device")
fileprivate static let PreviewActionCopyURL = NSLocalizedString("Copy URL", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to copy the URL of the current tab to clipboard")
fileprivate static let PreviewActionCloseTab = NSLocalizedString("Close Tab", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to close the current tab")
weak var tab: Tab?
fileprivate weak var delegate: TabPeekDelegate?
fileprivate var clientPicker: UINavigationController?
fileprivate var isBookmarked: Bool = false
fileprivate var isInReadingList: Bool = false
fileprivate var hasRemoteClients: Bool = false
fileprivate var ignoreURL: Bool = false
fileprivate var screenShot: UIImageView?
fileprivate var previewAccessibilityLabel: String!
// Preview action items.
lazy var previewActions: [UIPreviewActionItem] = {
var actions = [UIPreviewActionItem]()
if !self.ignoreURL {
if !self.isInReadingList {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionAddToReadingList, style: .default) { previewAction, viewController in
guard let tab = self.tab else { return }
_ = self.delegate?.tabPeekDidAddToReadingList(tab)
})
}
if !self.isBookmarked {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionAddToBookmarks, style: .default) { previewAction, viewController in
guard let tab = self.tab else { return }
self.delegate?.tabPeekDidAddBookmark(tab)
})
}
if self.hasRemoteClients {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionSendToDevice, style: .default) { previewAction, viewController in
guard let clientPicker = self.clientPicker else { return }
self.delegate?.tabPeekRequestsPresentationOf(clientPicker)
})
}
// only add the copy URL action if we don't already have 3 items in our list
// as we are only allowed 4 in total and we always want to display close tab
if actions.count < 3 {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionCopyURL, style: .default) { previewAction, viewController in
guard let url = self.tab?.canonicalURL else { return }
UIPasteboard.general.url = url
SimpleToast().showAlertWithText(Strings.AppMenuCopyURLConfirmMessage, bottomContainer: self.view)
})
}
}
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionCloseTab, style: .destructive) { previewAction, viewController in
guard let tab = self.tab else { return }
self.delegate?.tabPeekDidCloseTab(tab)
})
return actions
}()
init(tab: Tab, delegate: TabPeekDelegate?) {
self.tab = tab
self.delegate = delegate
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
if let webViewAccessibilityLabel = tab?.webView?.accessibilityLabel {
previewAccessibilityLabel = String(format: NSLocalizedString("Preview of %@", tableName: "3DTouchActions", comment: "Accessibility label, associated to the 3D Touch action on the current tab in the tab tray, used to display a larger preview of the tab."), webViewAccessibilityLabel)
}
// if there is no screenshot, load the URL in a web page
// otherwise just show the screenshot
setupWebView(tab?.webView)
guard let screenshot = tab?.screenshot else { return }
setupWithScreenshot(screenshot)
}
fileprivate func setupWithScreenshot(_ screenshot: UIImage) {
let imageView = UIImageView(image: screenshot)
self.view.addSubview(imageView)
imageView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
screenShot = imageView
screenShot?.accessibilityLabel = previewAccessibilityLabel
}
fileprivate func setupWebView(_ webView: WKWebView?) {
guard let webView = webView, let url = webView.url, !isIgnoredURL(url) else { return }
let clonedWebView = WKWebView(frame: webView.frame, configuration: webView.configuration)
clonedWebView.allowsLinkPreview = false
webView.accessibilityLabel = previewAccessibilityLabel
self.view.addSubview(clonedWebView)
clonedWebView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
clonedWebView.navigationDelegate = self
clonedWebView.load(URLRequest(url: url))
}
func setState(withProfile browserProfile: BrowserProfile, clientPickerDelegate: ClientPickerViewControllerDelegate) {
assert(Thread.current.isMainThread)
guard let tab = self.tab else {
return
}
guard let displayURL = tab.url?.absoluteString, displayURL.characters.count > 0 else {
return
}
let mainQueue = DispatchQueue.main
browserProfile.bookmarks.modelFactory >>== {
$0.isBookmarked(displayURL).uponQueue(mainQueue) {
self.isBookmarked = $0.successValue ?? false
}
}
browserProfile.remoteClientsAndTabs.getClientGUIDs().uponQueue(mainQueue) {
guard let clientGUIDs = $0.successValue else {
return
}
self.hasRemoteClients = !clientGUIDs.isEmpty
let clientPickerController = ClientPickerViewController()
clientPickerController.clientPickerDelegate = clientPickerDelegate
clientPickerController.profile = browserProfile
if let url = tab.url?.absoluteString {
clientPickerController.shareItem = ShareItem(url: url, title: tab.title, favicon: nil)
}
self.clientPicker = UINavigationController(rootViewController: clientPickerController)
}
let result = browserProfile.readingList?.getRecordWithURL(displayURL).successValue!
self.isInReadingList = (result?.url.characters.count ?? 0) > 0
self.ignoreURL = isIgnoredURL(displayURL)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
screenShot?.removeFromSuperview()
screenShot = nil
}
}
|
mpl-2.0
|
437d2aab8b1cab947c432b5408cb21b6
| 45.453488 | 294 | 0.679099 | 5.521769 | false | false | false | false |
DragonCherry/CameraPreviewController
|
CameraPreviewController/Classes/CameraPreviewController+Video.swift
|
1
|
4140
|
//
// CameraPreviewController+Video.swift
// Pods
//
// Created by DragonCherry on 6/7/17.
//
//
import UIKit
import TinyLog
import GPUImage
extension CameraPreviewController {
open func startRecordingVideo(completion: (() -> Void)? = nil) {
if !isRecordingVideo {
guard let formatDescription = camera.inputCamera.activeFormat.formatDescription else { return }
findOrientation(completion: { (orientation) in
let dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription)
let path = (NSTemporaryDirectory() as NSString).appendingPathComponent("\(UUID().uuidString).m4v")
let url = URL(fileURLWithPath: path)
let videoWidth = CGFloat(min(dimensions.width, dimensions.height))
let videoHeight = CGFloat(max(dimensions.width, dimensions.height))
if let writer = GPUImageMovieWriter(movieURL: url, size: CGSize(width: videoWidth, height: videoHeight)) {
self.lastFilter.addTarget(writer)
self.videoWriter = writer
self.videoUrl = url
writer.delegate = self
let radian: ((CGFloat) -> CGFloat) = { degree in
return CGFloat(Double.pi) * degree / CGFloat(180)
}
var transform: CGAffineTransform?
switch orientation {
case .landscapeLeft:
transform = CGAffineTransform(rotationAngle: radian(90))
case .landscapeRight:
transform = CGAffineTransform(rotationAngle: radian(-90))
case .portraitUpsideDown:
transform = CGAffineTransform(rotationAngle: radian(180))
default:
break
}
if self.cameraPosition == .front, orientation.isLandscape {
transform = transform?.scaledBy(x: -1, y: 1)
}
DispatchQueue.main.async {
if let transform = transform {
writer.startRecording(inOrientation: transform)
} else {
writer.startRecording()
}
logi("Recording video with size: \(videoWidth)x\(videoHeight)")
completion?()
}
}
})
}
}
open func finishRecordingVideo(completion: (() -> Void)? = nil) {
if isRecordingVideo {
if let writer = self.videoWriter {
DispatchQueue.main.async {
if let completion = completion {
writer.finishRecording(completionHandler: completion)
} else {
writer.finishRecording()
}
self.lastFilter.removeTarget(writer)
}
} else {
logc("Invalid status error.")
}
}
}
func clearRecordingVideo() {
videoWriter = nil
videoUrl = nil
}
}
// MARK: - GPUImageMovieWriterDelegate
extension CameraPreviewController: GPUImageMovieWriterDelegate {
public func movieRecordingCompleted() {
if let videoUrl = self.videoUrl, isRecordingVideo {
clearRecordingVideo()
DispatchQueue.main.async {
self.delegate?.cameraPreview(self, didSaveVideoAt: videoUrl)
}
}
}
public func movieRecordingFailedWithError(_ error: Error!) {
logi("\(error?.localizedDescription ?? "")")
if isRecordingVideo {
clearRecordingVideo()
DispatchQueue.main.async {
self.delegate?.cameraPreview(self, didFailSaveVideoWithError: error)
}
}
}
}
|
mit
|
572c50aaeafb696f287990d65a09dcbc
| 35.637168 | 122 | 0.507005 | 6.088235 | false | false | false | false |
OpenLocate/openlocate-ios
|
Source/HttpClient.swift
|
1
|
8085
|
//
// HttpClient.swift
//
// Copyright (c) 2017 OpenLocate
//
// 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
typealias HttpClientCompletionHandler = (HttpRequest, HttpResponse) -> Void
typealias Parameters = Any
typealias QueryParameters = [String: String]
typealias ResponseBody = Any
typealias StatusCode = Int
typealias JsonDictionary = [String: Any]
typealias JsonArray = [Any]
// URLSessionProtocol
typealias DataTaskResult = (Data?, URLResponse?, Error?) -> Void
protocol URLSessionProtocol {
func dataTask(with request: URLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol
}
extension URLSession: URLSessionProtocol {
func dataTask(with request: URLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol {
return (dataTask(with: request,
completionHandler: completionHandler) as URLSessionDataTask) as URLSessionDataTaskProtocol
}
}
protocol URLSessionDataTaskProtocol {
func resume()
}
extension URLSessionDataTask: URLSessionDataTaskProtocol { }
// Http Client protocols
struct URLRequestParamters {
let url: String
let params: Parameters?
let queryParams: QueryParameters?
let additionalHeaders: Headers?
}
protocol Postable {
func post(
parameters: URLRequestParamters,
success: @escaping HttpClientCompletionHandler,
failure: @escaping HttpClientCompletionHandler) throws
}
protocol Getable {
func get(
parameters: URLRequestParamters,
success: @escaping HttpClientCompletionHandler,
failure: @escaping HttpClientCompletionHandler) throws
}
enum HttpClientError: Error {
case badRequest
}
// Used to make REST API calls to the backend.
protocol HttpClientType: Postable, Getable {}
final class HttpClient: HttpClientType {
private let session: URLSessionProtocol
init(urlSession: URLSessionProtocol = URLSession(configuration: .default)) {
self.session = urlSession
}
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
// Example: `iOS Example/1.0 (org.openlocate.iOS-Example; build:1; iOS 11.0.0) OpenLocate/1.0.0`
var userAgent: String = {
if let info = Bundle.main.infoDictionary {
let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
let osNameVersion: String = {
let version = ProcessInfo.processInfo.operatingSystemVersion
let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
let osName: String = {
#if os(iOS)
return "iOS"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
let openLocateVersion: String = {
guard let openLocateInfo = Bundle(for: OpenLocate.self).infoDictionary,
let build = openLocateInfo["CFBundleShortVersionString"] else {
return "Unknown"
}
return "OpenLocate/\(build)"
}()
return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(openLocateVersion)"
}
return "OpenLocate"
}()
}
extension HttpClient {
private func execute(_ request: HttpRequest) throws {
guard var urlRequest = URLRequest(request) else {
// if the url could not be created, throw an error
throw HttpClientError.badRequest
}
// make url request from request
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.addValue(userAgent, forHTTPHeaderField: "User-Agent")
// create the task object with the request
let task = session.dataTask(with: urlRequest) { data, response, error in
self.onTaskExecute(
with: request,
data: data,
response: response,
error: error
)
}
// execute the task
task.resume()
}
private func onTaskExecute(
with request: HttpRequest,
data: Data?,
response urlResponse: URLResponse?,
error: Error?) {
// cast response as HTTPURLResponse and get it's status code
guard let httpResponse = urlResponse as? HTTPURLResponse else {
if let failure = request.failureCompletion {
failure(request, HttpResponse.Builder()
.set(statusCode: 400)
.build()
)
}
return
}
let code = httpResponse.statusCode
var body: ResponseBody?
if let data = data, !data.isEmpty {
body = try? JSONSerialization.jsonObject(with: data,
options: .mutableContainers)
}
let response = HttpResponse.Builder()
.set(statusCode: code)
.set(body: body)
.set(error: error)
.build()
if let success = request.successCompletion, response.success {
success(request, response)
return
}
if let failure = request.failureCompletion {
failure(request, response)
}
}
}
// Implement Postable protocol methods
extension HttpClient {
func post(
parameters: URLRequestParamters,
success: @escaping HttpClientCompletionHandler,
failure: @escaping HttpClientCompletionHandler) throws {
let request = HttpRequest.Builder()
.set(url: parameters.url)
.set(method: .post)
.set(params: parameters.params)
.set(queryParams: parameters.queryParams)
.set(additionalHeaders: parameters.additionalHeaders)
.set(success: success)
.set(failure: failure)
.build()
try execute(request)
}
func get(
parameters: URLRequestParamters,
success: @escaping HttpClientCompletionHandler,
failure: @escaping HttpClientCompletionHandler) throws {
let request = HttpRequest.Builder()
.set(url: parameters.url)
.set(method: .get)
.set(params: parameters.params)
.set(queryParams: parameters.queryParams)
.set(additionalHeaders: parameters.additionalHeaders)
.set(success: success)
.set(failure: failure)
.build()
try execute(request)
}
}
|
mit
|
9222f3b9710d63eb23e816f273173425
| 33.404255 | 120 | 0.634879 | 5.123574 | false | false | false | false |
legendecas/Rocket.Chat.iOS
|
Rocket.ChatTests/Views/AvatarViewSpec.swift
|
1
|
2001
|
//
// AvatarViewSpec.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 17/03/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import XCTest
import RealmSwift
@testable import Rocket_Chat
class AvatarViewSpec: XCTestCase {
func testInitializeFromNib() {
XCTAssertNotNil(AvatarView.instantiateFromNib(), "instantiation from nib will work")
}
func testAvatarInitials() {
guard let avatarView = AvatarView.instantiateFromNib() else {
XCTAssert(false)
return
}
XCTAssertTrue(avatarView.initialsFor("") == "?")
XCTAssertTrue(avatarView.initialsFor("?") == "?")
XCTAssertTrue(avatarView.initialsFor("f") == "F")
XCTAssertTrue(avatarView.initialsFor("B") == "B")
XCTAssertTrue(avatarView.initialsFor("fo") == "FO")
XCTAssertTrue(avatarView.initialsFor("FO") == "FO")
XCTAssertTrue(avatarView.initialsFor("fOo") == "FO")
XCTAssertTrue(avatarView.initialsFor("FOO") == "FO")
XCTAssertTrue(avatarView.initialsFor("F.O") == "FO")
XCTAssertTrue(avatarView.initialsFor("F.o") == "FO")
XCTAssertTrue(avatarView.initialsFor("Foo.bar") == "FB")
XCTAssertTrue(avatarView.initialsFor("Foobar.bar") == "FB")
XCTAssertTrue(avatarView.initialsFor("Foobar.bar.zab") == "FZ")
XCTAssertTrue(avatarView.initialsFor("...") == "?")
XCTAssertTrue(avatarView.initialsFor(".foo.b.a") == "?")
XCTAssertTrue(avatarView.initialsFor(".foo.b.a.") == "?")
XCTAssertTrue(avatarView.initialsFor(".foo.b.a.") == "?")
XCTAssertTrue(avatarView.initialsFor(".f.") == "?")
XCTAssertTrue(avatarView.initialsFor(".f......") == "?")
XCTAssertTrue(avatarView.initialsFor(".f......1234f") == "?")
XCTAssertTrue(avatarView.initialsFor(".?.!\"") == "?")
XCTAssertTrue(avatarView.initialsFor("1.2") == "12")
XCTAssertTrue(avatarView.initialsFor("!.!") == "!!")
}
}
|
mit
|
89a3c9d2860e227ad8fadc90908697f0
| 38.215686 | 92 | 0.6245 | 4.385965 | false | true | false | false |
ObjectAlchemist/OOUIKit
|
Sources/_UIKitDelegate/UITextFieldDelegate/EditingTheTextFieldsText/UITextFieldDelegateEditPrinting.swift
|
1
|
1581
|
//
// UITextFieldDelegateEditPrinting.swift
// OOUIKit
//
// Created by Karsten Litsche on 05.11.17.
//
import UIKit
public final class UITextFieldDelegateEditPrinting: NSObject, UITextFieldDelegate {
// MARK: - init
convenience override init() {
fatalError("Not supported!")
}
public init(_ decorated: UITextFieldDelegate, filterKey: String = "") {
self.decorated = decorated
// add space if exist to separate following log
self.filterKey = filterKey.count == 0 ? "" : "\(filterKey) "
}
// MARK: - protocol: UITextFieldDelegate
public final func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
printUI("\(filterKey)textfield shouldChangeCharactersInRange called (\n range=\(range.location)/\(range.length)\n string=\(string)\n)")
return decorated.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) ?? true
}
public final func textFieldShouldClear(_ textField: UITextField) -> Bool {
printUI("\(filterKey)textfield shouldClear called")
return decorated.textFieldShouldClear?(textField) ?? true
}
public final func textFieldShouldReturn(_ textField: UITextField) -> Bool {
printUI("\(filterKey)textfield shouldReturn called")
return decorated.textFieldShouldReturn?(textField) ?? true
}
// MARK: - private
private let decorated: UITextFieldDelegate
private let filterKey: String
}
|
mit
|
843b7bd8c31a14d3566dec05a8289144
| 33.369565 | 145 | 0.678684 | 5.451724 | false | false | false | false |
RefractalDev/Motif
|
MotifKit/TypeFunctions.swift
|
1
|
2813
|
//
// MotifTypeFunctions.swift
// MotifKit
//
// Created by Jonathan Kingsley on 07/05/2016.
// Copyright © 2016 Refractal. All rights reserved.
//
import Foundation
extension Motif {
// Define our completion handler versions
public class func setColor(key: String, file: String = #file, completion: (UIColor) -> Void) {
setObject(UIColor.self, key: key, file: file, completion: completion)
}
public class func setAttributes(key: String, file: String = #file, completion: ([String: AnyObject]) -> Void) {
setObject([String: AnyObject].self, key: key, file: file, completion: completion)
}
public class func setFont(key: String, size: CGFloat, file: String = #file, completion completionHandler: (UIFont) -> Void) {
setObject(UIFont.self, key: key, file: file, completion: { (font: UIFont) in
completionHandler(font.fontWithSize(size))
})
}
public class func setColors(keys: [String], file: String = #file, completion: ([UIColor]) -> Void) {
setObjects(UIColor.self, keys: keys, file: file, completion: completion)
}
public class func setAttributes(keys: [String], file: String = #file, completion: ([[String: AnyObject]]) -> Void) {
setObjects([String: AnyObject].self, keys: keys, file: file, completion: completion)
}
public class func setFonts(keys: [String], sizes: [CGFloat], file: String = #file, completion completionHandler: ([UIFont]) -> Void) {
setObjects(UIFont.self, keys: keys, file: file, completion: { (fonts: [UIFont]) in
var newResult = [UIFont]()
for (index, font) in fonts.enumerate() {
newResult.append(font.fontWithSize(sizes[index]))
}
return completionHandler(newResult)
})
}
// Define our object specific versions
public class func setColor(key: String, target: NSObject..., variable: String, file: String = #file) {
for passedClass in target {
setObject(UIColor.self, key: key, target: passedClass, variable: variable, file: file)
}
}
public class func setAttributes(key: String, target: NSObject..., variable: String, file: String = #file) {
for passedClass in target {
setObject([String: AnyObject].self, key: key, target: passedClass, variable: variable, file: file)
}
}
public class func setFont(key: String, target: NSObject..., variable: String, size: CGFloat, file: String = #file) {
for passedClass in target {
setObject(UIFont.self, key: key, file: file, completion: { (font: UIFont) in
passedClass.setValue(font.fontWithSize(size), forKey: variable)
})
}
}
}
|
mit
|
1b6cf70a6ca448a5b256217896123556
| 39.185714 | 138 | 0.621266 | 4.273556 | false | false | false | false |
boztalay/HabitTracker
|
HabitTracker/PersistenceController.swift
|
1
|
3010
|
//
// PersistenceController.swift
// HabitTracker
//
// Created by Ben Oztalay on 4/9/15.
// Copyright (c) 2015 Ben Oztalay. All rights reserved.
//
import CoreData
class PersistenceController: NSObject {
var managedObjectContext: NSManagedObjectContext
private var privateContext: NSManagedObjectContext
init(completionCallback: (() -> ())?) {
// Create the managed object model
let modelUrl = NSBundle.mainBundle().URLForResource("HabitTracker", withExtension: "momd")!
let managedObjectModel = NSManagedObjectModel(contentsOfURL: modelUrl)!
// Create our private (write to disk) and main (for UI) contexts
self.managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
self.privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
// Create and set the persistent store coordinator
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
self.managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
self.privateContext.persistentStoreCoordinator = persistentStoreCoordinator
super.init()
// Set up the actual store, but do it in the background because it might take a while
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let persistentStoreCoordinator = self.privateContext.persistentStoreCoordinator
var options = NSMutableDictionary()
options[NSMigratePersistentStoresAutomaticallyOption] = true
options[NSInferMappingModelAutomaticallyOption] = true
options[NSSQLitePragmasOption] = ["journal_mode" : "DELETE"]
let fileManager = NSFileManager.defaultManager()
let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last as! NSURL
let storeUrl = documentsUrl.URLByAppendingPathComponent("DataModel.sqlite")
if let completionCallback = completionCallback {
dispatch_async(dispatch_get_main_queue()) {
completionCallback()
}
}
}
}
func save() {
if !self.privateContext.hasChanges && !self.managedObjectContext.hasChanges {
return
}
self.managedObjectContext.performBlockAndWait() {
var error: NSError?
self.managedObjectContext.save(&error)
if error == nil {
println("WARNING: COULDN'T SAVE MAIN CONTEXT!")
}
self.privateContext.performBlock() {
self.privateContext.save(&error)
if error == nil {
println("WARNING: COULDN'T SAVE THE PRIVATE CONTEXT!")
}
}
}
}
}
|
mit
|
cf0c0467cb58ed984e3d7fa2df3c4151
| 39.675676 | 122 | 0.640199 | 6.168033 | false | false | false | false |
Jawbone/CocoaLumberjack
|
Framework/watchOSSwiftTest Extension/Formatter.swift
|
31
|
1358
|
//
// Formatter.swift
// Lumberjack
//
// Created by C.W. Betts on 10/3/14.
//
//
import Foundation
import CocoaLumberjack.DDDispatchQueueLogFormatter
class Formatter: DDDispatchQueueLogFormatter {
let threadUnsafeDateFormatter: NSDateFormatter
override init() {
threadUnsafeDateFormatter = NSDateFormatter()
threadUnsafeDateFormatter.formatterBehavior = .Behavior10_4
threadUnsafeDateFormatter.dateFormat = "HH:mm:ss.SSS"
super.init()
}
override func formatLogMessage(logMessage: DDLogMessage!) -> String {
let dateAndTime = threadUnsafeDateFormatter.stringFromDate(logMessage.timestamp)
var logLevel: String
let logFlag = logMessage.flag
if logFlag.contains(.Error) {
logLevel = "E"
} else if logFlag.contains(.Warning){
logLevel = "W"
} else if logFlag.contains(.Info) {
logLevel = "I"
} else if logFlag.contains(.Debug) {
logLevel = "D"
} else if logFlag.contains(.Verbose) {
logLevel = "V"
} else {
logLevel = "?"
}
let formattedLog = "\(dateAndTime) |\(logLevel)| [\(logMessage.fileName) \(logMessage.function)] #\(logMessage.line): \(logMessage.message)"
return formattedLog;
}
}
|
bsd-3-clause
|
9adf4fb487904e01ecbac2c2e5347bd8
| 28.521739 | 148 | 0.608984 | 4.650685 | false | false | false | false |
austinzheng/swift
|
test/SILGen/scalar_to_tuple_args.swift
|
4
|
3906
|
// RUN: %target-swift-emit-silgen -module-name scalar_to_tuple_args %s | %FileCheck %s
func inoutWithDefaults(_ x: inout Int, y: Int = 0, z: Int = 0) {}
func inoutWithCallerSideDefaults(_ x: inout Int, y: Int = #line) {}
func scalarWithDefaults(_ x: Int, y: Int = 0, z: Int = 0) {}
func scalarWithCallerSideDefaults(_ x: Int, y: Int = #line) {}
func tupleWithDefaults(x x: (Int, Int), y: Int = 0, z: Int = 0) {}
func variadicFirst(_ x: Int...) {}
func variadicSecond(_ x: Int, _ y: Int...) {}
var x = 0
// CHECK: [[X_ADDR:%.*]] = global_addr @$s20scalar_to_tuple_args1xSivp : $*Int
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[INOUT_WITH_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args17inoutWithDefaults_1y1zySiz_S2itF
// CHECK: apply [[INOUT_WITH_DEFAULTS]]([[WRITE]], [[DEFAULT_Y]], [[DEFAULT_Z]])
inoutWithDefaults(&x)
// CHECK: [[LINE_VAL:%.*]] = integer_literal
// CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]]
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[INOUT_WITH_CALLER_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args27inoutWithCallerSideDefaults_1yySiz_SitF
// CHECK: apply [[INOUT_WITH_CALLER_DEFAULTS]]([[WRITE]], [[LINE]])
inoutWithCallerSideDefaults(&x)
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X:%.*]] = load [trivial] [[READ]]
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[SCALAR_WITH_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args0A12WithDefaults_1y1zySi_S2itF
// CHECK: apply [[SCALAR_WITH_DEFAULTS]]([[X]], [[DEFAULT_Y]], [[DEFAULT_Z]])
scalarWithDefaults(x)
// CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]]
// CHECK: [[LINE_VAL:%.*]] = integer_literal
// CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]]
// CHECK: [[SCALAR_WITH_CALLER_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args0A22WithCallerSideDefaults_1yySi_SitF
// CHECK: apply [[SCALAR_WITH_CALLER_DEFAULTS]]([[X]], [[LINE]])
scalarWithCallerSideDefaults(x)
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X1:%.*]] = load [trivial] [[READ]]
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X2:%.*]] = load [trivial] [[READ]]
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[TUPLE_WITH_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args0C12WithDefaults1x1y1zySi_Sit_S2itF
// CHECK: apply [[TUPLE_WITH_DEFAULTS]]([[X1]], [[X2]], [[DEFAULT_Y]], [[DEFAULT_Z]])
tupleWithDefaults(x: (x,x))
// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: ([[ARRAY:%.*]], [[MEMORY:%.*]]) = destructure_tuple [[ALLOC_ARRAY]]
// CHECK: [[ADDR:%.*]] = pointer_to_address [[MEMORY]]
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X:%.*]] = load [trivial] [[READ]]
// CHECK: store [[X]] to [trivial] [[ADDR]]
// CHECK: [[VARIADIC_FIRST:%.*]] = function_ref @$s20scalar_to_tuple_args13variadicFirstyySid_tF
// CHECK: apply [[VARIADIC_FIRST]]([[ARRAY]])
variadicFirst(x)
// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: ([[ARRAY:%.*]], [[MEMORY:%.*]]) = destructure_tuple [[ALLOC_ARRAY]]
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X:%.*]] = load [trivial] [[READ]]
// CHECK: [[VARIADIC_SECOND:%.*]] = function_ref @$s20scalar_to_tuple_args14variadicSecondyySi_SidtF
// CHECK: apply [[VARIADIC_SECOND]]([[X]], [[ARRAY]])
variadicSecond(x)
|
apache-2.0
|
6aa7e42660e006f268230fb10009efc4
| 53.222222 | 126 | 0.598105 | 3.130714 | false | false | false | false |
mrdepth/EVEOnlineAPI
|
EVEAPI/EVEAPI/Helper.swift
|
1
|
5814
|
//
// helper.swift
// ESI
//
// Created by Artem Shimanski on 10.04.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import Foundation
import Alamofire
import Futures
//fileprivate let salt = Int(truncatingBitPattern: 0x9e3779b9 as UInt64)
//
//func combine(seed: inout Int, value: Int) {
// seed ^= value &+ salt &+ (seed << 6) &+ (seed >> 2);
//}
extension DateFormatter {
static var esiDateFormatter: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter
}
static var esiDateTimeFormatter: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter
}
}
extension Data: ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = self
return request
}
}
extension Promise {
func set<T>(response: DataResponse<T>, cached: TimeInterval?) where Value == ESI.Result<T>{
do {
switch response.result {
case let .success(value):
let metadata = response.response?.allHeaderFields
let expires = (metadata?["Expires"] as? String).flatMap({DateFormatter.rfc822DateFormatter.date(from: $0)}) ?? cached.map({Date.init(timeIntervalSinceNow: $0)})
try fulfill(ESI.Result<T>(value: value, expires: expires, metadata: metadata as? [String: String]))
case let .failure(error):
throw error
}
}
catch {
try! fail(error)
}
}
}
public enum ESIError: LocalizedError {
case internalError
// case network(error: Error)
// case objectSerialization(reason: String)
// case serialization(error: Error)
// case unauthorized(reason: String)
case server(error: String, ssoStatus: Int?)
case notFound
case forbidden
case invalidFormat(Any.Type, Any)
case objectSerialization(reason: String)
case dateFormatError
public var errorDescription: String? {
switch self {
case let .server(error, ssoStatus?):
return String(format: NSLocalizedString("%@ (Status: %d)", comment: ""), error, ssoStatus)
case let .server(error, nil):
return error
default:
return nil
}
}
}
protocol DateFormatted {
var dateFormatter: DateFormatter? {get}
}
public protocol JSONCoding {
var json: Any {get}
init(json: Any) throws
}
public protocol HTTPQueryable {
var httpQuery: String? {get}
}
extension Int: JSONCoding, HTTPQueryable {
public var json: Any {
return self
}
public init(json: Any) throws {
guard let v = json as? Int else {throw ESIError.invalidFormat(Swift.type(of: self), json)}
self = v
}
public var httpQuery: String? {
return String(self)
}
}
extension Int64: JSONCoding, HTTPQueryable {
public var json: Any {
return self
}
public init(json: Any) throws {
guard let v = json as? Int64 else {throw ESIError.invalidFormat(Swift.type(of: self), json)}
self = v
}
public var httpQuery: String? {
return String(self)
}
}
extension Double: JSONCoding, HTTPQueryable {
public var json: Any {
return self
}
public init(json: Any) throws {
guard let v = json as? Double else {throw ESIError.invalidFormat(Swift.type(of: self), json)}
self = v
}
public var httpQuery: String? {
return String(self)
}
}
extension Float: JSONCoding, HTTPQueryable {
public var json: Any {
return self
}
public init(json: Any) throws {
guard let v = json as? Float else {throw ESIError.invalidFormat(Swift.type(of: self), json)}
self = v
}
public var httpQuery: String? {
return String(self)
}
}
extension Bool: JSONCoding, HTTPQueryable {
public var json: Any {
return self
}
public init(json: Any) throws {
guard let v = json as? Bool else {throw ESIError.invalidFormat(Swift.type(of: self), json)}
self = v
}
public var httpQuery: String? {
return String(self)
}
}
extension Date: JSONCoding, HTTPQueryable {
public var json: Any {
return DateFormatter.esiDateTimeFormatter.string(from: self)
}
public init(json: Any) throws {
guard let s = json as? String, let d = DateFormatter.esiDateTimeFormatter.date(from: s) else {throw ESIError.invalidFormat(Swift.type(of: self), json)}
self = d
}
public var httpQuery: String? {
return DateFormatter.esiDateFormatter.string(from: self)
}
}
extension Data: JSONCoding {
public var json: Any {
return self
}
public init(json: Any) throws {
guard let v = json as? Data else {throw ESIError.invalidFormat(Swift.type(of: self), json)}
self = v
}
}
extension String: JSONCoding, HTTPQueryable {
public var json: Any {
return self
}
public init(json: Any) throws {
if json is NSNull {
self = ""
}
else {
guard let v = json as? String else {throw ESIError.invalidFormat(Swift.type(of: self), json)}
self = v
}
}
public var httpQuery: String? {
return self
}
}
extension Array: JSONCoding, HTTPQueryable {
public var json: Any {
return compactMap{($0 as? JSONCoding)?.json}
}
public init(json: Any) throws {
guard let v = json as? [Any],
let type = Element.self as? JSONCoding.Type else {throw ESIError.invalidFormat(Swift.type(of: self), json)}
self = try v.compactMap{try type.init(json: $0) as? Element}
}
public var httpQuery: String? {
let a = compactMap{ ($0 as? HTTPQueryable)?.httpQuery }
return !a.isEmpty ? a.joined(separator: ",") : nil
}
}
/*struct AnyJSONCoding<T: JSONCoding>: JSONCoding {
public init(_ base: T) {
self.base = base
}
public var base: T
var json: Any {
return base.json
}
}*/
|
mit
|
d753b1673e0f2b5cb98714bdb824e932
| 20.771536 | 164 | 0.696198 | 3.299092 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK
|
AviasalesSDKTemplate/Source/HotelsSource/Filters/FilterCellFactories/FilterCells/FilterItemsWithSelectionFilterCell.swift
|
1
|
1851
|
import UIKit
class FilterItemsWithSelectionFilterCell: HLDividerCell {
private struct Consts {
static let leftPadding: CGFloat = 15
static let rightPadding: CGFloat = 15
static let topPadding: CGFloat = 15
static let bottomPadding: CGFloat = 15
static let chooseButtonToFilterViewOffset: CGFloat = 15
static let chooseButtonHeight: CGFloat = 20
}
@IBOutlet weak var chooseButton: UIButton!
var chooseButtonPressedAction: (() -> Void)?
@IBAction func chooseButtonPressed() {
chooseButtonPressedAction?()
}
@IBOutlet weak var cancelableFilterView: CancelableFilterView!
var tableWidth: CGFloat?
private (set) var filter: Filter!
class func height(for tableWidth: CGFloat, with filter: Filter, stringFilterItems: [StringFilterItem]) -> CGFloat {
let leftAndRight = Consts.leftPadding + Consts.rightPadding
let topAndBottom = Consts.topPadding + Consts.bottomPadding
let cancelableFilterViewHeight = CancelableFilterView.height(for: tableWidth - leftAndRight, with: filter, stringFilterItems: stringFilterItems)
let chooseButton = Consts.chooseButtonHeight + (cancelableFilterViewHeight > 0 ? Consts.chooseButtonToFilterViewOffset : 0)
return cancelableFilterViewHeight + topAndBottom + chooseButton
}
func configure(with filter: Filter, and filterItems: [StringFilterItem]) {
if let tableWidth = tableWidth {
let leftAndRight = Consts.leftPadding + Consts.rightPadding
cancelableFilterView.tableWidth = tableWidth - leftAndRight
}
cancelableFilterView.configure(with: filter, and: filterItems)
}
override func awakeFromNib() {
super.awakeFromNib()
chooseButton.setTitleColor(JRColorScheme.actionColor(), for: .normal)
}
}
|
mit
|
b91eea4951fcc6f3b901b04ed14f9577
| 36.77551 | 152 | 0.712588 | 5.11326 | false | false | false | false |
brocktonpoint/CCCodeExample
|
CCCodeExample/JSONFetch.swift
|
1
|
4890
|
/*
The MIT License (MIT)
Copyright (c) 2015 CawBox
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
enum JSONFetchError: ErrorType {
case NoError
case InvalidData
case InvalidFormatting
}
class JSONFetch {
private let jsonURL = NSURL (string: "http://jsonplaceholder.typicode.com/photos")!
static let PhotosDidChangeNotification = "com.cawbox.notification.photosdidchange"
init () {
loadJSONFromCache {
error in
print ("complete")
}
}
private var photos = [JSONPhoto]() {
didSet {
NSNotificationCenter.defaultCenter().postNotificationName (
JSONFetch.PhotosDidChangeNotification,
object: nil
)
}
}
var allPhotos: [JSONPhoto] {
return photos
}
}
extension JSONFetch {
var cacheURL: NSURL? {
guard let cacheURL = NSFileManager.defaultManager().URLsForDirectory (
.CachesDirectory,
inDomains: .UserDomainMask
).first else {
return nil
}
return cacheURL.URLByAppendingPathComponent ("json.cache")
}
private func loadJSONFromCache (completion: (JSONFetchError) -> Void) {
guard let cacheURL = cacheURL,
let cachedData = NSData (contentsOfURL: cacheURL) else {
loadJSONFromURL (completion)
return
}
guard let jsonData = try? NSJSONSerialization.JSONObjectWithData (cachedData, options: []) else {
completion (.InvalidData)
return
}
guard let json = jsonData as? [[String: AnyObject]] else {
completion (.InvalidFormatting)
return
}
loadJSON (json, completion: completion)
}
private func loadJSONFromURL (completion: (JSONFetchError) -> Void) {
let fetch = NSURLSession.sharedSession().dataTaskWithURL (jsonURL) {
data, response, error in
guard let data = data else {
completion (.InvalidData)
return
}
// Write the JSON to a cache, to be used on next launch
if let cacheURL = self.cacheURL {
data.writeToURL (cacheURL, atomically: true)
}
guard let jsonData = try? NSJSONSerialization.JSONObjectWithData (data, options: []) else {
completion (.InvalidData)
return
}
guard let json = jsonData as? [[String: AnyObject]] else {
completion (.InvalidFormatting)
return
}
self.loadJSON (json, completion: completion)
}
fetch.resume ()
}
private func loadJSON (json: [[String: AnyObject]], completion: (JSONFetchError) -> Void) {
var fetchedPhotos = [JSONPhoto]()
for photoJson in json {
guard let albumId = photoJson["albumId"] as? Int,
let id = photoJson["id"] as? Int,
let title = photoJson["title"] as? String,
let sourceURL = photoJson["url"] as? String,
let thumbnailURL = photoJson["thumbnailUrl"] as? String else {
continue
}
fetchedPhotos.append (JSONPhoto (
id: id,
album: albumId,
title: title,
sourceURL: sourceURL,
thumbnailURL: thumbnailURL
)
)
if fetchedPhotos.count > 250 {
break
}
}
dispatch_async(dispatch_get_main_queue()) {
self.photos = fetchedPhotos
completion (.NoError)
}
}
}
|
mit
|
f0290cb845c0502366f7d0febe5da0fd
| 31.606667 | 105 | 0.5818 | 5.469799 | false | false | false | false |
codestergit/swift
|
test/Generics/function_defs.swift
|
2
|
10856
|
// RUN: %target-typecheck-verify-swift
//===----------------------------------------------------------------------===//
// Type-check function definitions
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Basic type checking
//===----------------------------------------------------------------------===//
protocol EqualComparable {
func isEqual(_ other: Self) -> Bool
}
func doCompare<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) -> Bool {
var b1 = t1.isEqual(t2)
if b1 {
return true
}
return t1.isEqual(u) // expected-error {{cannot invoke 'isEqual' with an argument list of type '(U)'}} expected-note {{expected an argument list of type '(T)'}}
}
protocol MethodLessComparable {
func isLess(_ other: Self) -> Bool
}
func min<T : MethodLessComparable>(_ x: T, y: T) -> T {
if (y.isLess(x)) { return y }
return x
}
//===----------------------------------------------------------------------===//
// Interaction with existential types
//===----------------------------------------------------------------------===//
func existential<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) {
var eqComp : EqualComparable = t1 // expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}}
eqComp = u
if t1.isEqual(eqComp) {} // expected-error{{cannot invoke 'isEqual' with an argument list of type '(EqualComparable)'}}
// expected-note @-1 {{expected an argument list of type '(T)'}}
if eqComp.isEqual(t2) {} // expected-error{{member 'isEqual' cannot be used on value of protocol type 'EqualComparable'; use a generic constraint instead}}
}
protocol OtherEqualComparable {
func isEqual(_ other: Self) -> Bool
}
func otherExistential<T : EqualComparable>(_ t1: T) {
var otherEqComp : OtherEqualComparable = t1 // expected-error{{value of type 'T' does not conform to specified type 'OtherEqualComparable'}}
otherEqComp = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}}
_ = otherEqComp
var otherEqComp2 : OtherEqualComparable // expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}}
otherEqComp2 = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}}
_ = otherEqComp2
_ = t1 as EqualComparable & OtherEqualComparable // expected-error{{'T' is not convertible to 'EqualComparable & OtherEqualComparable'; did you mean to use 'as!' to force downcast?}} {{10-12=as!}} expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}}
}
protocol Runcible {
func runce<A>(_ x: A)
func spoon(_ x: Self)
}
func testRuncible(_ x: Runcible) { // expected-error{{protocol 'Runcible' can only be used as a generic constraint}}
x.runce(5)
}
//===----------------------------------------------------------------------===//
// Overloading
//===----------------------------------------------------------------------===//
protocol Overload {
associatedtype A
associatedtype B
func getA() -> A
func getB() -> B
func f1(_: A) -> A
func f1(_: B) -> B
func f2(_: Int) -> A // expected-note{{found this candidate}}
func f2(_: Int) -> B // expected-note{{found this candidate}}
func f3(_: Int) -> Int // expected-note {{found this candidate}}
func f3(_: Float) -> Float // expected-note {{found this candidate}}
func f3(_: Self) -> Self // expected-note {{found this candidate}}
var prop : Self { get }
}
func testOverload<Ovl : Overload, OtherOvl : Overload>(_ ovl: Ovl, ovl2: Ovl,
other: OtherOvl) {
var a = ovl.getA()
var b = ovl.getB()
// Overloading based on arguments
_ = ovl.f1(a)
a = ovl.f1(a)
_ = ovl.f1(b)
b = ovl.f1(b)
// Overloading based on return type
a = ovl.f2(17)
b = ovl.f2(17)
ovl.f2(17) // expected-error{{ambiguous use of 'f2'}}
// Check associated types from different objects/different types.
a = ovl2.f2(17)
a = ovl2.f1(a)
other.f1(a) // expected-error{{cannot invoke 'f1' with an argument list of type '(Ovl.A)'}}
// expected-note @-1 {{overloads for 'f1' exist with these partially matching parameter lists: (Self.A), (Self.B)}}
// Overloading based on context
var f3i : (Int) -> Int = ovl.f3
var f3f : (Float) -> Float = ovl.f3
var f3ovl_1 : (Ovl) -> Ovl = ovl.f3
var f3ovl_2 : (Ovl) -> Ovl = ovl2.f3
var f3ovl_3 : (Ovl) -> Ovl = other.f3 // expected-error{{ambiguous reference to member 'f3'}}
var f3i_unbound : (Ovl) -> (Int) -> Int = Ovl.f3
var f3f_unbound : (Ovl) -> (Float) -> Float = Ovl.f3
var f3f_unbound2 : (OtherOvl) -> (Float) -> Float = OtherOvl.f3
var f3ovl_unbound_1 : (Ovl) -> (Ovl) -> Ovl = Ovl.f3
var f3ovl_unbound_2 : (OtherOvl) -> (OtherOvl) -> OtherOvl = OtherOvl.f3
}
//===----------------------------------------------------------------------===//
// Subscripting
//===----------------------------------------------------------------------===//
protocol Subscriptable {
associatedtype Index
associatedtype Value
func getIndex() -> Index
func getValue() -> Value
subscript (index : Index) -> Value { get set }
}
protocol IntSubscriptable {
associatedtype ElementType
func getElement() -> ElementType
subscript (index : Int) -> ElementType { get }
}
func subscripting<T : Subscriptable & IntSubscriptable>(_ t: T) {
var index = t.getIndex()
var value = t.getValue()
var element = t.getElement()
value = t[index]
t[index] = value // expected-error{{cannot assign through subscript: 't' is a 'let' constant}}
element = t[17]
t[42] = element // expected-error{{cannot assign through subscript: subscript is get-only}}
// Suggests the Int form because we prefer concrete matches to generic matches in diagnosis.
t[value] = 17 // expected-error{{cannot convert value of type 'T.Value' to expected argument type 'Int'}}
}
//===----------------------------------------------------------------------===//
// Static functions
//===----------------------------------------------------------------------===//
protocol StaticEq {
static func isEqual(_ x: Self, y: Self) -> Bool
}
func staticEqCheck<T : StaticEq, U : StaticEq>(_ t: T, u: U) {
if t.isEqual(t, t) { return } // expected-error{{static member 'isEqual' cannot be used on instance of type 'T'}}
if T.isEqual(t, y: t) { return }
if U.isEqual(u, y: u) { return }
T.isEqual(t, y: u) // expected-error{{cannot invoke 'isEqual' with an argument list of type '(T, y: U)'}} expected-note {{expected an argument list of type '(T, y: T)'}}
}
//===----------------------------------------------------------------------===//
// Operators
//===----------------------------------------------------------------------===//
protocol Ordered {
static func <(lhs: Self, rhs: Self) -> Bool
}
func testOrdered<T : Ordered>(_ x: T, y: Int) {
if y < 100 || 500 < y { return }
if x < x { return }
}
//===----------------------------------------------------------------------===//
// Requires clauses
//===----------------------------------------------------------------------===//
func conformanceViaRequires<T>(_ t1: T, t2: T) -> Bool
where T : EqualComparable, T : MethodLessComparable {
let b1 = t1.isEqual(t2)
if b1 || t1.isLess(t2) {
return true
}
}
protocol GeneratesAnElement {
associatedtype Element : EqualComparable
func makeIterator() -> Element
}
protocol AcceptsAnElement {
associatedtype Element : MethodLessComparable
func accept(_ e : Element)
}
func impliedSameType<T : GeneratesAnElement>(_ t: T)
where T : AcceptsAnElement {
t.accept(t.makeIterator())
let e = t.makeIterator(), e2 = t.makeIterator()
if e.isEqual(e2) || e.isLess(e2) {
return
}
}
protocol GeneratesAssoc1 {
associatedtype Assoc1 : EqualComparable
func get() -> Assoc1
}
protocol GeneratesAssoc2 {
associatedtype Assoc2 : MethodLessComparable
func get() -> Assoc2
}
func simpleSameType<T : GeneratesAssoc1, U : GeneratesAssoc2>
(_ t: T, u: U) -> Bool
where T.Assoc1 == U.Assoc2 {
return t.get().isEqual(u.get()) || u.get().isLess(t.get())
}
protocol GeneratesMetaAssoc1 {
associatedtype MetaAssoc1 : GeneratesAnElement
func get() -> MetaAssoc1
}
protocol GeneratesMetaAssoc2 {
associatedtype MetaAssoc2 : AcceptsAnElement
func get() -> MetaAssoc2
}
func recursiveSameType
<T : GeneratesMetaAssoc1, U : GeneratesMetaAssoc2, V : GeneratesAssoc1>
(_ t: T, u: U)
where T.MetaAssoc1 == V.Assoc1, V.Assoc1 == U.MetaAssoc2
{
t.get().accept(t.get().makeIterator())
let e = t.get().makeIterator(), e2 = t.get().makeIterator()
if e.isEqual(e2) || e.isLess(e2) {
return
}
}
// <rdar://problem/13985164>
protocol P1 {
associatedtype Element
}
protocol P2 {
associatedtype AssocP1 : P1
func getAssocP1() -> AssocP1
}
func beginsWith2<E0: P1, E1: P1>(_ e0: E0, _ e1: E1) -> Bool
where E0.Element == E1.Element,
E0.Element : EqualComparable
{
}
func beginsWith3<S0: P2, S1: P2>(_ seq1: S0, _ seq2: S1) -> Bool
where S0.AssocP1.Element == S1.AssocP1.Element,
S1.AssocP1.Element : EqualComparable {
return beginsWith2(seq1.getAssocP1(), seq2.getAssocP1())
}
// FIXME: Test same-type constraints that try to equate things we
// don't want to equate, e.g., T == U.
//===----------------------------------------------------------------------===//
// Bogus requirements
//===----------------------------------------------------------------------===//
func nonTypeReq<T>(_: T) where T : Wibble {} // expected-error{{use of undeclared type 'Wibble'}}
func badProtocolReq<T>(_: T) where T : Int {} // expected-error{{type 'T' constrained to non-protocol type 'Int'}}
func nonTypeSameType<T>(_: T) where T == Wibble {} // expected-error{{use of undeclared type 'Wibble'}}
func nonTypeSameType2<T>(_: T) where Wibble == T {} // expected-error{{use of undeclared type 'Wibble'}}
func sameTypeEq<T>(_: T) where T = T {} // expected-error{{use '==' for same-type requirements rather than '='}} {{34-35===}}
// expected-warning@-1{{redundant same-type constraint 'T' == 'T'}}
func badTypeConformance1<T>(_: T) where Int : EqualComparable {} // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}}
func badTypeConformance2<T>(_: T) where T.Blarg : EqualComparable { } // expected-error{{'Blarg' is not a member type of 'T'}}
func badSameType<T, U : GeneratesAnElement, V>(_ : T)
where T == U.Element, U.Element == V {} // expected-error{{same-type requirement makes generic parameters 'T' and 'V' equivalent}}
|
apache-2.0
|
92a9a67b0406e7f4ba8d305a9cd72dd0
| 35.307692 | 375 | 0.577008 | 3.992644 | false | false | false | false |
colbylwilliams/bugtrap
|
iOS/Code/Swift/bugTrap/bugTrapKit/Trackers/Pivotal/PivotalProxy.swift
|
1
|
9163
|
//
// PivotalProxy.swift
// bugTrap
//
// Created by Colby L Williams on 10/19/14.
// Copyright (c) 2014 bugTrap. All rights reserved.
//
import Foundation
import UIKit
class PivotalProxy : TrackerProxy {
let restProxy = RestProxy()
var token = ""
required init() {
}
func getUrl(path: String) -> NSURL {
let urlString = "https://www.pivotaltracker.com/services/v5/\(path)"
let url = NSURL(string: urlString)
return url!
}
func authenticate(data trackerData: [DataKeys : String], callback: (Result<Bool>) -> ()) {
if let tok = trackerData[DataKeys.Token] { // Check for the token first
token = tok
}
if !token.isEmpty { // Do we have a token? If so, try to authenticate
restProxy.setAuthentication(.Token, token: token)
verifyAuthentication(callback)
} else {
Log.error("PivotalProxy init", "Error Initializing PivotalProxy: No Token. Attempting to get Token with Username and Password.")
var username = "", password = ""
if let user = trackerData[DataKeys.UserName] { // Do we have a username?
username = user
} else {
Log.error("PivotalProxy init", "Error Initializing PivotalProxy: No Username")
callback(.Error(NSError(domain: "PivotalProxy", code: 401, userInfo: nil)))
}
if let pass = trackerData[DataKeys.Password] { // Do we have a password?
password = pass
} else {
Log.error("PivotalProxy init", "Error Initializing PivotalProxy: No Password")
callback(.Error(NSError(domain: "PivotalProxy", code: 401, userInfo: nil)))
}
if !username.isEmpty && !password.isEmpty { // Do we have both username and password? If so try to authenticate
self.restProxy.setAuthentication(.Basic, username: username, password: password)
verifyAuthentication(callback)
} else {
Log.error("PivotalProxy authenticate", "Error Initializing PivotalProxy: No Username or Password")
callback(.Error(NSError(domain: "PivotalProxy", code: 401, userInfo: nil)))
}
}
}
func verifyAuthentication(callback: (Result<Bool>) -> ()) {
Log.info("PivotalProxy verifyAuthentication")
if self.token.isEmpty {
let url = NSURL(string: "https://www.pivotaltracker.com/services/v5/me")
restProxy.get(url!, authenticationType: .Basic) { result in
switch result {
case let .Error(error):
callback(.Error(error))
return
case let .Value(wrapped):
if let json = wrapped.value {
let pivotalMe = PivotalMe.deserialize(json)
Log.info("PivotalProxy", pivotalMe)
if let newToken = pivotalMe?.apiToken {
self.token = newToken
self.restProxy.setAuthentication(.Token, token: newToken)
Analytics.Shared.trackerLogin(TrackerType.PivotalTracker.rawValue)
callback(.Value(Wrapped(true)))
} else {
callback(.Value(Wrapped(false)))
}
} else {
callback(.Value(Wrapped(false)))
}
}
}
} else {
getProjects() { projectsResult in
switch projectsResult {
case let .Error(error):
callback(.Error(error))
case .Value(_):
Analytics.Shared.trackerLogin(TrackerType.PivotalTracker.rawValue)
callback(.Value(Wrapped(true)))
}
}
}
}
func getProjects(callback: (Result<[PivotalProject]>) -> ()) {
let url = getUrl("projects")
restProxy.get(url, authenticationType: .Token) { result in
switch result {
case let .Error(error):
callback(.Error(error))
return
case let .Value(wrapped):
if let json = wrapped.value {
let pivotalProjects = PivotalProject.deserializeAll(json)
callback(.Value(Wrapped(pivotalProjects)))
} else {
callback(.Value(Wrapped(nil)))
}
}
}
}
// func getProjectDetails(project: SimpleItem, callback: (Result<PivotalProject>) -> ()) {
//
// let url = getUrl("projects/\(project.id!).json")
//
// restProxy.get(url, authenticationType: .Token) { result in
// switch result {
// case let .Error(error):
// callback(.Error(error))
// return
// case let .Value(wrapped):
// if let json = wrapped.value {
// let project = PivotalProject.deserialize(json)
// callback(.Value(Wrapped(project)))
// } else {
// callback(.Value(Wrapped(nil)))
// }
// }
// }
// }
func getPeople(projectId: Int, callback: (Result<[PivotalProjectMembership]>) -> ()) {
let url = getUrl("projects/\(projectId)/memberships")
restProxy.get(url, authenticationType: .Token) { result in
switch result {
case let .Error(error):
callback(.Error(error))
return
case let .Value(wrapped):
if let json = wrapped.value {
let memberships = PivotalProjectMembership.deserializeAll(json)
callback(.Value(Wrapped(memberships)))
} else {
callback(.Value(Wrapped(nil)))
}
}
}
}
func getProjectLabels(projectId: Int, callback: (Result<[PivotalLabel]>) -> ()) {
let url = getUrl("projects/\(projectId)/labels")
restProxy.get(url, authenticationType: .Token) { result in
switch result {
case let .Error(error):
callback(.Error(error))
return
case let .Value(wrapped):
if let json = wrapped.value {
let labels = PivotalLabel.deserializeAll(json)
callback(.Value(Wrapped(labels)))
} else {
callback(.Value(Wrapped(nil)))
}
}
}
}
// func getPriorityLevels(callback: (Result<[SimpleItem]>) -> ()) {
//
// let url = getUrl("priority_levels.json")
//
// restProxy.get(url, authenticationType: .Token) { result in
// switch result {
// case let .Error(error):
// callback(.Error(error))
// return
// case let .Value(wrapped):
// if let json = wrapped.value {
// let priorityLevels = SimpleItem.deserializeAll(json)
// callback(.Value(Wrapped(priorityLevels)))
// } else {
// callback(.Value(Wrapped(nil)))
// }
// }
// }
// }
func getDataForUrl(url: String, callback: (Result<NSData>) -> ()) {
if let nsUrl = NSURL(string: url) {
restProxy.getData(nsUrl, callback: callback)
} else {
callback(.Value(Wrapped(NSData())))
}
}
func uploadAttachments(projectId: Int, callback: (Result<[PivotalAttachment]>) -> ()) {
Log.info("PivotalProxy", "uploadAttachments")
let url = getUrl("projects/\(projectId)/uploads")
TrapState.Shared.getImageDataForSnapshots { imageData in
let imageCount = imageData.count
var iterationCount = 0
var attachments = [PivotalAttachment]()
for image in imageData {
self.restProxy.postAttachment(url, authenticationType: .Token, attachment: image) { result in
iterationCount++
switch result {
case let .Error(error):
// let's just not add this project
Log.error("PivotalProxy", error)
case let .Value(wrapped):
if let json = wrapped.value {
if let attachment = PivotalAttachment.deserialize(json) {
attachment.projectId = projectId
attachments.append(attachment)
}
}
}
// are we finished?
if iterationCount == imageCount {
callback(.Value(Wrapped(attachments)))
}
}
}
}
}
func createIssueForProject(issue: PivotalStory, project: PivotalProject, callback: (Result<PivotalStory>) -> ()) {
Log.info("PivotalProxy", "createIssueForProject")
let url = getUrl("projects/\(project.id!)/stories")
// get snapshot ids then itterate
if TrapState.Shared.hasSnapshotImages {
self.uploadAttachments(project.id!) { attachmentsResult in
switch attachmentsResult {
case let .Error(error):
//let's just not add this project
Log.error("PivotalProxy", error)
case let .Value(wrapped):
if let attachments = wrapped.value {
let comment = PivotalComment()
comment.fileAttachments = attachments
issue.comments.append(comment)
}
self.restProxy.post(url, authenticationType: .Token, object: issue) { postResult in
switch postResult {
case let .Error(error):
callback(.Error(error))
return
case let .Value(wrapped):
if let json = wrapped.value {
let story = PivotalStory.deserialize(json)
callback(.Value(Wrapped(story)))
} else {
callback(.Value(Wrapped(nil)))
}
}
}
}
}
} else { //no attachments to post
restProxy.post(url, authenticationType: .Token, object: issue) { result in
switch result {
case let .Error(error):
callback(.Error(error))
return
case let .Value(wrapped):
if let json = wrapped.value {
let story = PivotalStory.deserialize(json)
callback(.Value(Wrapped(story)))
} else {
callback(.Value(Wrapped(nil)))
}
}
}
}
}
}
|
mit
|
d7ac9f218474d7e49778caedd27464c1
| 24.96034 | 132 | 0.609626 | 3.736949 | false | false | false | false |
marsal-silveira/iStackOS
|
Pods/Gloss/Sources/ExtensionDictionary.swift
|
1
|
4997
|
//
// ExtensionDictionary.swift
// Gloss
//
// Copyright (c) 2015 Harlan Kellaway
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Dictionary {
// MARK: - Public functions
/**
Parses the nested dictionary from the keyPath
components separated with a delimiter and gets the value
:parameter: keyPath KeyPath with delimiter
:parameter: delimiter Delimiter
:returns: Value from the nested dictionary
*/
public func valueForKeyPath(keyPath: String, withDelimiter delimiter: String = GlossKeyPathDelimiter()) -> AnyObject? {
var keys = keyPath.componentsSeparatedByString(delimiter)
guard let first = keys.first as? Key else {
print("[Gloss] Unable to use string as key on type: \(Key.self)")
return nil
}
guard let value = self[first] as? AnyObject else {
return nil
}
keys.removeAtIndex(0)
if !keys.isEmpty, let subDict = value as? JSON {
let rejoined = keys.joinWithSeparator(delimiter)
return subDict.valueForKeyPath(rejoined, withDelimiter: delimiter)
}
return value
}
// MARK: - Internal functions
/**
Creates a dictionary from a list of elements, this allows us to map, flatMap
and filter dictionaries.
:parameter: elements Elements to add to the new dictionary
*/
init(elements: [Element]) {
self.init()
for (key, value) in elements {
self[key] = value
}
}
/**
Flat map for dictionary.
:parameter: transform Transform
*/
func flatMap<KeyPrime : Hashable, ValuePrime>(transform: (Key, Value) throws -> (KeyPrime, ValuePrime)?) rethrows -> [KeyPrime : ValuePrime] {
return Dictionary<KeyPrime,ValuePrime>(elements: try flatMap({ (key, value) in
return try transform(key, value)
}))
}
/**
Adds entries from provided dictionary
:parameter: other Dictionary to add entries from
:parameter: delimiter Keypath delimiter
*/
mutating func add(other: Dictionary, delimiter: String = GlossKeyPathDelimiter()) -> () {
for (key, value) in other {
if let key = key as? String {
self.setValue(valueToSet: value, forKeyPath: key, withDelimiter: delimiter)
} else {
self.updateValue(value, forKey:key)
}
}
}
// MARK: - Private functions
/**
Creates a nested dictionary from the keyPath
components separated with a delimiter and sets the value
:parameter: valueToSet Value to set
:parameter: keyPath KeyPath of the value
*/
private mutating func setValue(valueToSet val: Any, forKeyPath keyPath: String, withDelimiter delimiter: String = GlossKeyPathDelimiter()) {
var keys = keyPath.componentsSeparatedByString(delimiter)
guard let first = keys.first as? Key else {
print("[Gloss] Unable to use string as key on type: \(Key.self)")
return
}
keys.removeAtIndex(0)
if keys.isEmpty, let settable = val as? Value {
self[first] = settable
} else {
let rejoined = keys.joinWithSeparator(delimiter)
var subdict: JSON = [:]
if let sub = self[first] as? JSON {
subdict = sub
}
subdict.setValue(valueToSet: val, forKeyPath: rejoined, withDelimiter: delimiter)
if let settable = subdict as? Value {
self[first] = settable
} else {
print("[Gloss] Unable to set value: \(subdict) to dictionary of type: \(self.dynamicType)")
}
}
}
}
|
mit
|
d3681888f346e39a9de22d98d7e9e3dc
| 32.993197 | 146 | 0.61637 | 5.057692 | false | false | false | false |
urbanthings/urbanthings-sdk-apple
|
UnitTests/Infrastructure/TestPlacePoint.swift
|
1
|
667
|
//
// TestPlacePoint.swift
// UrbanThingsAPI
//
// Created by Mark Woollard on 05/05/2016.
// Copyright © 2016 UrbanThings. All rights reserved.
//
import Foundation
@testable import UTAPI
struct TestPlacePoint : PlacePoint {
let name:String?
let primaryCode:String
let importSource:String? = nil
let localityName:String? = nil
let country:String? = nil
let hasResourceStatus:Bool = false
let location:Location
let placePointType: PlacePointType = .Place
init(primaryCode:String, name:String, location:Location) {
self.primaryCode = primaryCode
self.name = name
self.location = location
}
}
|
apache-2.0
|
4bafaf12ef7890e59fd21e10dd3247d6
| 22.821429 | 62 | 0.689189 | 4.060976 | false | true | false | false |
vector-im/vector-ios
|
Riot/Categories/UIButton.swift
|
1
|
2218
|
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
extension UIButton {
/// Enable multiple lines for button title.
///
/// - Parameter textAlignment: Title text alignement. Default `NSTextAlignment.center`.
func vc_enableMultiLinesTitle(textAlignment: NSTextAlignment = .center) {
guard let titleLabel = self.titleLabel else {
return
}
titleLabel.lineBreakMode = .byWordWrapping
titleLabel.numberOfLines = 0
titleLabel.textAlignment = textAlignment
}
/// Set background color as an image.
/// Useful to automatically adjust highlighted background if `adjustsImageWhenHighlighted` property is set to true or disabled background when `adjustsImageWhenDisabled`is set to true.
///
/// - Parameters:
/// - color: The background color to set as an image.
/// - state: The control state for wich to apply this color.
func vc_setBackgroundColor(_ color: UIColor, for state: UIControl.State) {
let image = UIImage.vc_image(from: color)
self.setBackgroundImage(image, for: state)
}
/// Shortcut to button label property `adjustsFontForContentSizeCategory`
@IBInspectable
var vc_adjustsFontForContentSizeCategory: Bool {
get {
return self.titleLabel?.adjustsFontForContentSizeCategory ?? false
}
set {
self.titleLabel?.adjustsFontForContentSizeCategory = newValue
}
}
/// Set title font and enable Dynamic Type support
func vc_setTitleFont(_ font: UIFont) {
self.vc_adjustsFontForContentSizeCategory = true
self.titleLabel?.font = font
}
}
|
apache-2.0
|
08ab0e60eb801c2dd2a9638f0cfd2e32
| 35.966667 | 188 | 0.692065 | 5.182243 | false | false | false | false |
recurly/recurly-client-ios
|
RecurlySDK-iOS/Models/REApplePayInfo.swift
|
1
|
1981
|
//
// REApplePayInfo.swift
// RecurlySDK-iOS
//
// Created by Carlos Landaverde on 12/1/22.
//
import Foundation
import PassKit
public struct REApplePayInfo {
// Customize the 'Total' label default value
public var totalLabel: String = "Total"
// Current country code
public var countryCode: String = "US"
// Current currency code
public var currencyCode: String = "USD"
// Identifies the merchant, as previously agreed with Apple. Must match one of the merchant
// identifiers in the application's entitlement.
// https://developer.apple.com/apple-pay/sandbox-testing/
public var merchantIdentifier: String = "merchant.com.YOURDOMAIN.YOURAPPNAME"
// Required fields of user to create billing info
public var requiredContactFields: Set<PKContactField> = [.name, .phoneNumber, .postalAddress]
// Items displayed on the summary of purchase
public var purchaseItems: [REApplePayItem]
// MARK: - Initializers
public init(purchaseItems: [REApplePayItem]) {
self.purchaseItems = purchaseItems
}
// Internal function to retrieve the 'PKPaymentSummaryItem' objects
// This items are displayed on a list to calculate the total of the purchase
public func paymentSummaryItems() -> [PKPaymentSummaryItem] {
var result = [PKPaymentSummaryItem]()
var total = NSDecimalNumber(string: "0.00")
purchaseItems.forEach {
result.append(PKPaymentSummaryItem(label: $0.amountLabel, amount: $0.amount, type: .final))
total = $0.amount.adding(total)
}
// Calculate the final total of items
if result.count > 0 {
result.append(PKPaymentSummaryItem(label: totalLabel, amount: total, type: .final))
} else {
result.append(PKPaymentSummaryItem(label: totalLabel, amount: total, type: .pending))
}
return result
}
}
|
mit
|
6683fec219e803cfc9516cee5e48bff1
| 32.016667 | 103 | 0.657749 | 4.585648 | false | false | false | false |
Why51982/SLDouYu
|
SLDouYu/SLDouYu/Classes/Home/Controller/SLAmuseViewController.swift
|
1
|
2231
|
//
// SLAmuseViewController.swift
// SLDouYu
//
// Created by CHEUNGYuk Hang Raymond on 2016/10/31.
// Copyright © 2016年 CHEUNGYuk Hang Raymond. All rights reserved.
//
import UIKit
//MARK: - 定义常量
private let kItemMargin: CGFloat = 10
private let kItemW: CGFloat = (kScreenW - 3 * kItemMargin) / 2
private let kNormalItemH: CGFloat = kItemW * 3 / 4
private let kPrettyItemH: CGFloat = kItemW * 4 / 3
private let kHeaderViewH: CGFloat = 50
private let kCycleViewH: CGFloat = kScreenW * 3 / 8
private let kGameViewH: CGFloat = 90
private let kAmuseMenuViewH: CGFloat = 200
private let kNormalCellReuseIdentifier = "kNormalCellReuseIdentifier"
private let kPrettyCellReuseIdentifier = "kPrettyCellReuseIdentifier"
private let kHeaderViewReuseIdentifier = "kHeaderViewReuseIdentifier"
class SLAmuseViewController: SLBaseAnchorViewController {
//MARK: - 懒加载
fileprivate lazy var amuseVM: SLAmuseViewModel = SLAmuseViewModel()
fileprivate lazy var amuseMenuView: SLAmuseMenuView = {
let amuseMenuView = SLAmuseMenuView.amuseMenuView()
amuseMenuView.frame = CGRect(x: 0, y: -kAmuseMenuViewH, width: kScreenW, height: kAmuseMenuViewH)
return amuseMenuView
}()
}
//MARK: - 设置UI界面
extension SLAmuseViewController {
override func setupUI() {
super.setupUI()
//添加amuseView
collectionView.addSubview(amuseMenuView)
//设置collectionView的内边距
collectionView.contentInset = UIEdgeInsets(top: kAmuseMenuViewH, left: 0, bottom: 0, right: 0)
}
}
extension SLAmuseViewController {
//发送网络请求
override func loadData() {
//给父类的ViewModel赋值
baseVM = amuseVM
//发送网络请求
amuseVM.loadAmuseData {
//刷新表格
self.collectionView.reloadData()
//调整数据
var tempGroups = self.amuseVM.anchorGroups
tempGroups.removeFirst()
self.amuseMenuView.groups = tempGroups
//停止动画,并显示collectionView
self.loadDataFinished()
}
}
}
|
mit
|
85f921460912bf061d73d20ab33f83a6
| 26.558442 | 105 | 0.659755 | 4.779279 | false | false | false | false |
riehs/on-the-map
|
On the Map/On the Map/MapPoints.swift
|
1
|
4715
|
//
// MapPoints.swift
// On the Map
//
// Created by Daniel Riehs on 3/23/15.
// Copyright (c) 2015 Daniel Riehs. All rights reserved.
//
import Foundation
class MapPoints: NSObject {
//These shared keys are used by all students in Udacity.com's "iOS Networking with Swift" course.
let ParseID: String = "QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr"
let ParseAPIKey: String = "QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY"
//Database URL:
let DatabaseURL: String = "https://parse.udacity.com/parse/classes"
//Each point on the map is a StudentInformation object. They are stored in this array.
var mapPoints = [StudentInformation]()
//This will be set to true when a new pin is submitted to Parse.
var needToRefreshData = false
//Get student information from Parse.
func fetchData(_ completionHandler: @escaping (_ success: Bool, _ errorString: String?) -> Void) {
let request = NSMutableURLRequest(url: URL(string: "\(self.DatabaseURL)/StudentLocation")!)
request.addValue(self.ParseID, forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue(self.ParseAPIKey, forHTTPHeaderField: "X-Parse-REST-API-Key")
//Initialize session.
let session = URLSession.shared
//Initialize task for data retrieval.
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
if error != nil {
completionHandler(false, error!.localizedDescription)
}
//Parse the data.
let parsingError: NSError? = nil
let parsedResult = (try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)) as! NSDictionary
if let error = parsingError {
completionHandler(false, error.description)
} else {
if let results = parsedResult["results"] as? [[String : AnyObject]] {
//Clear existing data from the mapPoints object.
self.mapPoints.removeAll(keepingCapacity: true)
//Re-populate the mapPoints object with refreshed data.
for result in results {
self.mapPoints.append(StudentInformation(dictionary: result))
}
//Setting this flag to true lets the TabViewController know that the views need to be reloaded.
self.needToRefreshData = true
completionHandler(true, nil)
} else {
completionHandler(false, "Could not find results in \(parsedResult)")
}
}
})
task.resume()
}
//Submit a student information node to Parse.
func submitData(_ latitude: String, longitude: String, addressField: String, link: String, completionHandler: @escaping (_ success: Bool, _ errorString: String?) -> Void) {
let request = NSMutableURLRequest(url: URL(string: "\(self.DatabaseURL)/StudentLocation")!)
request.httpMethod = "POST"
request.addValue(self.ParseID, forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue(self.ParseAPIKey, forHTTPHeaderField: "X-Parse-REST-API-Key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//API Parameters.
request.httpBody = "{\"uniqueKey\": \"\(UdacityLogin.sharedInstance().userKey)\", \"firstName\": \"\(UdacityLogin.sharedInstance().firstName)\", \"lastName\": \"\(UdacityLogin.sharedInstance().lastName)\",\"mapString\": \"\(addressField)\", \"mediaURL\": \"\(link)\",\"latitude\": \(latitude), \"longitude\": \(longitude)}".data(using: String.Encoding.utf8)
//Initialize session.
let session = URLSession.shared
//Initialize task for data retrieval.
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
if error != nil {
completionHandler(false, "Failed to submit data.")
} else {
completionHandler(true, nil)
}
})
task.resume()
/*
// Code for deleting a record - Not currently in use.
let request = NSMutableURLRequest(URL: NSURL(string: "\(self.DatabaseURL)/StudentLocation/UniqueObjectId")!)
request.HTTPMethod = "DELETE"
request.addValue(self.ParseID, forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue(self.ParseAPIKey, forHTTPHeaderField: "X-Parse-REST-API-Key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { data, response, error in
if error != nil {
completionHandler(success: false, errorString: "Failed to submit data.")
} else {
completionHandler(success: true, errorString: nil)
}
}
task.resume()
// End code for deleting.
*/
}
//Allows other classes to reference a common instance of the mapPoints array.
class func sharedInstance() -> MapPoints {
struct Singleton {
static var sharedInstance = MapPoints()
}
return Singleton.sharedInstance
}
}
|
mit
|
55166a647d980056652c393c56ff337d
| 32.678571 | 359 | 0.720891 | 3.893476 | false | false | false | false |
nathawes/swift
|
test/attr/attr_inlinable.swift
|
8
|
10313
|
// RUN: %target-typecheck-verify-swift -swift-version 5
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-testing
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -enable-testing
@inlinable struct TestInlinableStruct {}
// expected-error@-1 {{'@inlinable' attribute cannot be applied to this declaration}}
@inlinable @usableFromInline func redundantAttribute() {}
// expected-warning@-1 {{'@inlinable' declaration is already '@usableFromInline'}}
private func privateFunction() {}
// expected-note@-1 2{{global function 'privateFunction()' is not '@usableFromInline' or public}}
fileprivate func fileprivateFunction() {}
// expected-note@-1{{global function 'fileprivateFunction()' is not '@usableFromInline' or public}}
func internalFunction() {}
// expected-note@-1 2{{global function 'internalFunction()' is not '@usableFromInline' or public}}
@usableFromInline func versionedFunction() {}
public func publicFunction() {}
private struct PrivateStruct {}
// expected-note@-1 3{{struct 'PrivateStruct' is not '@usableFromInline' or public}}
struct InternalStruct {}
// expected-note@-1 3{{struct 'InternalStruct' is not '@usableFromInline' or public}}
@usableFromInline struct VersionedStruct {
@usableFromInline init() {}
}
public struct PublicStruct {
public init() {}
@inlinable public var storedProperty: Int
// expected-error@-1 {{'@inlinable' attribute cannot be applied to stored properties}}
@inlinable public lazy var lazyProperty: Int = 0
// expected-error@-1 {{'@inlinable' attribute cannot be applied to stored properties}}
}
public struct Struct {
@_transparent
public func publicTransparentMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a '@_transparent' function}}
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// expected-error@-1 {{global function 'internalFunction()' is internal and cannot be referenced from a '@_transparent' function}}
fileprivateFunction()
// expected-error@-1 {{global function 'fileprivateFunction()' is fileprivate and cannot be referenced from a '@_transparent' function}}
privateFunction()
// expected-error@-1 {{global function 'privateFunction()' is private and cannot be referenced from a '@_transparent' function}}
}
@inlinable
public func publicInlinableMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inlinable' function}}
let _: PublicStruct
let _: VersionedStruct
let _: InternalStruct
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}}
let _: PrivateStruct
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}}
let _ = PublicStruct.self
let _ = VersionedStruct.self
let _ = InternalStruct.self
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}}
let _ = PrivateStruct.self
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}}
let _ = PublicStruct()
let _ = VersionedStruct()
let _ = InternalStruct()
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}}
let _ = PrivateStruct()
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}}
}
private func privateMethod() {}
// expected-note@-1 {{instance method 'privateMethod()' is not '@usableFromInline' or public}}
@_transparent
@usableFromInline
func versionedTransparentMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a '@_transparent' function}}
privateMethod()
// expected-error@-1 {{instance method 'privateMethod()' is private and cannot be referenced from a '@_transparent' function}}
}
@inlinable
func internalInlinableMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inlinable' function}}
}
@_transparent
func internalTransparentMethod() {
struct Nested {}
// OK
}
@inlinable
private func privateInlinableMethod() {
// expected-error@-2 {{'@inlinable' attribute can only be applied to public declarations, but 'privateInlinableMethod' is private}}
struct Nested {}
// OK
}
@inline(__always)
func internalInlineAlwaysMethod() {
struct Nested {}
// OK
}
}
// Make sure protocol extension members can reference protocol requirements
// (which do not inherit the @usableFromInline attribute).
@usableFromInline
protocol VersionedProtocol {
associatedtype T
func requirement() -> T
}
extension VersionedProtocol {
func internalMethod() {}
// expected-note@-1 {{instance method 'internalMethod()' is not '@usableFromInline' or public}}
@inlinable
func versionedMethod() -> T {
internalMethod()
// expected-error@-1 {{instance method 'internalMethod()' is internal and cannot be referenced from an '@inlinable' function}}
return requirement()
}
}
enum InternalEnum {
// expected-note@-1 2{{enum 'InternalEnum' is not '@usableFromInline' or public}}
// expected-note@-2 {{type declared here}}
case apple
case orange
}
@inlinable public func usesInternalEnum() {
_ = InternalEnum.apple
// expected-error@-1 {{enum 'InternalEnum' is internal and cannot be referenced from an '@inlinable' function}}
let _: InternalEnum = .orange
// expected-error@-1 {{enum 'InternalEnum' is internal and cannot be referenced from an '@inlinable' function}}
}
@usableFromInline enum VersionedEnum {
case apple
case orange
case pear(InternalEnum)
// expected-error@-1 {{type of enum case in '@usableFromInline' enum must be '@usableFromInline' or public}}
case persimmon(String)
}
@inlinable public func usesVersionedEnum() {
_ = VersionedEnum.apple
let _: VersionedEnum = .orange
_ = VersionedEnum.persimmon
}
// Inherited initializers - <rdar://problem/34398148>
@usableFromInline
@_fixed_layout
class Base {
@usableFromInline
init(x: Int) {}
}
@usableFromInline
@_fixed_layout
class Middle : Base {}
@usableFromInline
@_fixed_layout
class Derived : Middle {
@inlinable
init(y: Int) {
super.init(x: y)
}
}
// More inherited initializers
@_fixed_layout
public class Base2 {
@inlinable
public init(x: Int) {}
}
@_fixed_layout
@usableFromInline
class Middle2 : Base2 {}
@_fixed_layout
@usableFromInline
class Derived2 : Middle2 {
@inlinable
init(y: Int) {
super.init(x: y)
}
}
// Even more inherited initializers - https://bugs.swift.org/browse/SR-10940
@_fixed_layout
public class Base3 {}
// expected-note@-1 {{initializer 'init()' is not '@usableFromInline' or public}}
@_fixed_layout
public class Derived3 : Base3 {
@inlinable
public init(_: Int) {}
// expected-error@-1 {{initializer 'init()' is internal and cannot be referenced from an '@inlinable' function}}
}
@_fixed_layout
public class Base4 {}
@_fixed_layout
@usableFromInline
class Middle4 : Base4 {}
// expected-note@-1 {{initializer 'init()' is not '@usableFromInline' or public}}
@_fixed_layout
@usableFromInline
class Derived4 : Middle4 {
@inlinable
public init(_: Int) {}
// expected-error@-1 {{initializer 'init()' is internal and cannot be referenced from an '@inlinable' function}}
}
// Stored property initializer expressions.
//
// Note the behavior here does not depend on the state of the -enable-library-evolution
// flag; the test runs with both the flag on and off. Only the explicit
// presence of a '@_fixed_layout' attribute determines the behavior here.
let internalGlobal = 0
// expected-note@-1 {{let 'internalGlobal' is not '@usableFromInline' or public}}
public let publicGlobal = 0
struct InternalStructWithInit {
var x = internalGlobal // OK
var y = publicGlobal // OK
}
public struct PublicResilientStructWithInit {
var x = internalGlobal // OK
var y = publicGlobal // OK
}
private func privateIntReturningFunc() -> Int { return 0 }
internal func internalIntReturningFunc() -> Int { return 0 }
@frozen
public struct PublicFixedStructWithInit {
var x = internalGlobal // expected-error {{let 'internalGlobal' is internal and cannot be referenced from a property initializer in a '@frozen' type}}
var y = publicGlobal // OK
static var z = privateIntReturningFunc() // OK
static var a = internalIntReturningFunc() // OK
}
public struct KeypathStruct {
var x: Int
// expected-note@-1 {{property 'x' is not '@usableFromInline' or public}}
@inlinable public func usesKeypath() {
_ = \KeypathStruct.x
// expected-error@-1 {{property 'x' is internal and cannot be referenced from an '@inlinable' function}}
}
}
public struct HasInternalSetProperty {
public internal(set) var x: Int // expected-note {{setter for 'x' is not '@usableFromInline' or public}}
@inlinable public mutating func setsX() {
x = 10 // expected-error {{setter for 'x' is internal and cannot be referenced from an '@inlinable' function}}
}
}
@usableFromInline protocol P {
typealias T = Int
}
extension P {
@inlinable func f() {
_ = T.self // ok, typealias inherits @usableFromInline from P
}
}
// rdar://problem/60605117
public struct PrivateInlinableCrash {
@inlinable // expected-error {{'@inlinable' attribute can only be applied to public declarations, but 'formatYesNo' is private}}
private func formatYesNo(_ value: Bool) -> String {
value ? "YES" : "NO"
}
}
// https://bugs.swift.org/browse/SR-12404
@inlinable public func inlinableOuterFunction() {
func innerFunction1(x: () = privateFunction()) {}
// expected-error@-1 {{global function 'privateFunction()' is private and cannot be referenced from a default argument value}}
func innerFunction2(x: () = internalFunction()) {}
// expected-error@-1 {{global function 'internalFunction()' is internal and cannot be referenced from a default argument value}}
func innerFunction3(x: () = versionedFunction()) {}
func innerFunction4(x: () = publicFunction()) {}
}
|
apache-2.0
|
f78c7c5379021fc948ab814204b08d2e
| 31.130841 | 152 | 0.712402 | 4.281029 | false | false | false | false |
edragoev1/pdfjet
|
Sources/PDFjet/QRUtil.swift
|
1
|
5528
|
/**
*
Copyright 2009 Kazuhiko Arase
URL: http://www.d-project.com/
Licensed under the MIT license:
http://www.opensource.org/licenses/mit-license.php
The word "QR Code" is registered trademark of
DENSO WAVE INCORPORATED
http://www.denso-wave.com/qrcode/faqpatent-e.html
*/
import Foundation
/**
* QRUtil
* @author Kazuhiko Arase
*/
class QRUtil {
static let singleton = QRUtil()
private var G15: Int
private var G15_MASK: Int
private init() {
G15 = 1 << 10
G15 |= 1 << 8
G15 |= 1 << 5
G15 |= 1 << 4
G15 |= 1 << 2
G15 |= 1 << 1
G15 |= 1
G15_MASK = 1 << 14
G15_MASK |= 1 << 12
G15_MASK |= 1 << 10
G15_MASK |= 1 << 4
G15_MASK |= 1 << 1
}
func getErrorCorrectPolynomial(_ errorCorrectLength: Int) -> Polynomial {
var a = Polynomial([1], 0)
for i in 0..<errorCorrectLength {
a = a.multiply(Polynomial([1, QRMath.singleton.gexp(i)], 0))
}
return a
}
func getMask(
_ maskPattern: Int,
_ i: Int,
_ j: Int) -> Bool {
switch maskPattern {
case MaskPattern.PATTERN000 : return (i + j) % 2 == 0
case MaskPattern.PATTERN001 : return (i % 2) == 0
case MaskPattern.PATTERN010 : return (j % 3) == 0
case MaskPattern.PATTERN011 : return (i + j) % 3 == 0
case MaskPattern.PATTERN100 : return (i / 2 + j / 3) % 2 == 0
case MaskPattern.PATTERN101 : return (i * j) % 2 + (i * j) % 3 == 0
case MaskPattern.PATTERN110 : return ((i * j) % 2 + (i * j) % 3) % 2 == 0
case MaskPattern.PATTERN111 : return ((i * j) % 3 + (i + j) % 2) % 2 == 0
default :
Swift.print("mask: " + String(describing: maskPattern))
}
return false
}
func getLostPoint(_ qrCode: QRCode) -> Int {
let moduleCount = qrCode.getModuleCount()
var lostPoint = 0
// LEVEL1
for row in 0..<moduleCount {
for col in 0..<moduleCount {
var sameCount = 0
let dark = qrCode.isDark(row, col)
for r in -1...1 {
if row + r < 0 || moduleCount <= row + r {
continue
}
for c in -1...1 {
if col + c < 0 || moduleCount <= col + c {
continue
}
if r == 0 && c == 0 {
continue
}
if dark == qrCode.isDark(row + r, col + c) {
sameCount += 1
}
}
}
if sameCount > 5 {
lostPoint += (3 + sameCount - 5)
}
}
}
// LEVEL2
for row in 0..<(moduleCount - 1) {
for col in 0..<(moduleCount - 1) {
var count = 0
if qrCode.isDark(row, col) {
count += 1
}
if qrCode.isDark(row + 1, col) {
count += 1
}
if qrCode.isDark(row, col + 1) {
count += 1
}
if qrCode.isDark(row + 1, col + 1) {
count += 1
}
if count == 0 || count == 4 {
lostPoint += 3
}
}
}
// LEVEL3
for row in 0..<moduleCount {
for col in 0..<(moduleCount - 6) {
if qrCode.isDark(row, col)
&& !qrCode.isDark(row, col + 1)
&& qrCode.isDark(row, col + 2)
&& qrCode.isDark(row, col + 3)
&& qrCode.isDark(row, col + 4)
&& !qrCode.isDark(row, col + 5)
&& qrCode.isDark(row, col + 6) {
lostPoint += 40
}
}
}
for col in 0..<moduleCount {
for row in 0..<(moduleCount - 6) {
if qrCode.isDark(row, col)
&& !qrCode.isDark(row + 1, col)
&& qrCode.isDark(row + 2, col)
&& qrCode.isDark(row + 3, col)
&& qrCode.isDark(row + 4, col)
&& !qrCode.isDark(row + 5, col)
&& qrCode.isDark(row + 6, col) {
lostPoint += 40
}
}
}
// LEVEL4
var darkCount = 0
for col in 0..<moduleCount {
for row in 0..<moduleCount {
if qrCode.isDark(row, col) {
darkCount += 1
}
}
}
let ratio = abs(100 * darkCount / moduleCount / moduleCount - 50) / 5
lostPoint += ratio * 10
return lostPoint
}
func getBCHTypeInfo(_ data: Int) -> Int {
var d = data << 10
while (getBCHDigit(d) - getBCHDigit(G15)) >= 0 {
d ^= (G15 << (getBCHDigit(d) - getBCHDigit(G15)))
}
return ((data << 10) | d) ^ G15_MASK
}
func getBCHDigit(_ input: Int) -> Int {
var data = input
var digit = 0
while data != 0 {
digit += 1
data >>= 1
}
return digit
}
}
|
mit
|
bec408b80dea5da60140d3ac1a70faca
| 28.561497 | 85 | 0.402315 | 4.162651 | false | false | false | false |
kumabook/FeedlyKit
|
Source/Tag.swift
|
1
|
1918
|
//
// Tag.swift
// FeedlyKit
//
// Created by Hiroki Kumamoto on 1/18/15.
// Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//
import Foundation
import SwiftyJSON
public final class Tag: Stream,
ResponseObjectSerializable, ResponseCollectionSerializable,
ParameterEncodable {
public var id: String
public var label: String
public var description: String?
public override var streamId: String {
return id
}
public override var streamTitle: String {
return label
}
public class func collection(_ response: HTTPURLResponse, representation: Any) -> [Tag]? {
let json = JSON(representation)
return json.arrayValue.map({ Tag(json: $0) })
}
public class func read(_ userId: String) -> Tag {
return Tag(id: "user/\(userId)/tag/global.read", label: "Read")
}
public class func saved(_ userId: String) -> Tag {
return Tag(id: "user/\(userId)/tag/global.saved", label: "Saved")
}
@objc required public convenience init?(response: HTTPURLResponse, representation: Any) {
let json = JSON(representation)
self.init(json: json)
}
public init(id: String, label: String, description: String? = nil) {
self.id = id
self.label = label
self.description = description
}
public init(json: JSON) {
self.id = json["id"].stringValue
self.label = json["label"].stringValue
self.description = json["description"].string
}
public init(label: String, profile: Profile, description: String? = nil) {
self.id = "user/\(profile.id)/tag/\(label)"
self.label = label
self.description = description
}
public func toParameters() -> [String : Any] {
return ["id":id, "label":label]
}
}
|
mit
|
1b104b97790051d72b481bc313c65b9c
| 28.507692 | 94 | 0.594891 | 4.369021 | false | false | false | false |
PureSwift/Cairo
|
Sources/Cairo/Font.swift
|
1
|
10790
|
//
// Font.swift
// Cairo
//
// Created by Alsey Coleman Miller on 5/7/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
import CCairo
import CFontConfig
import CFreeType
public final class ScaledFont {
// MARK: - Properties
internal let internalPointer: OpaquePointer
// MARK: - Initialization
deinit {
cairo_scaled_font_destroy(internalPointer)
}
internal init(_ internalPointer: OpaquePointer) {
self.internalPointer = internalPointer
}
public init(face: FontFace, matrix: Matrix, currentTransformation: Matrix, options: FontOptions) {
var matrixCopy = (matrix, currentTransformation)
self.internalPointer = cairo_scaled_font_create(face.internalPointer, &matrixCopy.0, &matrixCopy.1, options.internalPointer)!
guard self.status != CAIRO_STATUS_NO_MEMORY
else { fatalError("Out of memory") }
}
// MARK: - Accessors
public var status: Status {
return cairo_scaled_font_status(internalPointer)
}
public lazy var type: cairo_font_type_t = {
return cairo_scaled_font_get_type(self.internalPointer)
}()
public lazy var face: FontFace = {
let pointer = cairo_scaled_font_get_font_face(self.internalPointer)!
cairo_font_face_reference(pointer)
return FontFace(pointer)
}()
/// same as `maximumAdvancement`
public var fontExtents: cairo_font_extents_t {
var fontExtents = cairo_font_extents_t()
cairo_scaled_font_extents(internalPointer, &fontExtents)
return fontExtents
}
// MARK: FreeType Properties
public lazy var fullName: String = {
return self.lockFontFace { String(validatingUTF8: $0.pointee.family_name)! }
}()
public lazy var postScriptName: String? = {
return self.lockFontFace {
if let cString = FT_Get_Postscript_Name($0) {
return String(cString: cString)
} else {
return nil
}
}
}()
public lazy var ascent: Int = {
return self.lockFontFace { $0.pointee.bbox.yMax }
}()
public lazy var capHeight: Int = {
return self.lockFontFace {
if let tablePointer = FT_Get_Sfnt_Table($0, FT_SFNT_OS2) {
// owned by font face
let os2Table = tablePointer.assumingMemoryBound(to: TT_OS2.self)
return Int(os2Table.pointee.sCapHeight)
} else {
return 0
}
}
}()
public lazy var descent: Int = {
return self.lockFontFace { Int($0.pointee.descender) }
}()
public lazy var fontBBox: (x: Int, y: Int, width: Int, height: Int) = {
return self.lockFontFace {
let bbox = $0.pointee.bbox
return (bbox.xMin, bbox.yMin, bbox.xMax - bbox.xMin, bbox.yMax - bbox.yMin)
}
}()
public lazy var italicAngle: Double = {
return self.lockFontFace {
if let tablePointer = FT_Get_Sfnt_Table($0, FT_SFNT_POST) {
// owned by font face
let psTable = tablePointer.assumingMemoryBound(to: TT_Postscript.self)
return Double(psTable.pointee.italicAngle)
} else {
return 0
}
}
}()
public lazy var leading: Int = {
return self.lockFontFace { Int($0.pointee.height + $0.pointee.ascender + $0.pointee.descender) }
}()
public lazy var glyphCount: Int = {
return self.lockFontFace { Int($0.pointee.num_glyphs) }
}()
public lazy var unitsPerEm: Int = {
return self.lockFontFace { Int($0.pointee.units_per_EM) }
}()
public lazy var xHeight: Int = {
return self.lockFontFace {
if let tablePointer = FT_Get_Sfnt_Table($0, FT_SFNT_OS2) {
// owned by font face
let os2Table = tablePointer.assumingMemoryBound(to: TT_OS2.self)
return Int(os2Table.pointee.sxHeight)
} else {
return 0
}
}
}()
// MARK: - Subscripting
public subscript (glyph: FontIndex) -> String {
return self.lockFontFace { (fontFace) in
let bufferSize = 256
let buffer = UnsafeMutablePointer<CChar>.allocate(capacity: bufferSize)
defer { buffer.deallocate() }
FT_Get_Glyph_Name(fontFace, FT_UInt(glyph), buffer, FT_UInt(bufferSize))
return String(validatingUTF8: buffer)!
}
}
public subscript (glyphName: String) -> FontIndex {
return self.lockFontFace { (fontFace) in
return glyphName.withCString { (cString) in
return FontIndex(FT_Get_Name_Index(fontFace, UnsafeMutablePointer(mutating: cString)))
}
}
}
public subscript (character: UInt) -> FontIndex {
return self.lockFontFace { FontIndex(FT_Get_Char_Index($0, character)) }
}
// MARK: - Methods
public func advances(for glyphs: [FontIndex]) -> [Int] {
return self.lockFontFace { (fontFace) in
return glyphs.map { (glyph) in
FT_Load_Glyph(fontFace, FT_UInt(glyph), Int32(FT_LOAD_NO_SCALE))
return fontFace.pointee.glyph.pointee.metrics.horiAdvance
}
}
}
public func boundingBoxes(for glyphs: [FontIndex]) -> [(x: Int, y: Int, width: Int, height: Int)] {
return self.lockFontFace { (fontFace) in
return glyphs.map { (glyph) in
FT_Load_Glyph(fontFace, FT_UInt(glyph), Int32(FT_LOAD_NO_SCALE))
let metrics = fontFace.pointee.glyph.pointee.metrics
return (metrics.horiBearingX, metrics.horiBearingY - metrics.height, metrics.width, metrics.height)
}
}
}
// MARK: - Private Methods
private func lockFontFace<T>(_ block: (FT_Face) -> T) -> T {
let ftFace = cairo_ft_scaled_font_lock_face(self.internalPointer)!
defer { cairo_ft_scaled_font_unlock_face(self.internalPointer) }
return block(ftFace)
}
}
// MARK: - Supporting Types
public typealias FontIndex = UInt16
/// The font's face.
///
/// - Note: Only compatible with FreeType and FontConfig.
public final class FontFace {
// MARK: - Properties
internal let internalPointer: OpaquePointer
// MARK: - Initialization
deinit {
cairo_font_face_destroy(internalPointer)
}
public init(fontConfigPattern: OpaquePointer) {
self.internalPointer = cairo_ft_font_face_create_for_pattern(fontConfigPattern)!
}
internal init(_ internalPointer: OpaquePointer) {
self.internalPointer = internalPointer
}
// MARK: - Accessors
public var status: Status {
return cairo_font_face_status(internalPointer)
}
public lazy var type: cairo_font_type_t = cairo_font_face_get_type(self.internalPointer) // Never changes
}
public final class FontOptions {
// MARK: - Properties
internal let internalPointer: OpaquePointer
// MARK: - Initialization
deinit {
cairo_font_options_destroy(internalPointer)
}
internal init(_ internalPointer: OpaquePointer) {
self.internalPointer = internalPointer
}
/// Initializes a new `FontOptions` object.
public init() {
self.internalPointer = cairo_font_options_create()!
}
// MARK: - Methods
public func merge(_ other: FontOptions) {
cairo_font_options_merge(internalPointer, other.internalPointer)
}
// MARK: - Accessors
public var status: Status {
return cairo_font_options_status(internalPointer)
}
public var copy: FontOptions {
return FontOptions(cairo_font_options_copy(internalPointer))
}
public var hintMetrics: FontHintMetrics {
get { return FontHintMetrics(rawValue: cairo_font_options_get_hint_metrics(internalPointer).rawValue)! }
set { cairo_font_options_set_hint_metrics(internalPointer, cairo_hint_metrics_t(rawValue: newValue.rawValue)) }
}
public var hintStyle: cairo_hint_style_t {
get { return cairo_font_options_get_hint_style(internalPointer) }
set { cairo_font_options_set_hint_style(internalPointer, newValue) }
}
public var antialias: cairo_antialias_t {
get { return cairo_font_options_get_antialias(internalPointer) }
set { cairo_font_options_set_antialias(internalPointer, newValue) }
}
public var subpixelOrder: cairo_subpixel_order_t {
get { return cairo_font_options_get_subpixel_order(internalPointer) }
set { cairo_font_options_set_subpixel_order(internalPointer, newValue) }
}
}
extension FontOptions: Equatable {
public static func == (lhs: FontOptions, rhs: FontOptions) -> Bool {
return cairo_font_options_equal(lhs.internalPointer, rhs.internalPointer) != 0
}
}
extension FontOptions: Hashable {
public func hash(into hasher: inout Hasher) {
let hashValue = cairo_font_options_hash(internalPointer)
hashValue.hash(into: &hasher)
}
}
// MARK: - Supporting Types
/// cairo_font_slant_t
public enum FontSlant: UInt32 {
case normal
case italic
case oblique
}
/// cairo_font_weight_t
public enum FontWeight: UInt32 {
case normal
case bold
}
/// cairo_hint_metrics_t
public enum FontHintMetrics: UInt32 {
case `default`
case off
case on
}
#if os(Linux)
public let FT_SFNT_OS2 = FT_Sfnt_Tag(rawValue: 2)
public let FT_SFNT_POST = FT_Sfnt_Tag(rawValue: 5)
#endif
|
mit
|
1d77d616a5ac1117da30b38d86e0ff4c
| 25.060386 | 133 | 0.553805 | 4.540825 | false | false | false | false |
svenbacia/TraktKit
|
TraktKit/Sources/Resource/Trakt/AuthResource.swift
|
1
|
1675
|
//
// Auth.swift
// TraktKit
//
// Created by Sven Bacia on 28/12/2016.
// Copyright © 2016 Sven Bacia. All rights reserved.
//
import Foundation
struct AuthResource {
// MARK: Properties
private let credentials: Credentials
private let configuration: Trakt.Configuration
// MARK: - Init
init(credentials: Credentials, configuration: Trakt.Configuration) {
self.credentials = credentials
self.configuration = configuration
}
// MARK: - Endpoints
func exchangeAccessToken(for code: String) -> Resource<Token> {
let params = [
"code": code,
"client_id": credentials.clientID,
"client_secret": credentials.clientSecret,
"redirect_uri": credentials.redirectURI,
"grant_type": "authorization_code"
]
return buildResource(base: configuration.base, path: "/oauth/token", params: params, method: .post, decoder: .timeIntervalSinceNow)
}
func refreshAccessToken(with refreshToken: String) -> Resource<Token> {
let params = [
"client_id": credentials.clientID,
"client_secret": credentials.clientSecret,
"redirect_uri": credentials.redirectURI,
"refresh_token": refreshToken,
"grant_type": "refresh_token"
]
return buildResource(base: configuration.base, path: "/oauth/token", params: params, method: .post, decoder: .timeIntervalSinceNow)
}
func revokeAccessToken(_ accessToken: String) -> Resource<Any> {
return buildResource(base: configuration.base, path: "/oauth/revoke", body: "token=\(accessToken)", method: .post)
}
}
|
mit
|
31505af33d4e20b6ef8b0b2ac288d4f9
| 31.192308 | 139 | 0.640382 | 4.512129 | false | true | false | false |
ziyincody/MTablesView
|
Example/MTablesView/ViewController.swift
|
1
|
2464
|
//
// ViewController.swift
// MTablesView
//
// Created by [email protected] on 02/18/2017.
// Copyright (c) 2017 [email protected]. All rights reserved.
//
import UIKit
import MTablesView
class ViewController: UIViewController,MTableViewDelegate {
var bottomAnchor:NSLayoutConstraint?
var viewHalfHeight:CGFloat = 0
var sectionTitles = ["ABC", "BCD", "CDE"]
var mainData = [["ABC","BCD","CDE"],["ABC","BCD","CDE"]]
var detailedData = [[["ABC","ABC"],["BCD","BCD"],["CDE","CDE"]],[["ABC","ABC"],["BCD","BCD"],["CDE","CDE"]]]
var barButton:UIBarButtonItem?
lazy var mainView:MTablesView = {
let mTable = MTablesView(viewTitle: "Hi", sectionTitles: self.sectionTitles, mainData: self.mainData, detailedData: self.detailedData)
mTable.delegate = self
mTable.selectingOption = true
mTable.segueDirection = .right
return mTable
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
self.title = "Demo"
barButton = UIBarButtonItem(title: "Show", style: .plain, target: self, action: #selector(showTable(sender: )))
self.navigationItem.rightBarButtonItem = barButton
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupViews()
}
private func setupViews()
{
view.addSubview(mainView)
viewHalfHeight = self.view.frame.size.height / 1.5
let anchors = mainView.anchor(nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, centerX:nil, centerY:nil, topConstant: 0, leftConstant: 0, bottomConstant: viewHalfHeight, rightConstant: 0, widthConstant: 0, heightConstant: viewHalfHeight)
bottomAnchor = anchors[0]
}
func showTable(sender:UIBarButtonItem)
{
bottomAnchor?.isActive = false
if sender.title == "Show"
{
bottomAnchor?.constant = 0
sender.title = "Hide"
}
else if sender.title == "Hide"
{
bottomAnchor?.constant = viewHalfHeight
sender.title = "Show"
}
bottomAnchor?.isActive = true
UIView.animate(withDuration: 0.5) {
self.view.layoutIfNeeded()
}
}
func moveBackView()
{
showTable(sender: barButton!)
}
}
|
mit
|
aeba3825e8c3c0ef460791fbd7195eb8
| 29.04878 | 276 | 0.607955 | 4.43964 | false | false | false | false |
dobnezmi/EmotionNote
|
EmotionNote/SIFloatingNode.swift
|
1
|
2335
|
//
// SIFloatingNode.swift
// SIFloatingCollectionExample_Swift
//
// Created by Neverland on 15.08.15.
// Copyright (c) 2015 ProudOfZiggy. All rights reserved.
//
//
// Modified by Shingo Suzuki on 16.08.11.
import SpriteKit
public enum SIFloatingNodeState {
case Normal
case Selected
case Removing
case Commit
}
public class SIFloatingNode: SKShapeNode {
private(set) var previousState: SIFloatingNodeState = .Normal
private var _state: SIFloatingNodeState = .Normal
public var state: SIFloatingNodeState {
get {
return _state
}
set {
if _state != newValue {
previousState = _state
_state = newValue
stateChaged()
}
}
}
public static let removingKey = "action.removing"
public static let selectingKey = "action.selecting"
public static let normalizeKey = "action.normalize"
public static let commitKey = "action.commit"
private func stateChaged() {
var action: SKAction?
var actionKey: String?
switch state {
case .Normal:
action = normalizeAnimation()
actionKey = SIFloatingNode.normalizeKey
case .Selected:
action = selectingAnimation()
actionKey = SIFloatingNode.selectingKey
case .Removing:
action = removingAnimation()
actionKey = SIFloatingNode.removingKey
case .Commit:
action = commitAnimation()
actionKey = SIFloatingNode.commitKey
}
if let a = action, let ak = actionKey {
run(a, withKey: ak)
}
}
override public func removeFromParent() {
if let action = removeAnimation() {
run(action, completion: { () -> Void in
super.removeFromParent()
})
} else {
super.removeFromParent()
}
}
// MARK: -
// MARK: Animations
public func selectingAnimation() -> SKAction? {return nil}
public func normalizeAnimation() -> SKAction? {return nil}
public func removeAnimation() -> SKAction? {return nil}
public func removingAnimation() -> SKAction? {return nil}
public func commitAnimation() -> SKAction? {return nil}
}
|
apache-2.0
|
10156d70be9508720ce1bda30e841ee9
| 27.47561 | 65 | 0.59015 | 4.804527 | false | false | false | false |
russelhampton05/MenMew
|
App Prototypes/App_Prototype_A_001/App_Prototype_Alpha_001/PaymentPopupViewController.swift
|
1
|
6052
|
//
// PaymentPopupViewController.swift
// App_Prototype_Alpha_001
//
// Created by Jon Calanio on 11/13/16.
// Copyright © 2016 Jon Calanio. All rights reserved.
//
import UIKit
import LocalAuthentication
class PaymentPopupViewController: UIViewController {
//IBOutlets
@IBOutlet var payTitle: UILabel!
@IBOutlet var payConfirmLabel: UILabel!
@IBOutlet var confirmButton: UIButton!
@IBOutlet var cancelButton: UIButton!
@IBOutlet var printImage: UIImageView!
@IBOutlet var printStackView: UIStackView!
@IBOutlet var popupView: UIView!
//Variables
var didCancel: Bool = false
let authContext = LAContext()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
self.showAnimate()
loadTheme()
}
override func viewDidAppear(_ animated: Bool) {
if currentUser!.touchEnabled {
payConfirmLabel.text = "Please authenticate with TouchID."
printStackView.isHidden = false
confirmButton.isHidden = true
let delay = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: delay) {
self.ConfirmWithTouchID(laContext: self.authContext)
}
}
else {
confirmButton.isHidden = false
payConfirmLabel.text = "Payment will be finalized."
printStackView.isHidden = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func confirmButtonPressed(_ sender: Any) {
removeAnimate()
}
@IBAction func cancelButtonPressed(_ sender: Any) {
didCancel = true
removeAnimate()
}
//Popup view animation
func showAnimate() {
self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.view.alpha = 0.0
UIView.animate(withDuration: 0.25, animations: {
self.view.alpha = 1.0
self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
})
}
//Popup remove animation
func removeAnimate() {
UIView.animate(withDuration: 0.25, animations: {
self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.view.alpha = 0.0
}, completion:{(finished : Bool) in
if (finished)
{
if !self.didCancel {
if let payVC = self.parent as? PaymentDetailsViewController {
payVC.performSegue(withIdentifier: "PaymentSummarySegue", sender: payVC)
}
}
self.view.removeFromSuperview()
}
})
}
//Get Touch ID
func ConfirmWithTouchID(laContext: LAContext)->(Bool, NSError?){
var error: NSError?
var didSucceed = false
guard laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {
return (didSucceed, error)
}
laContext.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Authenticate with your fingerprint now.", reply: { (success, error) -> Void in
if( success ) {
didSucceed = success
//Show success prompt
DispatchQueue.main.async {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.printStackView.isHidden = true
self.payConfirmLabel.text = "Authentication success. Please proceed."
self.confirmButton.isHidden = false
})
}
}
else{
// Check if there is an error
if error != nil {
didSucceed = false
//Show failure prompt
DispatchQueue.main.async {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.printStackView.isHidden = true
self.payConfirmLabel.text = "Authentication failure. Reason: \(error!.localizedDescription)"
})
}
}
}
})
return (didSucceed, error)
}
func loadTheme() {
if currentTheme!.name! == "Light" {
//Background and Tint
popupView.backgroundColor = currentTheme!.highlight!
self.view.tintColor = currentTheme!.primary!
//Labels
payConfirmLabel.textColor = currentTheme!.primary!
payTitle.textColor = currentTheme!.primary!
//Buttons
confirmButton.backgroundColor = currentTheme!.primary!
confirmButton.setTitleColor(currentTheme!.highlight!, for: .normal)
cancelButton.backgroundColor = currentTheme!.primary!
cancelButton.setTitleColor(currentTheme!.highlight!, for: .normal)
}
else {
//Background and Tint
popupView.backgroundColor = currentTheme!.primary!
self.view.tintColor = currentTheme!.highlight!
//Labels
payConfirmLabel.textColor = currentTheme!.highlight!
payTitle.textColor = currentTheme!.highlight!
//Buttons
confirmButton.backgroundColor = currentTheme!.highlight!
confirmButton.setTitleColor(currentTheme!.primary!, for: .normal)
cancelButton.backgroundColor = currentTheme!.highlight!
cancelButton.setTitleColor(currentTheme!.primary!, for: .normal)
}
}
}
|
mit
|
f1062f11c545aa21d3d91a91ff1938d7
| 32.994382 | 179 | 0.555115 | 5.634078 | false | false | false | false |
remlostime/one
|
one/one/ViewControllers/ProfileViewController.swift
|
1
|
10770
|
//
// ProfileViewController.swift
// one
//
// Created by Kai Chen on 2/13/17.
// Copyright © 2017 Kai Chen. All rights reserved.
//
import UIKit
import Parse
private let numberOfPicsPerPage = 12
class ProfileViewController: UICollectionViewController {
var uuids = [String]()
var pictures = [PFFile]()
var imageCache = NSCache<NSString, UIImage>()
var numberOfPosts = numberOfPicsPerPage
var ptr: UIRefreshControl!
var userid = PFUser.current()?.username
// MARK: Lifecyle
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
if userid != PFUser.current()?.username {
self.navigationItem.rightBarButtonItem = nil
}
NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: .newPostIsSent, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(updateUserInfo), name: .updateUserInfo, object: nil)
self.navigationItem.title = userid
ptr = UIRefreshControl()
ptr.addTarget(self, action: #selector(pullToRefresh), for: .valueChanged)
collectionView?.addSubview(ptr)
loadPosts(false)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.titleTextAttributes =
[NSFontAttributeName: UIFont.boldSystemFont(ofSize: 16)]
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y >= scrollView.contentSize.height - self.view.frame.size.height {
loadPosts(true)
}
}
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind,
withReuseIdentifier: Identifier.homeHeaderView.rawValue,
for: indexPath) as? HomeHeaderCollectionView
headerView?.username = userid!
headerView?.delegate = self
// UI setup
headerView?.config()
if userid == PFUser.current()?.username {
headerView?.userNameLabel.text = (PFUser.current()?.object(forKey: User.fullname.rawValue)) as? String
headerView?.bioLabel.text = (PFUser.current()?.object(forKey: User.bio.rawValue)) as? String
let profileImageQuery = PFUser.current()?.object(forKey: User.profileImage.rawValue) as! PFFile
profileImageQuery.getDataInBackground { (data: Data?, error: Error?) in
let image = UIImage(data: data!)
headerView?.profileImageView.image = image
}
} else {
let query = PFUser.query()
query?.whereKey(User.id.rawValue, equalTo: userid!)
query?.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in
if error == nil {
let object = objects?.first
headerView?.userNameLabel.text = object?.object(forKey: User.fullname.rawValue) as? String
headerView?.bioLabel.text = object?.object(forKey: User.bio.rawValue) as? String
let profileImageFile = object?.object(forKey: User.profileImage.rawValue) as? PFFile
profileImageFile?.getDataInBackground(block: { (data: Data?, error: Error?) in
headerView?.profileImageView.image = UIImage(data: data!)
})
} else {
print("error:\(error?.localizedDescription)")
}
})
}
// Posts, followers and followings calculate
let postsQuery = PFQuery(className: Post.modelName.rawValue)
postsQuery.whereKey(User.id.rawValue, equalTo: (userid)!)
postsQuery.countObjectsInBackground { (count: Int32, error: Error?) in
if error == nil {
headerView?.postsNumLabel.text = "\(count)"
}
}
let followersQuery = PFQuery(className: Follow.modelName.rawValue)
followersQuery.whereKey(Follow.following.rawValue, equalTo: (userid)!)
followersQuery.countObjectsInBackground { (count: Int32, error: Error?) in
if error == nil {
headerView?.followersNumLabel.text = "\(count)"
}
}
let followingQuery = PFQuery(className: Follow.modelName.rawValue)
followingQuery.whereKey(Follow.follower.rawValue, equalTo: (userid)!)
followingQuery.countObjectsInBackground { (count: Int32, error: Error?) in
if error == nil {
headerView?.followingNumLabel.text = "\(count)"
}
}
let postGesture = UITapGestureRecognizer(target: self, action: #selector(postLabelTapped))
headerView?.postsNumLabel.addGestureRecognizer(postGesture)
let followingGesture = UITapGestureRecognizer(target: self, action: #selector(followingLabelTapped))
headerView?.followingNumLabel.addGestureRecognizer(followingGesture)
let followerGesture = UITapGestureRecognizer(target: self, action: #selector(followerLabelTapped))
headerView?.followersNumLabel.addGestureRecognizer(followerGesture)
return headerView!
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return pictures.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Identifier.pictureCell.rawValue, for: indexPath) as! PictureCollectionViewCell
cell.tag = indexPath.row
let key = "\(indexPath.row)"
if let image = imageCache.object(forKey: key as NSString) {
cell.imageView.image = image
} else {
pictures[indexPath.row].getDataInBackground { [weak cell, weak self](data: Data?, error: Error?) in
guard let strongCell = cell, let strongSelf = self else {
return
}
if error == nil {
DispatchQueue.main.async {
if strongCell.tag == indexPath.row {
let image = UIImage(data: data!)
strongSelf.imageCache.setObject(image!, forKey: key as NSString)
strongCell.imageView.image = image
}
}
} else {
print("error:\(error?.localizedDescription)")
}
}
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let uuid = uuids[indexPath.row]
let postViewController = self.storyboard?.instantiateViewController(withIdentifier: Identifier.postViewController.rawValue) as? PostViewController
postViewController?.postUUID = uuid
navigationController?.pushViewController(postViewController!, animated: true)
}
// MARK: Actions
@IBAction func logoutButtonTapped(_ sender: UIBarButtonItem) {
PFUser.logOutInBackground { (error: Error?) in
if error == nil {
UserDefaults.standard.removeObject(forKey: User.id.rawValue)
UserDefaults.standard.synchronize()
let signInVC = self.storyboard?.instantiateViewController(withIdentifier: Identifier.signInViewController.rawValue) as? SignInViewController
let appDelegate: AppDelegate = (UIApplication.shared.delegate as? AppDelegate)!
appDelegate.window?.rootViewController = signInVC
}
}
}
func postLabelTapped() {
if !pictures.isEmpty {
let indexPath = NSIndexPath(row: 0, section: 0)
collectionView?.scrollToItem(at: indexPath as IndexPath, at: .top, animated: true)
}
}
func followingLabelTapped() {
let followingVC = self.storyboard?.instantiateViewController(withIdentifier: Identifier.followVC.rawValue) as! FollowViewController
followingVC.status = .Following
self.navigationController?.pushViewController(followingVC, animated: true)
}
func followerLabelTapped() {
let followerVC = self.storyboard?.instantiateViewController(withIdentifier: Identifier.followVC.rawValue) as! FollowViewController
followerVC.status = .Followers
self.navigationController?.pushViewController(followerVC, animated: true)
}
// MARK: Helpers
func loadPosts(_ loadingMore: Bool) {
let query = PFQuery(className: Post.modelName.rawValue)
query.whereKey(User.id.rawValue, equalTo: (userid)!)
if (!loadingMore) {
numberOfPosts = numberOfPicsPerPage
}
query.limit = numberOfPosts
query.findObjectsInBackground { [weak self](objects: [PFObject]?, error: Error?) in
guard let strongSelf = self else {
return
}
if error == nil {
strongSelf.uuids.removeAll()
strongSelf.pictures.removeAll()
for object in objects! {
strongSelf.uuids.append(object.value(forKey: Post.uuid.rawValue) as! String)
strongSelf.pictures.append(object.value(forKey: Post.picture.rawValue) as! PFFile)
}
strongSelf.collectionView?.reloadData()
strongSelf.numberOfPosts += numberOfPicsPerPage
} else {
print(error!.localizedDescription)
}
}
}
func reloadData() {
loadPosts(false)
}
func updateUserInfo() {
reloadData()
}
func pullToRefresh() {
ptr.endRefreshing()
loadPosts(false)
}
}
extension ProfileViewController: HomeHeaderCollectionViewDelegate {
func navigateToEditPage() {
let editVC = self.storyboard?.instantiateViewController(withIdentifier: Identifier.editUserInfoViewController.rawValue) as? EditUserInfoViewController
let navigationVC = UINavigationController(rootViewController: editVC!)
present(navigationVC, animated: true, completion: nil)
}
}
|
gpl-3.0
|
0c2d93f53d1b6ae281d5ee12916deb15
| 37.460714 | 171 | 0.630514 | 5.463724 | false | false | false | false |
AnirudhDas/ADSlidePanels
|
ADSlidePanelsDemo/ADSlidePanelsDemo/ViewController.swift
|
1
|
3355
|
//
// ViewController.swift
// ADSlidePanelsDemo
//
// Created by Aniruddha Das on 1/23/17.
// Copyright © 2017 Aniruddha Das. All rights reserved.
//
import UIKit
import ADSlidePanels
class ViewController: UIViewController, ADSlidePanelViewDelegate {
var slideView: ADSlidePanelView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.addSidePanel()
self.leftBarButton()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func leftBarButton() {
var leftBarButtons = [UIBarButtonItem]()
let barButtonItem = UIBarButtonItem.init(image: UIImage(named: "menu_normal"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.menuButtonTapped))
leftBarButtons.append(barButtonItem)
if leftBarButtons.count > 0 {
self.navigationItem.leftBarButtonItems = leftBarButtons
}
let backButton = UIBarButtonItem(title: "Back", style: .plain, target: self, action: nil)
self.navigationItem.backBarButtonItem = backButton
}
func menuButtonTapped() {
self.showSidePanel()
}
func addSidePanel() {
if self.slideView != nil {
self.slideView?.removeFromSuperview()
self.slideView = nil
}
let contents = self.sidePanelContents()
self.slideView = ADSlidePanelView.initMenuView(contents, slideDirection: .left, delegate: self)
self.slideView?.isHidden = true
self.slideView?.backGroundColor = UIColor.white
self.slideView?.separatorColor = UIColor.init(colorLiteralRed: 86.0/255.0, green: 119.0/255.0, blue: 133.0/255.0, alpha: 1.0)
self.slideView?.separatorType = UITableViewCellSeparatorStyle.singleLine
self.slideView?.transparentViewMargin = 120
self.view.addSubview(self.slideView!)
self.slideView?.setupInitialConstraintWRTView(self.view, containerView: nil)
}
func sidePanelContents() -> [Item] {
var sideContents = [Item]()
let item1 = Item.init(title: "Feedback", iconName: "feedback", isSelected: false)
sideContents.append(item1)
let item2 = Item.init(title: "My Job", iconName: "myjobs", isSelected: false)
sideContents.append(item2)
return sideContents
}
func showSidePanel() {
self.slideView?.lblUserName.text = "Aniruddha Das"
self.slideView?.userIView.image = UIImage(named: "DP")
self.slideView?.menuTView.reloadData()
self.slideView?.showSidePanelWithoutSlideEffectOnSuperView()
}
func removeSidePanel() {
self.slideView?.removeSidePanelWithoutSlideEffectOnSuperView()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.removeSidePanel()
}
func didSelectItem(_ item: Item) {
if item.title.caseInsensitiveCompare("Feedback") == ComparisonResult.orderedSame {
} else if item.title.caseInsensitiveCompare("My Jobs") == ComparisonResult.orderedSame {
}
self.removeSidePanel()
}
}
|
mit
|
24cb7c49f669dc12d4eafbf53ffce253
| 33.57732 | 177 | 0.650566 | 4.520216 | false | false | false | false |
OpsLabJPL/MarsImagesIOS
|
Pods/SwiftMessages/SwiftMessages/TopBottomAnimation.swift
|
4
|
9136
|
//
// TopBottomAnimation.swift
// SwiftMessages
//
// Created by Timothy Moose on 6/4/17.
// Copyright © 2017 SwiftKick Mobile. All rights reserved.
//
import UIKit
public class TopBottomAnimation: NSObject, Animator {
public enum Style {
case top
case bottom
}
public weak var delegate: AnimationDelegate?
public let style: Style
open var springDamping: CGFloat = 0.8
open var closeSpeedThreshold: CGFloat = 750.0;
open var closePercentThreshold: CGFloat = 0.33;
open var closeAbsoluteThreshold: CGFloat = 75.0;
public private(set) lazy var panGestureRecognizer: UIPanGestureRecognizer = {
let pan = UIPanGestureRecognizer()
pan.addTarget(self, action: #selector(pan(_:)))
return pan
}()
weak var messageView: UIView?
weak var containerView: UIView?
var context: AnimationContext?
public init(style: Style) {
self.style = style
}
init(style: Style, delegate: AnimationDelegate) {
self.style = style
self.delegate = delegate
}
public func show(context: AnimationContext, completion: @escaping AnimationCompletion) {
NotificationCenter.default.addObserver(self, selector: #selector(adjustMargins), name: UIDevice.orientationDidChangeNotification, object: nil)
install(context: context)
showAnimation(completion: completion)
}
public func hide(context: AnimationContext, completion: @escaping AnimationCompletion) {
NotificationCenter.default.removeObserver(self)
let view = context.messageView
self.context = context
UIView.animate(withDuration: hideDuration!, delay: 0, options: [.beginFromCurrentState, .curveEaseIn], animations: {
switch self.style {
case .top:
view.transform = CGAffineTransform(translationX: 0, y: -view.frame.height)
case .bottom:
view.transform = CGAffineTransform(translationX: 0, y: view.frame.maxY + view.frame.height)
}
}, completion: { completed in
#if SWIFTMESSAGES_APP_EXTENSIONS
completion(completed)
#else
// Fix #131 by always completing if application isn't active.
completion(completed || UIApplication.shared.applicationState != .active)
#endif
})
}
public var showDuration: TimeInterval? { return 0.4 }
public var hideDuration: TimeInterval? { return 0.2 }
func install(context: AnimationContext) {
let view = context.messageView
let container = context.containerView
messageView = view
containerView = container
self.context = context
if let adjustable = context.messageView as? MarginAdjustable {
bounceOffset = adjustable.bounceAnimationOffset
}
view.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(view)
view.leadingAnchor.constraint(equalTo: container.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: container.trailingAnchor).isActive = true
switch style {
case .top:
view.topAnchor.constraint(equalTo: container.topAnchor, constant: -bounceOffset).with(priority: UILayoutPriority(200)).isActive = true
case .bottom:
view.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: bounceOffset).with(priority: UILayoutPriority(200)).isActive = true
}
// Important to layout now in order to get the right safe area insets
container.layoutIfNeeded()
adjustMargins()
container.layoutIfNeeded()
let animationDistance = view.frame.height
switch style {
case .top:
view.transform = CGAffineTransform(translationX: 0, y: -animationDistance)
case .bottom:
view.transform = CGAffineTransform(translationX: 0, y: animationDistance)
}
if context.interactiveHide {
if let view = view as? BackgroundViewable {
view.backgroundView.addGestureRecognizer(panGestureRecognizer)
} else {
view.addGestureRecognizer(panGestureRecognizer)
}
}
if let view = view as? BackgroundViewable,
let cornerRoundingView = view.backgroundView as? CornerRoundingView,
cornerRoundingView.roundsLeadingCorners {
switch style {
case .top:
cornerRoundingView.roundedCorners = [.bottomLeft, .bottomRight]
case .bottom:
cornerRoundingView.roundedCorners = [.topLeft, .topRight]
}
}
}
@objc public func adjustMargins() {
guard let adjustable = messageView as? MarginAdjustable & UIView,
let context = context else { return }
adjustable.preservesSuperviewLayoutMargins = false
if #available(iOS 11, *) {
adjustable.insetsLayoutMarginsFromSafeArea = false
}
var layoutMargins = adjustable.defaultMarginAdjustment(context: context)
switch style {
case .top:
layoutMargins.top += bounceOffset
case .bottom:
layoutMargins.bottom += bounceOffset
}
adjustable.layoutMargins = layoutMargins
}
func showAnimation(completion: @escaping AnimationCompletion) {
guard let view = messageView else {
completion(false)
return
}
let animationDistance = abs(view.transform.ty)
// Cap the initial velocity at zero because the bounceOffset may not be great
// enough to allow for greater bounce induced by a quick panning motion.
let initialSpringVelocity = animationDistance == 0.0 ? 0.0 : min(0.0, closeSpeed / animationDistance)
UIView.animate(withDuration: showDuration!, delay: 0.0, usingSpringWithDamping: springDamping, initialSpringVelocity: initialSpringVelocity, options: [.beginFromCurrentState, .curveLinear, .allowUserInteraction], animations: {
view.transform = .identity
}, completion: { completed in
// Fix #131 by always completing if application isn't active.
#if SWIFTMESSAGES_APP_EXTENSIONS
completion(completed)
#else
completion(completed || UIApplication.shared.applicationState != .active)
#endif
})
}
fileprivate var bounceOffset: CGFloat = 5
/*
MARK: - Pan to close
*/
fileprivate var closing = false
fileprivate var rubberBanding = false
fileprivate var closeSpeed: CGFloat = 0.0
fileprivate var closePercent: CGFloat = 0.0
fileprivate var panTranslationY: CGFloat = 0.0
@objc func pan(_ pan: UIPanGestureRecognizer) {
switch pan.state {
case .changed:
guard let view = messageView else { return }
let height = view.bounds.height - bounceOffset
if height <= 0 { return }
var velocity = pan.velocity(in: view)
var translation = pan.translation(in: view)
if case .top = style {
velocity.y *= -1.0
translation.y *= -1.0
}
var translationAmount = translation.y >= 0 ? translation.y : -pow(abs(translation.y), 0.7)
if !closing {
// Turn on rubber banding if background view is inset from message view.
if let background = (messageView as? BackgroundViewable)?.backgroundView, background != view {
switch style {
case .top:
rubberBanding = background.frame.minY > 0
case .bottom:
rubberBanding = background.frame.maxY < view.bounds.height
}
}
if !rubberBanding && translationAmount < 0 { return }
closing = true
delegate?.panStarted(animator: self)
}
if !rubberBanding && translationAmount < 0 { translationAmount = 0 }
switch style {
case .top:
view.transform = CGAffineTransform(translationX: 0, y: -translationAmount)
case .bottom:
view.transform = CGAffineTransform(translationX: 0, y: translationAmount)
}
closeSpeed = velocity.y
closePercent = translation.y / height
panTranslationY = translation.y
case .ended, .cancelled:
if closeSpeed > closeSpeedThreshold || closePercent > closePercentThreshold || panTranslationY > closeAbsoluteThreshold {
delegate?.hide(animator: self)
} else {
closing = false
rubberBanding = false
closeSpeed = 0.0
closePercent = 0.0
panTranslationY = 0.0
showAnimation(completion: { (completed) in
self.delegate?.panEnded(animator: self)
})
}
default:
break
}
}
}
|
apache-2.0
|
e31c606e87e92baa62a93cf94df7a580
| 38.206009 | 234 | 0.61642 | 5.262097 | false | false | false | false |
russbishop/swift
|
test/Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift
|
1
|
1992
|
@_exported import ObjectiveC // Clang module
// The iOS/arm64 target uses _Bool for Objective-C's BOOL. We include
// x86_64 here as well because the iOS simulator also uses _Bool.
#if ((os(iOS) || os(tvOS)) && (arch(arm64) || arch(x86_64))) || os(watchOS)
public struct ObjCBool : Boolean {
private var value : Bool
public init(_ value: Bool) {
self.value = value
}
/// \brief Allow use in a Boolean context.
public var boolValue: Bool {
return value
}
}
#else
public struct ObjCBool : Boolean {
private var value : UInt8
public init(_ value: Bool) {
self.value = value ? 1 : 0
}
public init(_ value: UInt8) {
self.value = value
}
/// \brief Allow use in a Boolean context.
public var boolValue: Bool {
if value == 0 { return false }
return true
}
}
#endif
extension ObjCBool : BooleanLiteralConvertible {
public init(booleanLiteral: Bool) {
self.init(booleanLiteral)
}
}
public struct Selector : StringLiteralConvertible {
private var ptr : OpaquePointer
public init(_ value: String) {
self.init(stringLiteral: value)
}
public init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
public init (stringLiteral value: String) {
self = sel_registerName(value)
}
}
extension Selector : Equatable {}
public func ==(lhs: Selector, rhs: Selector) -> Bool {
return sel_isEqual(lhs, rhs)
}
public struct NSZone {
public var pointer : OpaquePointer
}
internal func _convertBoolToObjCBool(_ x: Bool) -> ObjCBool {
return ObjCBool(x)
}
internal func _convertObjCBoolToBool(_ x: ObjCBool) -> Bool {
return Bool(x)
}
public func ~=(x: NSObject, y: NSObject) -> Bool {
return true
}
extension NSObject : Equatable, Hashable {
public var hashValue: Int {
return hash
}
}
public func == (lhs: NSObject, rhs: NSObject) -> Bool {
return lhs.isEqual(rhs)
}
|
apache-2.0
|
655d74268f0b2c384ab2c9bad84700c7
| 19.75 | 75 | 0.675703 | 3.801527 | false | false | false | false |
EstebanVallejo/sdk-ios
|
MercadoPagoSDK/MercadoPagoSDK/Cardholder.swift
|
2
|
1034
|
//
// Cardholder.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 28/12/14.
// Copyright (c) 2014 com.mercadopago. All rights reserved.
//
import Foundation
public class Cardholder : NSObject {
public var name : String?
public var identification : Identification?
public override init () {
super.init()
}
public class func fromJSON(json : NSDictionary) -> Cardholder {
var cardholder : Cardholder = Cardholder()
cardholder.name = JSON(json["name"]!).asString
cardholder.identification = Identification.fromJSON(json["identification"]! as! NSDictionary)
return cardholder
}
public func toJSONString() -> String {
let obj:[String:AnyObject] = [
"name": String.isNullOrEmpty(self.name) ? JSON.null : self.name!,
"identification" : self.identification == nil ? JSON.null : JSON.parse(self.identification!.toJSONString()).mutableCopyOfTheObject()
]
return JSON(obj).toString()
}
}
|
mit
|
8d10530e47b1e886c4a48ab59dc27738
| 30.363636 | 144 | 0.641199 | 4.418803 | false | false | false | false |
benlangmuir/swift
|
test/DebugInfo/protocolarg.swift
|
27
|
1295
|
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
func markUsed<T>(_ t: T) {}
func use<T>(_ t: inout T) {}
public protocol IGiveOutInts {
func callMe() -> Int64
}
// CHECK: define {{.*}}@"$s11protocolarg16printSomeNumbersyyAA12IGiveOutInts_pF"
// CHECK: @llvm.dbg.declare(metadata %T11protocolarg12IGiveOutIntsP** %
// CHECK-SAME: metadata ![[ARG:[0-9]+]],
// CHECK-SAME: metadata !DIExpression(DW_OP_deref))
// CHECK: @llvm.dbg.declare(metadata %T11protocolarg12IGiveOutIntsP* %
// CHECK-SAME: metadata ![[VAR:.*]], metadata !DIExpression())
public func printSomeNumbers(_ gen: IGiveOutInts) {
var gen = gen
// FIXME: Should be DW_TAG_interface_type
// CHECK: ![[PT:[0-9]+]] = !DICompositeType(tag: DW_TAG_structure_type, name: "IGiveOutInts"
// CHECK: ![[ARG]] = !DILocalVariable(name: "gen", arg: 1,
// CHECK-SAME: line: [[@LINE-5]],
// CHECK-SAME: type: ![[LET_PT:[0-9]+]]
// CHECK: ![[LET_PT]] = !DIDerivedType(tag: DW_TAG_const_type,
// CHECK-SAME: baseType: ![[PT]])
// CHECK: ![[VAR]] = !DILocalVariable(name: "gen", {{.*}} line: [[@LINE-8]],
// CHECK-SAME: type: ![[PT]]
markUsed(gen.callMe())
use(&gen)
}
|
apache-2.0
|
19fbe7a3ffe2610b2a11eef5e9c572b6
| 40.774194 | 94 | 0.569112 | 3.286802 | false | false | false | false |
malt03/DebugHead
|
DebugHead/Classes/DebugHead.swift
|
1
|
1592
|
//
// DebugHead.swift
// Pods
//
// Created by Koji Murata on 2017/04/15.
//
//
import Foundation
public final class DebugHead {
public static let shared = DebugHead()
public func prepare(
menus: [DebugMenu],
center: CGPoint = CGPoint(x: UIScreen.main.bounds.size.width - 50, y: UIScreen.main.bounds.size.height - 100),
sorting: Bool = true,
footerView: UIView? = nil,
openImmediately: Bool = false,
sideStickInfo: SideStickInfo? = .default
) {
debugHeadWindow = DebugHeadWindow(
menus: menus,
center: center,
sorting: sorting,
footerView: footerView,
openImmediately: openImmediately,
sideStickInfo: sideStickInfo
)
NotificationCenter.default.addObserver(self, selector: #selector(windowDidBecomeKey), name: UIWindow.didBecomeKeyNotification, object: nil)
}
@objc private func windowDidBecomeKey() {
guard let debugHeadWindow = debugHeadWindow else { return }
if UIApplication.shared.keyWindow == debugHeadWindow && !debugHeadWindow.isOpen {
var next = false
for window in UIApplication.shared.windows.reversed() {
if next {
window.makeKeyAndVisible()
return
}
if window == debugHeadWindow { next = true }
}
}
}
public func remove() {
debugHeadWindow?.closeDebugMenu {
self.debugHeadWindow = nil
}
}
public func open() {
debugHeadWindow?.openDebugMenu()
}
public func close() {
debugHeadWindow?.closeDebugMenu()
}
var debugHeadWindow: DebugHeadWindow?
private init() {}
}
|
mit
|
048543ad1802cbc8606b8b298c57da08
| 24.269841 | 143 | 0.659548 | 4.103093 | false | false | false | false |
gregomni/swift
|
test/Generics/loop_normalization_1.swift
|
3
|
1612
|
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s
protocol P {
associatedtype T
}
struct C {}
// CHECK-LABEL: .f1@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f1<T: P, U: P>(_: T, _: U) where T.T == C, T.T == U.T { }
// CHECK-LABEL: .f2@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f2<T: P, U: P>(_: T, _: U) where U.T == C, T.T == U.T { }
// CHECK-LABEL: .f3@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f3<T: P, U: P>(_: T, _: U) where T.T == C, U.T == C, T.T == U.T { }
// CHECK-LABEL: .f4@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f4<T: P, U: P>(_: T, _: U) where T.T == C, T.T == U.T, U.T == C { }
// CHECK-LABEL: .f5@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f5<T: P, U: P>(_: T, _: U) where T.T == U.T, T.T == C, U.T == C { }
// CHECK-LABEL: .f6@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f6<T: P, U: P>(_: T, _: U) where U.T == C, T.T == C, T.T == U.T { }
// CHECK-LABEL: .f7@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f7<T: P, U: P>(_: T, _: U) where T.T == C, U.T == C, T.T == U.T { }
// CHECK-LABEL: .f8@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f8<T: P, U: P>(_: T, _: U) where T.T == U.T, U.T == C, T.T == C { }
|
apache-2.0
|
3a083a60be97314dc70cc7f9a5828797
| 40.333333 | 135 | 0.491935 | 2.14077 | false | false | false | false |
Holmusk/HMRequestFramework-iOS
|
HMRequestFramework/database/coredata/processor/HMCDRequestProcessor.swift
|
1
|
26111
|
//
// HMCDRequestProcessor.swift
// HMRequestFramework
//
// Created by Hai Pham on 20/7/17.
// Copyright © 2017 Holmusk. All rights reserved.
//
import CoreData
import RxSwift
import SwiftFP
import SwiftUtilities
/// CoreData request processor class. We skip the handler due to CoreData
/// design limitations. This way, casting is done at the database level.
public struct HMCDRequestProcessor {
fileprivate var manager: HMCDManager?
fileprivate var rqmManager: HMFilterMiddlewareManager<Req>?
fileprivate var emManager: HMGlobalMiddlewareManager<HMErrorHolder>?
fileprivate init() {}
public func coreDataManager() -> HMCDManager {
if let manager = self.manager {
return manager
} else {
fatalError("CoreData manager cannot be nil")
}
}
}
extension HMCDRequestProcessor: HMCDRequestProcessorType {
public typealias Req = HMCDRequest
/// Override this method to provide default implementation.
///
/// - Returns: A HMFilterMiddlewareManager instance.
public func requestMiddlewareManager() -> HMFilterMiddlewareManager<Req>? {
return rqmManager
}
/// Override this method to provide default implementation.
///
/// - Returns: A HMFilterMiddlewareManager instance.
public func errorMiddlewareManager() -> HMFilterMiddlewareManager<HMErrorHolder>? {
return emManager
}
}
public extension HMCDRequestProcessor {
/// Override this method to provide default implementation.
///
/// - Parameter request: A Req instance.
/// - Returns: An Observable instance.
/// - Throws: Exception if no context is available.
public func executeTyped<Val>(_ request: Req) throws -> Observable<Try<[Val]>>
where Val: NSFetchRequestResult
{
let operation = try request.operation()
switch operation {
case .fetch:
return try executeFetch(request, Val.self)
default:
throw Exception("Please use normal execute for \(operation)")
}
}
/// Override this method to provide default implementation.
///
/// - Parameter request: A Req instance.
/// - Returns: An Observable instance.
/// - Throws: Exception if the execution fails.
public func execute(_ request: Req) throws -> Observable<Try<Void>> {
let operation = try request.operation()
switch operation {
case .deleteData:
return try executeDeleteData(request)
case .deleteBatch:
return try executeDeleteWithRequest(request)
case .persistLocally:
return try executePersistToFile(request)
case .resetStack:
return try executeResetStack(request)
case .fetch, .saveData, .upsert, .stream:
throw Exception("Please use typed execute for \(operation)")
}
}
/// Overwrite this method to provide default implementation.
///
/// - Parameter request: A Req instance.
/// - Returns: An Observable instance.
/// - Throws: Exception if the operation fails.
public func executeTyped(_ request: Req) throws -> Observable<Try<[HMCDResult]>> {
let operation = try request.operation()
switch operation {
case .saveData:
return try executeSaveData(request)
case .upsert:
return try executeUpsert(request)
default:
throw Exception("Please use normal execute for \(operation)")
}
}
}
public extension HMCDRequestProcessor {
/// Perform a CoreData get request.
///
/// - Parameters:
/// - request: A Req instance.
/// - cls: The Val class type.
/// - Returns: An Observable instance.
/// - Throws: Exception if the execution fails.
fileprivate func executeFetch<Val>(_ request: Req, _ cls: Val.Type) throws
-> Observable<Try<[Val]>> where Val: NSFetchRequestResult
{
let manager = coreDataManager()
let cdRequest = try request.fetchRequest(Val.self)
let context = manager.disposableObjectContext()
let opMode = request.operationMode()
let retries = request.retries()
let delay = request.retryDelay()
return manager.rx.fetch(context, cdRequest, opMode)
.delayRetry(retries: retries, delay: delay)
.map(Try.success)
.catchErrorJustReturn(Try.failure)
}
}
public extension HMCDRequestProcessor {
/// Perform a CoreData saveData operation.
///
/// - Parameter request: A Req instance.
/// - Returns: An Observable instance.
/// - Throws: Exception if the execution fails.
fileprivate func executeSaveData(_ request: Req) throws -> Observable<Try<[HMCDResult]>> {
let manager = coreDataManager()
let insertedData = try request.insertedData()
let context = manager.disposableObjectContext()
let opMode = request.operationMode()
let retries = request.retries()
let delay = request.retryDelay()
return manager.rx.saveConvertibles(context, insertedData, opMode)
.delayRetry(retries: retries, delay: delay)
.map(Try.success)
.catchErrorJustReturn(Try.failure)
}
}
public extension HMCDRequestProcessor {
/// Perform a CoreData data persistence operation.
///
/// - Parameter request: A Req instance.
/// - Returns: An Observable instance.
/// - Throws: Exception if the execution fails.
fileprivate func executePersistToFile(_ request: Req) throws -> Observable<Try<Void>> {
let manager = coreDataManager()
let opMode = request.operationMode()
let retries = request.retries()
let delay = request.retryDelay()
return manager.rx.persistLocally(opMode)
.delayRetry(retries: retries, delay: delay)
.map(Try.success)
.catchErrorJustReturn(Try.failure)
}
}
public extension HMCDRequestProcessor {
/// Perform a CoreData stack reset operation.
///
/// - Parameter request: A Req instance.
/// - Returns: An Observable instance.
/// - Throws: Exception if the execution fails.
fileprivate func executeResetStack(_ request: Req) throws -> Observable<Try<Void>> {
let manager = coreDataManager()
let opMode = request.operationMode()
let retries = request.retries()
let delay = request.retryDelay()
return manager.rx.resetStack(opMode)
.delayRetry(retries: retries, delay: delay)
.map(Try.success)
.catchErrorJustReturn(Try.failure)
}
}
public extension HMCDRequestProcessor {
/// Perform a CoreData upsert operation.
///
/// - Parameter request: A Req instance.
/// - Returns: An Observable instance.
/// - Throws: Exception if the execution fails.
fileprivate func executeUpsert(_ request: Req) throws -> Observable<Try<[HMCDResult]>> {
let manager = coreDataManager()
let data = try request.upsertedData()
let entityName = try request.entityName()
let opMode = request.operationMode()
// If the data requires versioning, we call updateVersionn.
var versionables: [HMCDVersionableType] = []
var nonVersionables: [HMCDUpsertableType] = []
for datum in data {
if let versionable = datum as? HMCDVersionableType {
versionables.append(versionable)
} else {
nonVersionables.append(datum)
}
}
let vRequests = try request.updateRequest(versionables)
let vContext = manager.disposableObjectContext()
let uContext = manager.disposableObjectContext()
return Observable
.concat(
manager.rx.updateVersion(vContext, entityName, vRequests, opMode),
manager.rx.upsert(uContext, entityName, nonVersionables, opMode)
)
.reduce([], accumulator: +)
.map(Try.success)
.catchErrorJustReturn(Try.failure)
}
}
public extension HMCDRequestProcessor {
/// Perform a CoreData delete operation. This operation detects identifiable
/// objects and treat those objects differently.
///
/// - Parameter request: A Req instance.
/// - Returns: An Observable instance.
/// - Throws: Exception if the execution fails.
fileprivate func executeDeleteData(_ request: Req) throws -> Observable<Try<Void>> {
let manager = coreDataManager()
let entityName = try request.entityName()
let retries = request.retries()
let delay = request.retryDelay()
let opMode = request.operationMode()
// Putting the context outside the create block allows it to be retained
// strongly, preventing inner managed objects from being ARC off.
let context = manager.disposableObjectContext()
// We need to use Observable.create to keep a reference to the context
// with which NSManagedObjects are constructed. Otherwise, those objects
// may become fault as the context is ARC off.
return Observable<[NSManagedObject]>
.create({
do {
let data = try request.deletedData()
// Since both CoreData and PureObject can be convertible,
// we can convert them all to NSManagedObject and delete them
// based on whether they are identifiable or not.
//
// We delete NSManagedObject using their ObjectID. If not, we
// construct the managed objects using a disposable context,
// and see if any of these objects is identifiable.
var cdObjects: [NSManagedObject] = []
for datum in data {
if let cdObject = datum as? NSManagedObject {
cdObjects.append(cdObject)
} else if let cdObject = try? datum.asManagedObject(context) {
cdObjects.append(cdObject)
}
}
$0.onNext(cdObjects)
$0.onCompleted()
} catch let e {
$0.onError(e)
}
return Disposables.create()
})
.flatMap({objects -> Observable<Void> in
// We deal with identifiables and normal objects differently.
// For identifiables, we need to fetch their counterparts in the
// DB first before deleting.
var ids: [HMCDIdentifiableType] = []
var nonIds: [NSManagedObject] = []
for object in objects {
if let identifiable = object as? HMCDIdentifiableType {
ids.append(identifiable)
} else {
nonIds.append(object)
}
}
let context1 = manager.disposableObjectContext()
let context2 = manager.disposableObjectContext()
return Observable.concat(
manager.rx.deleteIdentifiables(context1, entityName, ids, opMode),
manager.rx.delete(context2, nonIds, opMode)
)
})
.reduce((), accumulator: {_, _ in ()})
.delayRetry(retries: retries, delay: delay)
.map(Try.success)
.catchErrorJustReturn(Try.failure)
}
}
public extension HMCDRequestProcessor {
/// We need this check because batch delete does not work for InMemory store.
///
/// - Parameter request: A Req instance.
/// - Returns: An Observable instance.
/// - Throws: Exception if the execution fails.
fileprivate func executeDeleteWithRequest(_ request: Req) throws
-> Observable<Try<Void>>
{
return try executeFetchAndDelete(request)
}
/// Perform a batch delete operation. This only works for SQLite stores.
///
/// - Parameter request: A Req instance.
/// - Returns: An Observable instance.
/// - Throws: Exception if the execution fails.
@available(iOS 9.0, *)
fileprivate func executeBatchDelete(_ request: Req) throws
-> Observable<Try<Void>>
{
let manager = coreDataManager()
let deleteRequest = try request.untypedFetchRequest()
let context = manager.disposableObjectContext()
let opMode = request.operationMode()
let retries = request.retries()
let delay = request.retryDelay()
return manager.rx.delete(context, deleteRequest, opMode)
.map(toVoid)
.delayRetry(retries: retries, delay: delay)
.map(Try.success)
.catchErrorJustReturn(Try.failure)
}
/// Fetch some data from DB then delete them. This should only be used
/// when we want to batch-delete data but the store type is not SQLite.
///
/// - Parameter request: A Req instance.
/// - Returns: An Observable instance.
/// - Throws: Exception if the execution fails.
fileprivate func executeFetchAndDelete(_ request: Req) throws
-> Observable<Try<Void>>
{
let manager = coreDataManager()
let context = manager.disposableObjectContext()
let opMode = request.operationMode()
let fetchRequest = try request.fetchRequest(NSManagedObject.self)
// We can reuse the context with which we performed the fetch for the
// delete as well - this way, the NSManagedObject refetch will be very
// fast. At the same time, this helps keep this context around so that
// the inner managed objects are not ARC off.
return manager.rx.fetch(context, fetchRequest, opMode)
.flatMap({manager.rx.delete(context, $0, opMode)})
.map(Try.success)
.catchErrorJustReturn(Try.failure)
}
}
public extension HMCDRequestProcessor {
private func fetchAllRequest() -> Req {
return Req.builder()
.with(operation: .fetch)
.with(predicate: NSPredicate(value: true))
.shouldApplyMiddlewares()
.build()
}
public func fetchAllRequest(_ entityName: String?) -> Req {
return fetchAllRequest().cloneBuilder()
.with(entityName: entityName)
.with(description: "Fetch all data for \(entityName ?? "")")
.build()
}
public func fetchAllRequest<PO>(_ cls: PO.Type) -> Req where PO: HMCDPureObjectType {
return fetchAllRequest().cloneBuilder()
.with(poType: cls)
.with(description: "Fetch all data for \(cls)")
.build()
}
/// Override this method to provide default implementation.
///
/// - Parameters:
/// - previous: The result of the previous request.
/// - cls: The PureObject class type.
/// - qos: The QoSClass instance to perform work on.
/// - transforms: A Sequence of Request transformers.
/// - Returns: An Observable instance.
public func fetchAllDataFromDB<Prev,PO>(_ previous: Try<Prev>,
_ cls: PO.Type,
_ qos: DispatchQoS.QoSClass,
_ transforms: [HMTransform<Req>])
-> Observable<Try<[PO]>> where
PO: HMCDPureObjectType,
PO.CDClass: NSManagedObject,
PO.CDClass: HMCDPureObjectConvertibleType,
PO.CDClass.PureObject == PO
{
let request = fetchAllRequest(cls)
let generator = HMRequestGenerators.forceGn(request, Prev.self, transforms)
return processPureObject(previous, generator, cls, qos)
}
}
public extension HMCDRequestProcessor {
public func saveToMemoryRequest<CD,S>(_ data: S) -> Req where
CD: HMCDObjectType,
CD: HMCDObjectConvertibleType,
S: Sequence,
S.Element == CD
{
return Req.builder()
.with(cdType: CD.self)
.with(operation: .saveData)
.with(insertedData: data)
.with(description: "Save \(CD.self) to memory")
.shouldApplyMiddlewares()
.build()
}
/// Override this method to provide default implementation.
///
/// - Parameters:
/// - previous: The result of the previous operation.
/// - qos: A QoSClass instance.
/// - qos: The QoSClass instance to perform work on.
/// - transforms: A Sequence of Request transformers.
/// - Returns: An Observable instance.
public func saveToMemory<PO>(_ previous: Try<[PO]>,
_ qos: DispatchQoS.QoSClass,
_ transforms: [HMTransform<Req>])
-> Observable<Try<[HMCDResult]>> where
PO: HMCDPureObjectType,
PO.CDClass: HMCDObjectConvertibleType,
PO.CDClass: HMCDPureObjectConvertibleType,
PO.CDClass.PureObject == PO
{
let manager = coreDataManager()
let context = manager.disposableObjectContext()
let generator: HMRequestGenerator<[PO],Req> = HMRequestGenerators.forceGn({
manager.rx.construct(context, $0)
.subscribeOnConcurrent(qos: qos)
.map(self.saveToMemoryRequest)
.flatMap({HMTransforms.applyTransformers($0, transforms)})
})
return processResult(previous, generator, qos)
}
}
public extension HMCDRequestProcessor {
public func deleteDataRequest<PO,S>(_ data: S) -> Req where
PO: HMCDPureObjectType,
PO: HMCDObjectConvertibleType,
S: Sequence,
S.Element == PO
{
return Req.builder()
.with(operation: .deleteData)
.with(poType: PO.self)
.with(deletedData: data)
.with(description: "Delete data \(data) in memory")
.build()
}
/// Override this method to provide default implementation.
///
/// - Parameters:
/// - previous: The result of the previous operation.
/// - transforms: A Sequence of Request transformers.
/// - qos: The QoSClass instance to perform work on.
/// - Returns: An Observable instance.
public func deleteInMemory<PO>(_ previous: Try<[PO]>,
_ qos: DispatchQoS.QoSClass,
_ transforms: [HMTransform<Req>])
-> Observable<Try<Void>> where
PO: HMCDPureObjectType,
PO: HMCDObjectConvertibleType
{
let generator: HMRequestGenerator<[PO],Req> = HMRequestGenerators.forceGn({
let request = self.deleteDataRequest($0)
return HMTransforms.applyTransformers(request, transforms)
})
return processVoid(previous, generator, qos)
}
}
public extension HMCDRequestProcessor {
public func deleteAllRequest(_ entityName: String?) -> Req {
return fetchAllRequest(entityName)
.cloneBuilder()
.with(operation: .deleteBatch)
.with(description: "Delete all data for \(entityName ?? "")")
.build()
}
/// Override this method to provide default implementation.
///
/// - Parameters:
/// - previous: The result of the previous request.
/// - entityName: A String value denoting the entity name.
/// - qos: The QoSClass instance to perform work on.
/// - transforms: A Sequence of Request transformers.
/// - Returns: An Observable instance.
public func deleteAllInMemory<Prev>(_ previous: Try<Prev>,
_ entityName: String?,
_ qos: DispatchQoS.QoSClass,
_ transforms: [HMTransform<Req>])
-> Observable<Try<Void>>
{
let request = deleteAllRequest(entityName)
let generator = HMRequestGenerators.forceGn(request, Prev.self, transforms)
return processVoid(previous, generator, qos)
}
}
public extension HMCDRequestProcessor {
public func resetStackRequest() -> Req {
return Req.builder()
.with(operation: .resetStack)
.with(description: "Reset CoreData stack")
.shouldApplyMiddlewares()
.build()
}
/// Override this method to provide default implementation.
///
/// - Parameters:
/// - previous: The result of the previous operation.
/// - transforms: A Sequence of Request transformers.
/// - qos: The QoSClass instance to perform work on.
/// - Returns: An Observable instance.
public func resetStack<Prev>(_ previous: Try<Prev>,
_ qos: DispatchQoS.QoSClass,
_ transforms: [HMTransform<Req>])
-> Observable<Try<Void>>
{
let request = resetStackRequest()
let generator = HMRequestGenerators.forceGn(request, Prev.self, transforms)
return processVoid(previous, generator, qos)
}
}
public extension HMCDRequestProcessor {
public func upsertRequest<U,S>(_ data: S) -> Req where
U: HMCDObjectType,
U: HMCDUpsertableType,
S: Sequence,
S.Element == U
{
return Req.builder()
.with(cdType: U.self)
.with(operation: .upsert)
.with(upsertedData: data.map({$0 as HMCDUpsertableType}))
.with(vcStrategy: .takePreferable)
.with(description: "Upsert \(U.self) in memory")
.shouldApplyMiddlewares()
.build()
}
/// Override this method to provide default implementation.
///
/// - Parameters:
/// - previous: The result of the previous request.
/// - transforms: A Sequence of Request transformers.
/// - qos: The QoSClass instance to perform work on.
/// - Returns: An Observable instance.
public func upsertInMemory<U>(_ previous: Try<[U]>,
_ qos: DispatchQoS.QoSClass,
_ transforms: [HMTransform<Req>])
-> Observable<Try<[HMCDResult]>> where
U: HMCDObjectType, U: HMCDUpsertableType
{
let generator: HMRequestGenerator<[U],Req> = HMRequestGenerators.forceGn({
let request = self.upsertRequest($0)
return HMTransforms.applyTransformers(request, transforms)
})
return processResult(previous, generator, qos)
}
/// Override this method to provide default implementation.
///
/// - Parameters:
/// - previous: The result of the previous request.
/// - qos: A QoSClass instance.
/// - transforms: A Sequence of Request transformers.
/// - Returns: An Observable instance.
public func upsertInMemory<PO>(_ previous: Try<[PO]>,
_ qos: DispatchQoS.QoSClass,
_ transforms: [HMTransform<Req>])
-> Observable<Try<[HMCDResult]>> where
PO: HMCDPureObjectType,
PO.CDClass: HMCDUpsertableType,
PO.CDClass: HMCDPureObjectConvertibleType,
PO.CDClass.PureObject == PO
{
let cdManager = coreDataManager()
let context = cdManager.disposableObjectContext()
return Observable.just(previous)
.map({try $0.getOrThrow()})
.flatMap({cdManager.rx.construct(context, $0)
.subscribeOnConcurrent(qos: qos)
})
.map(Try.success)
.flatMap({self.upsertInMemory($0, qos, transforms)})
.catchErrorJustReturn(Try.failure)
}
}
public extension HMCDRequestProcessor {
public func persistToDBRequest() -> Req {
return Req.builder()
.with(operation: .persistLocally)
.with(description: "Persist all data to DB")
.shouldApplyMiddlewares()
.build()
}
/// Override this method to provide default implementation.
///
/// - Parameters:
/// - previous: The result of the previous request.
/// - qos: The QoSClass instance to perform work on.
/// - transforms: A Sequence of Request transformers.
/// - Returns: An Observable instance.
public func persistToDB<Prev>(_ previous: Try<Prev>,
_ qos: DispatchQoS.QoSClass,
_ transforms: [HMTransform<Req>])
-> Observable<Try<Void>>
{
let request = persistToDBRequest()
let generator = HMRequestGenerators.forceGn(request, Prev.self, transforms)
return processVoid(previous, generator, qos)
}
}
public extension HMCDRequestProcessor {
/// Get the basic stream request. For more sophisticated requests, please
/// use transformers on the accompanying method (as defined below).
///
/// - Parameter cls: The PO class type.
/// - Returns: A Req instance.
public func streamDBEventsRequest<PO>(_ cls: PO.Type) -> Req where
PO: HMCDPureObjectType,
PO.CDClass: HMCDPureObjectConvertibleType,
PO.CDClass.PureObject == PO
{
return Req.builder()
.with(poType: cls)
.with(operation: .stream)
.with(predicate: NSPredicate(value: true))
.with(description: "Stream DB events for \(cls)")
.shouldApplyMiddlewares()
.build()
}
/// Stream DB changes
///
/// - Parameters:
/// - cls: The PO class type.
/// - qos: The QoSClass instance to perform work on.
/// - transforms: A Sequence of Request transformers.
/// - Returns: An Observable instance.
public func streamDBEvents<PO>(_ cls: PO.Type,
_ qos: DispatchQoS.QoSClass,
_ transforms: [HMTransform<Req>])
-> Observable<Try<HMCDEvent<PO>>> where
PO: HMCDPureObjectType,
PO.CDClass: HMCDPureObjectConvertibleType,
PO.CDClass.PureObject == PO
{
let manager = coreDataManager()
let request = streamDBEventsRequest(cls)
return HMTransforms
.applyTransformers(request, transforms)
.subscribeOnConcurrent(qos: qos)
.flatMap({manager.rx.startDBStream($0, cls, qos)
.map(Try.success)
.catchErrorJustReturn(Try.failure)
})
.catchErrorJustReturn(Try.failure)
}
}
extension HMCDRequestProcessor: HMBuildableType {
public static func builder() -> Builder {
return Builder()
}
public final class Builder {
public typealias Req = HMCDRequestProcessor.Req
fileprivate var processor: Buildable
fileprivate init() {
processor = Buildable()
}
/// Set the manager instance.
///
/// - Parameter manager: A HMCDManager instance.
/// - Returns: The current Builder instance.
@discardableResult
public func with(manager: HMCDManager?) -> Self {
processor.manager = manager
return self
}
/// Set the request middleware manager.
///
/// - Parameter rqmManager: A HMFilterMiddlewareManager instance.
/// - Returns: The current Builder instance.
@discardableResult
public func with(rqmManager: HMFilterMiddlewareManager<Req>?) -> Self {
processor.rqmManager = rqmManager
return self
}
/// Set the error middleware manager.
///
/// - Parameter emManager: A HMGlobalMiddlewareManager instance.
/// - Returns: The current Builder instance.
@discardableResult
public func with(emManager: HMGlobalMiddlewareManager<HMErrorHolder>?) -> Self {
processor.emManager = emManager
return self
}
}
}
extension HMCDRequestProcessor.Builder: HMBuilderType {
public typealias Buildable = HMCDRequestProcessor
/// Override this method to provide default implementation.
///
/// - Parameter buildable: A Buildable instance.
/// - Returns: The current Builder instance.
@discardableResult
public func with(buildable: Buildable?) -> Self {
if let buildable = buildable {
return self
.with(manager: buildable.manager)
.with(rqmManager: buildable.rqmManager)
.with(emManager: buildable.emManager)
} else {
return self
}
}
public func build() -> Buildable {
return processor
}
}
|
apache-2.0
|
caceb98dcf1bbaea23e92737e5ca622f
| 32.00885 | 92 | 0.659249 | 4.401551 | false | false | false | false |
EasySwift/EasySwift
|
Carthage/Checkouts/swiftScan/swiftScan/MainTableViewController.swift
|
2
|
13232
|
//
// MainTableViewController.swift
// swiftScan
//
// Created by lbxia on 15/12/9.
// Copyright © 2015年 xialibing. All rights reserved.
//
import UIKit
import Foundation
import AVFoundation
class MainTableViewController: UITableViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var arrayItems:Array<Array<String>> = [
["模拟qq扫码界面","qqStyle"],
["模仿支付宝扫码区域","ZhiFuBaoStyle"],
["模仿微信扫码区域","weixinStyle"],
["无边框,内嵌4个角","InnerStyle"],
["4个角在矩形框线上,网格动画","OnStyle"],
["自定义颜色","changeColor"],
["只识别框内","recoCropRect"],
["改变尺寸","changeSize"],
["条形码效果","notSquare"],
["二维码/条形码生成","myCode"],
["相册","openLocalPhotoAlbum"]
];
override func viewDidLoad() {
super.viewDidLoad()
self.title = "swift 扫一扫"
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return arrayItems.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath as IndexPath)
// Configure the cell...
cell.textLabel?.text = arrayItems[indexPath.row].first
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//objc_msgSend对应方法好像没有
_ = NSSelectorFromString(arrayItems[indexPath.row].last!)
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
}
//MARK: ----模仿qq扫码界面---------
func qqStyle()
{
print("qqStyle")
let vc = QQScanViewController();
var style = LBXScanViewStyle()
style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green")
vc.scanStyle = style
self.navigationController?.pushViewController(vc, animated: true)
}
//MARK: ---模仿支付宝------
func ZhiFuBaoStyle()
{
//设置扫码区域参数
var style = LBXScanViewStyle()
style.centerUpOffset = 60;
style.xScanRetangleOffset = 30;
if UIScreen.main.bounds.size.height <= 480
{
//3.5inch 显示的扫码缩小
style.centerUpOffset = 40;
style.xScanRetangleOffset = 20;
}
style.red_notRecoginitonArea = 0.4
style.green_notRecoginitonArea = 0.4
style.blue_notRecoginitonArea = 0.4
style.alpa_notRecoginitonArea = 0.4
style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner;
style.photoframeLineW = 2.0;
style.photoframeAngleW = 16;
style.photoframeAngleH = 16;
style.isNeedShowRetangle = false;
style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid;
style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_full_net")
let vc = LBXScanViewController();
vc.scanStyle = style
self.navigationController?.pushViewController(vc, animated: true)
}
func createImageWithColor(color:UIColor)->UIImage
{
let rect=CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0);
UIGraphicsBeginImageContext(rect.size);
let context = UIGraphicsGetCurrentContext();
context!.setFillColor(color.cgColor);
context!.fill(rect);
let theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage!;
}
//MARK: -------条形码扫码界面 ---------
func notSquare()
{
//设置扫码区域参数
//设置扫码区域参数
var style = LBXScanViewStyle()
style.centerUpOffset = 44;
style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner;
style.photoframeLineW = 4;
style.photoframeAngleW = 28;
style.photoframeAngleH = 16;
style.isNeedShowRetangle = false;
style.anmiationStyle = LBXScanViewAnimationStyle.LineStill;
style.animationImage = createImageWithColor(color: UIColor.red)
//非正方形
//设置矩形宽高比
style.whRatio = 4.3/2.18;
//离左边和右边距离
style.xScanRetangleOffset = 30;
let vc = LBXScanViewController();
vc.scanStyle = style
self.navigationController?.pushViewController(vc, animated: true)
}
//MARK: ----无边框,内嵌4个角 -----
func InnerStyle()
{
//设置扫码区域参数
var style = LBXScanViewStyle()
style.centerUpOffset = 44;
style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner;
style.photoframeLineW = 3;
style.photoframeAngleW = 18;
style.photoframeAngleH = 18;
style.isNeedShowRetangle = false;
style.anmiationStyle = LBXScanViewAnimationStyle.LineMove;
//qq里面的线条图片
style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green")
let vc = LBXScanViewController();
vc.scanStyle = style
self.navigationController?.pushViewController(vc, animated: true)
}
//MARK: ---无边框,内嵌4个角------
func weixinStyle()
{
//设置扫码区域参数
var style = LBXScanViewStyle()
style.centerUpOffset = 44;
style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner;
style.photoframeLineW = 2;
style.photoframeAngleW = 18;
style.photoframeAngleH = 18;
style.isNeedShowRetangle = false;
style.anmiationStyle = LBXScanViewAnimationStyle.LineMove;
style.colorAngle = UIColor(red: 0.0/255, green: 200.0/255.0, blue: 20.0/255.0, alpha: 1.0)
style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_Scan_weixin_Line")
let vc = LBXScanViewController();
vc.scanStyle = style
self.navigationController?.pushViewController(vc, animated: true)
}
//MARK: ----框内区域识别
func recoCropRect()
{
//设置扫码区域参数
var style = LBXScanViewStyle()
style.centerUpOffset = 44;
style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On;
style.photoframeLineW = 6;
style.photoframeAngleW = 24;
style.photoframeAngleH = 24;
style.isNeedShowRetangle = true;
style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid;
//矩形框离左边缘及右边缘的距离
style.xScanRetangleOffset = 80;
//使用的支付宝里面网格图片
style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_part_net")
let vc = LBXScanViewController();
vc.scanStyle = style
vc.isOpenInterestRect = true
//TODO:待设置框内识别
self.navigationController?.pushViewController(vc, animated: true)
}
//MARK: -----4个角在矩形框线上,网格动画
func OnStyle()
{
//设置扫码区域参数
var style = LBXScanViewStyle()
style.centerUpOffset = 44;
style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On;
style.photoframeLineW = 6;
style.photoframeAngleW = 24;
style.photoframeAngleH = 24;
style.isNeedShowRetangle = true;
style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid;
//使用的支付宝里面网格图片
style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_part_net");
let vc = LBXScanViewController();
vc.scanStyle = style
self.navigationController?.pushViewController(vc, animated: true)
}
//MARK: -------自定义4个角及矩形框颜色
func changeColor()
{
//设置扫码区域参数
var style = LBXScanViewStyle()
style.centerUpOffset = 44;
style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On;
style.photoframeLineW = 6;
style.photoframeAngleW = 24;
style.photoframeAngleH = 24;
style.isNeedShowRetangle = true;
style.anmiationStyle = LBXScanViewAnimationStyle.LineMove;
//使用的支付宝里面网格图片
style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green");
//4个角的颜色
style.colorAngle = UIColor(red: 65.0/255.0, green: 174.0/255.0, blue: 57.0/255.0, alpha: 1.0)
//矩形框颜色
style.colorRetangleLine = UIColor(red: 247.0/255.0, green: 202.0/255.0, blue: 15.0/255.0, alpha: 1.0)
//非矩形框区域颜色
style.red_notRecoginitonArea = 247.0/255.0;
style.green_notRecoginitonArea = 202.0/255.0;
style.blue_notRecoginitonArea = 15.0/255.0;
style.alpa_notRecoginitonArea = 0.2;
let vc = LBXScanViewController();
vc.scanStyle = style
self.navigationController?.pushViewController(vc, animated: true)
}
//MARK: ------改变扫码区域位置
func changeSize()
{
//设置扫码区域参数
var style = LBXScanViewStyle()
//矩形框向上移动
style.centerUpOffset = 60;
//矩形框离左边缘及右边缘的距离
style.xScanRetangleOffset = 100;
style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On;
style.photoframeLineW = 6;
style.photoframeAngleW = 24;
style.photoframeAngleH = 24;
style.isNeedShowRetangle = true;
style.anmiationStyle = LBXScanViewAnimationStyle.LineMove;
//qq里面的线条图片
style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green")
let vc = LBXScanViewController();
vc.scanStyle = style
self.navigationController?.pushViewController(vc, animated: true)
}
//MARK: -------- 相册
func openLocalPhotoAlbum()
{
let picker = UIImagePickerController()
picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
picker.delegate = self;
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}
//MARK: -----相册选择图片识别二维码 (条形码没有找到系统方法)
private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
picker.dismiss(animated: true, completion: nil)
var image:UIImage? = info[UIImagePickerControllerEditedImage] as? UIImage
if (image == nil )
{
image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
if(image == nil)
{
return
}
if(image != nil)
{
let arrayResult = LBXScanWrapper.recognizeQRImage(image: image!)
if arrayResult.count > 0
{
let result = arrayResult[0];
showMsg(title: result.strBarCodeType, message: result.strScanned)
return
}
}
showMsg(title: "", message: "识别失败")
}
func showMsg(title:String?,message:String?)
{
let alertController = UIAlertController(title: title, message:message, preferredStyle: UIAlertControllerStyle.alert)
let alertAction = UIAlertAction(title: "知道了", style: UIAlertActionStyle.default) { (alertAction) -> Void in
}
alertController.addAction(alertAction)
present(alertController, animated: true, completion: nil)
}
func myCode()
{
let vc = MyCodeViewController()
self.navigationController?.pushViewController(vc, animated: true)
}
}
|
apache-2.0
|
52a34128a92cd8a7ebcf68f1c2258f03
| 28.687351 | 129 | 0.597717 | 5.066802 | false | false | false | false |
phatblat/realm-cocoa
|
RealmSwift/App.swift
|
1
|
20561
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 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
/**
An object representing the Realm App configuration
- see: `RLMAppConfiguration`
*/
public typealias AppConfiguration = RLMAppConfiguration
/**
An object representing a client which performs network calls on
Realm Cloud user api keys
- see: `RLMAPIKeyAuth`
*/
public typealias APIKeyAuth = RLMAPIKeyAuth
/**
An object representing a client which performs network calls on
Realm Cloud user registration & password functions
- see: `RLMEmailPasswordAuth`
*/
public typealias EmailPasswordAuth = RLMEmailPasswordAuth
/// A block type used to report an error
public typealias EmailPasswordAuthOptionalErrorBlock = RLMEmailPasswordAuthOptionalErrorBlock
extension EmailPasswordAuth {
/// Resets the password of an email identity using the
/// password reset function set up in the application.
/// - Parameters:
/// - email: The email address of the user.
/// - password: The desired new password.
/// - args: A list of arguments passed in as a BSON array.
/// - completion: A callback to be invoked once the call is complete.
public func callResetPasswordFunction(email: String,
password: String,
args: [AnyBSON],
_ completion: @escaping EmailPasswordAuthOptionalErrorBlock) {
let bson = ObjectiveCSupport.convert(object: .array(args))
self.__callResetPasswordFunction(email, password: password, args: bson as! [RLMBSON], completion: completion)
}
}
/**
An object representing a client which performs network calls on
Realm Cloud for registering devices to push notifications
- see `RLMPushClient`
*/
public typealias PushClient = RLMPushClient
/// An object which is used within UserAPIKeyProviderClient
public typealias UserAPIKey = RLMUserAPIKey
/**
`Credentials`is an enum representing supported authentication types for MongoDB Realm.
Example Usage:
```
let credentials = Credentials.JWT(token: myToken)
```
*/
@frozen public enum Credentials {
/// Credentials from a Facebook access token.
case facebook(accessToken: String)
/// Credentials from a Google serverAuthCode.
case google(serverAuthCode: String)
/// Credentials from a Google idToken.
case googleId(token: String)
/// Credentials from an Apple id token.
case apple(idToken: String)
/// Credentials from an email and password.
case emailPassword(email: String, password: String)
/// Credentials from a JSON Web Token
case jwt(token: String)
/// Credentials for a MongoDB Realm function using a mongodb document as a json payload.
/// If the json can not be successfully serialised and error will be produced and the object will be nil.
case function(payload: Document)
/// Credentials from a user api key.
case userAPIKey(String)
/// Credentials from a sever api key.
case serverAPIKey(String)
/// Represents anonymous credentials
case anonymous
}
/// The `App` has the fundamental set of methods for communicating with a Realm
/// application backend.
/// This interface provides access to login and authentication.
public typealias App = RLMApp
public extension App {
/**
Login to a user for the Realm app.
@param credentials The credentials identifying the user.
@param completion A callback invoked after completion. Will return `Result.success(User)` or `Result.failure(Error)`.
*/
func login(credentials: Credentials, _ completion: @escaping (Result<User, Error>) -> Void) {
self.__login(withCredential: ObjectiveCSupport.convert(object: credentials)) { user, error in
if let user = user {
completion(.success(user))
} else {
completion(.failure(error ?? Realm.Error.callFailed))
}
}
}
}
/// Use this delegate to be provided a callback once authentication has succeed or failed
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public typealias ASLoginDelegate = RLMASLoginDelegate
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension App {
/**
Sets the ASAuthorizationControllerDelegate to be handled by `App`
- Parameter controller: The ASAuthorizationController in which you want `App` to consume its delegate.
Usage:
```
let app = App(id: "my-app-id")
let appleIDProvider = ASAuthorizationAppleIDProvider()
let request = appleIDProvider.createRequest()
request.requestedScopes = [.fullName, .email]
let authorizationController = ASAuthorizationController(authorizationRequests: [request])
app.setASAuthorizationControllerDelegate(controller: authorizationController)
authorizationController.presentationContextProvider = self
authorizationController.performRequests()
```
*/
public func setASAuthorizationControllerDelegate(for controller: ASAuthorizationController) {
self.__setASAuthorizationControllerDelegateFor(controller)
}
}
#if canImport(Combine)
import Combine
/// :nodoc:
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, macCatalyst 13.0, macCatalystApplicationExtension 13.0, *)
@frozen public struct AppSubscription: Subscription {
private let app: App
private let token: RLMAppSubscriptionToken
internal init(app: App, token: RLMAppSubscriptionToken) {
self.app = app
self.token = token
}
/// A unique identifier for identifying publisher streams.
public var combineIdentifier: CombineIdentifier {
return CombineIdentifier(NSNumber(value: token.value))
}
/// This function is not implemented.
///
/// Realm publishers do not support backpressure and so this function does nothing.
public func request(_ demand: Subscribers.Demand) {
}
/// Stop emitting values on this subscription.
public func cancel() {
app.unsubscribe(token)
}
}
/// :nodoc:
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, macCatalyst 13.0, macCatalystApplicationExtension 13.0, *)
public struct AppPublisher: Publisher {
/// This publisher cannot fail.
public typealias Failure = Never
/// This publisher emits App.
public typealias Output = App
private let app: App
private let callbackQueue: DispatchQueue
internal init(_ app: App, callbackQueue: DispatchQueue = .main) {
self.app = app
self.callbackQueue = callbackQueue
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Never, Output == S.Input {
let token = app.subscribe { _ in
self.callbackQueue.async {
_ = subscriber.receive(self.app)
}
}
subscriber.receive(subscription: AppSubscription(app: app, token: token))
}
/// :nodoc:
public func receive<S: Scheduler>(on scheduler: S) -> Self {
guard let queue = scheduler as? DispatchQueue else {
fatalError("Cannot subscribe on scheduler \(scheduler): only serial dispatch queues are currently implemented.")
}
return Self(app, callbackQueue: queue)
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, macCatalyst 13.0, macCatalystApplicationExtension 13.0, *)
extension App: ObservableObject {
/// A publisher that emits Void each time the app changes.
///
/// Despite the name, this actually emits *after* the app has changed.
public var objectWillChange: AppPublisher {
return AppPublisher(self)
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, macCatalyst 13.0, macCatalystApplicationExtension 13.0, *)
public extension EmailPasswordAuth {
/**
Registers a new email identity with the username/password provider,
and sends a confirmation email to the provided address.
@param email The email address of the user to register.
@param password The password that the user created for the new username/password identity.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func registerUser(email: String, password: String) -> Future<Void, Error> {
return Future<Void, Error> { promise in
self.registerUser(email: email, password: password) { error in
if let error = error {
promise(.failure(error))
} else {
promise(.success(()))
}
}
}
}
/**
Confirms an email identity with the username/password provider.
@param token The confirmation token that was emailed to the user.
@param tokenId The confirmation token id that was emailed to the user.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func confirmUser(_ token: String, tokenId: String) -> Future<Void, Error> {
return Future<Void, Error> { promise in
self.confirmUser(token, tokenId: tokenId) { error in
if let error = error {
promise(.failure(error))
} else {
promise(.success(()))
}
}
}
}
/**
Re-sends a confirmation email to a user that has registered but
not yet confirmed their email address.
@param email The email address of the user to re-send a confirmation for.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func resendConfirmationEmail(email: String) -> Future<Void, Error> {
return Future<Void, Error> { promise in
self.resendConfirmationEmail(email) { error in
if let error = error {
promise(.failure(error))
} else {
promise(.success(()))
}
}
}
}
/**
Retries custom confirmation function for a given email address.
@param email The email address of the user to retry custom confirmation logic.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func retryCustomConfirmation(email: String) -> Future<Void, Error> {
return Future<Void, Error> { promise in
self.retryCustomConfirmation(email) { error in
if let error = error {
promise(.failure(error))
} else {
promise(.success(()))
}
}
}
}
/**
Sends a password reset email to the given email address.
@param email The email address of the user to send a password reset email for.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func sendResetPasswordEmail(email: String) -> Future<Void, Error> {
return Future<Void, Error> { promise in
self.sendResetPasswordEmail(email) { error in
if let error = error {
promise(.failure(error))
} else {
promise(.success(()))
}
}
}
}
/**
Resets the password of an email identity using the
password reset token emailed to a user.
@param password The new password.
@param token The password reset token that was emailed to the user.
@param tokenId The password reset token id that was emailed to the user.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func resetPassword(to: String, token: String, tokenId: String) -> Future<Void, Error> {
return Future<Void, Error> { promise in
self.resetPassword(to: to, token: token, tokenId: tokenId) { error in
if let error = error {
promise(.failure(error))
} else {
promise(.success(()))
}
}
}
}
/**
Resets the password of an email identity using the
password reset function set up in the application.
@param email The email address of the user.
@param password The desired new password.
@param args A list of arguments passed in as a BSON array.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func callResetPasswordFunction(email: String, password: String, args: [AnyBSON]) -> Future<Void, Error> {
return Future<Void, Error> { promise in
self.callResetPasswordFunction(email: email, password: password, args: args) { error in
if let error = error {
promise(.failure(error))
} else {
promise(.success(()))
}
}
}
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, macCatalyst 13.0, macCatalystApplicationExtension 13.0, *)
public extension APIKeyAuth {
/**
Creates a user API key that can be used to authenticate as the current user.
@param name The name of the API key to be created.
@returns A publisher that eventually return `UserAPIKey` or `Error`.
*/
func createAPIKey(named: String) -> Future<UserAPIKey, Error> {
return Future { self.createAPIKey(named: named, completion: $0) }
}
/**
Fetches a user API key associated with the current user.
@param objectId The ObjectId of the API key to fetch.
@returns A publisher that eventually return `UserAPIKey` or `Error`.
*/
func fetchAPIKey(_ objectId: ObjectId) -> Future<UserAPIKey, Error> {
return Future { self.fetchAPIKey(objectId, $0) }
}
/**
Fetches the user API keys associated with the current user.
@returns A publisher that eventually return `[UserAPIKey]` or `Error`.
*/
func fetchAPIKeys() -> Future<[UserAPIKey], Error> {
return Future { self.fetchAPIKeys($0) }
}
/**
Deletes a user API key associated with the current user.
@param objectId The ObjectId of the API key to delete.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func deleteAPIKey(_ objectId: ObjectId) -> Future<Void, Error> {
return Future { promise in
self.deleteAPIKey(objectId) { (error) in
if let error = error {
promise(.failure(error))
} else {
promise(.success(Void()))
}
}
}
}
/**
Enables a user API key associated with the current user.
@param objectId The ObjectId of the API key to enable.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func enableAPIKey(_ objectId: ObjectId) -> Future<Void, Error> {
return Future { promise in
self.enableAPIKey(objectId) { (error) in
if let error = error {
promise(.failure(error))
} else {
promise(.success(Void()))
}
}
}
}
/**
Disables a user API key associated with the current user.
@param objectId The ObjectId of the API key to disable.
@returns A publisher that eventually return `Result.success` or `Error`.
*/
func disableAPIKey(_ objectId: ObjectId) -> Future<Void, Error> {
return Future { promise in
self.disableAPIKey(objectId) { (error) in
if let error = error {
promise(.failure(error))
} else {
promise(.success(Void()))
}
}
}
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, macCatalyst 13.0, macCatalystApplicationExtension 13.0, *)
public extension App {
/// Login to a user for the Realm app.
/// @param credentials The credentials identifying the user.
/// @returns A publisher that eventually return `User` or `Error`.
func login(credentials: Credentials) -> Future<User, Error> {
return Future { self.login(credentials: credentials, $0) }
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, macCatalyst 13.0, macCatalystApplicationExtension 13.0, *)
public extension PushClient {
/// Request to register device token to the server
/// @param token device token
/// @param user - device's user
/// @returns A publisher that eventually return `Result.success` or `Error`.
func registerDevice(token: String, user: User) -> Future<Void, Error> {
return Future { promise in
self.registerDevice(token: token, user: user) { (error) in
if let error = error {
promise(.failure(error))
} else {
promise(.success(Void()))
}
}
}
}
/// Request to deregister a device for a user
/// @param user - devoce's user
/// @returns A publisher that eventually return `Result.success` or `Error`.
func deregisterDevice(user: User) -> Future<Void, Error> {
return Future { promise in
self.deregisterDevice(user: user) { (error) in
if let error = error {
promise(.failure(error))
} else {
promise(.success(Void()))
}
}
}
}
}
#endif // canImport(Combine)
public extension APIKeyAuth {
/**
Creates a user API key that can be used to authenticate as the current user.
@param name The name of the API key to be created.
@completion A completion that eventually return `Result.success(UserAPIKey)` or `Result.failure(Error)`.
*/
func createAPIKey(named: String, completion: @escaping (Result<UserAPIKey, Error>) -> Void) {
createAPIKey(named: named) { (userApiKey, error) in
if let userApiKey = userApiKey {
completion(.success(userApiKey))
} else {
completion(.failure(error ?? Realm.Error.callFailed))
}
}
}
/**
Fetches a user API key associated with the current user.
@param objectId The ObjectId of the API key to fetch.
@completion A completion that eventually return `Result.success(UserAPIKey)` or `Result.failure(Error)`.
*/
func fetchAPIKey(_ objectId: ObjectId, _ completion: @escaping (Result<UserAPIKey, Error>) -> Void) {
fetchAPIKey(objectId) { (userApiKey, error) in
if let userApiKey = userApiKey {
completion(.success(userApiKey))
} else {
completion(.failure(error ?? Realm.Error.callFailed))
}
}
}
/**
Fetches the user API keys associated with the current user.
@completion A completion that eventually return `Result.success([UserAPIKey])` or `Result.failure(Error)`.
*/
func fetchAPIKeys(_ completion: @escaping (Result<[UserAPIKey], Error>) -> Void) {
fetchAPIKeys { (userApiKeys, error) in
if let userApiKeys = userApiKeys {
completion(.success(userApiKeys))
} else {
completion(.failure(error ?? Realm.Error.callFailed))
}
}
}
}
|
apache-2.0
|
0ee7c15849bbadac073774ac39e8992f
| 36.865562 | 175 | 0.632314 | 4.703958 | false | false | false | false |
IBM-Swift/BluePic
|
BluePic-Server/Sources/BluePicApp/ObjectStorageConn.swift
|
1
|
3397
|
/**
* Copyright IBM Corporation 2016, 2017
*
* 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 BluemixObjectStorage
import LoggerAPI
import Dispatch
import CloudEnvironment
public struct ObjectStorageConn {
let connectQueue = DispatchQueue(label: "connectQueue")
let objStorage: ObjectStorage
let connProps: ObjectStorageCredentials
private var authenticated: Bool = false
// FIXME: Accessing Date object more than once will cause seg fault, related to https://bugs.swift.org/browse/SR-2462
private var lastAuthenticatedTs: Date?
init(credentials: ObjectStorageCredentials) {
connProps = credentials
objStorage = ObjectStorage(projectId: connProps.projectID)
}
mutating func getObjectStorage(completionHandler: @escaping (_ objStorage: ObjectStorage?) -> Void) {
Log.verbose("Starting task in serialized block (getting ObjectStorage instance)...")
connectQueue.sync {
self.connect(completionHandler: completionHandler)
}
Log.verbose("Completed task in serialized block.")
let param: ObjectStorage? = (authenticated) ? objStorage : nil
completionHandler(param)
}
private mutating func connect(completionHandler: (_ objStorage: ObjectStorage?) -> Void) {
Log.verbose("Determining if we have an ObjectStorage instance ready to use...")
if authenticated, let lastAuthenticatedTs = lastAuthenticatedTs {
// Check when was the last time we got an auth token
// If it's been less than 50 mins, then reuse auth token.
// This logic is just a stopgap solution to avoid requesting a new
// authToken for every ObjectStorage request.
// The ObjectStorage SDK will contain logic for handling expired authToken
let timeDiff = lastAuthenticatedTs.timeIntervalSinceNow
let minsDiff = Int(fabs(timeDiff / 60))
if minsDiff < 50 {
Log.verbose("Reusing existing Object Storage auth token...")
return
}
}
// Network call should be synchronous since we need to know the result before proceeding.
let semaphore = DispatchSemaphore(value: 0)
var copy = self
Log.verbose("Making network call synchronous...")
objStorage.connect(userId: connProps.userID, password: connProps.password, region: ObjectStorage.REGION_DALLAS) { error in
if let error = error {
let errorMsg = "Could not connect to Object Storage."
Log.error("\(errorMsg) Error was: '\(error)'.")
copy.authenticated = false
} else {
Log.verbose("Successfully obtained authentication token for Object Storage.")
copy.authenticated = true
copy.lastAuthenticatedTs = Date()
}
Log.verbose("Signaling semaphore...")
semaphore.signal()
}
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
self = copy
Log.verbose("Continuing execution after synchronous network call...")
}
}
|
apache-2.0
|
b89078b4fc4c8433b1951b3286a950db
| 38.5 | 126 | 0.722108 | 4.659808 | false | false | false | false |
SheepYo/HAYO
|
iOS/HAYO/LoginViewController.swift
|
1
|
2220
|
//
// LoginViewController.swift
// Sheep
//
// Created by mono on 7/28/14.
// Copyright (c) 2014 Sheep. All rights reserved.
//
import Foundation
class LoginViewController: UIViewController {
@IBOutlet weak var facebookButton: UIButton!
@IBOutlet weak var twitterButton: UIButton!
var snsUser: SNSUser!
override func viewDidLoad() {
super.viewDidLoad()
configureBackgroundTheme()
designButton(facebookButton)
designButton(twitterButton)
}
@IBAction func twitterDidTouchUpOutside(sender: UIButton) {
twitterButton.backgroundColor = UIColor.clearColor()
}
@IBAction func twitterDidTouchDown(sender: UIButton) {
twitterButton.backgroundColor = UIColor(white: 1, alpha: 0.35)
}
@IBAction func twitterDidTap(sender: UIButton) {
showProgress()
Account.loginToTwitter() { user in
self.handleResponse(user)
}
}
@IBAction func facebookDidTouchDown(sender: UIButton) {
facebookButton.backgroundColor = UIColor(white: 1, alpha: 0.35)
}
@IBAction func facebookDidTouchUpOutside(sender: UIButton) {
facebookButton.backgroundColor = UIColor.clearColor()
}
@IBAction func facebookDidTap(sender: UIButton) {
facebookButton.backgroundColor = UIColor.clearColor()
showProgress()
Account.loginToFacebook() { user in
self.handleResponse(user)
}
}
func handleResponse(user: SNSUser?) {
if Account.instance() != nil {
dismissProgress()
(UIApplication.sharedApplication().delegate as AppDelegate).navigate()
return
}
if user == nil {
showError()
return;
}
self.snsUser = user
dismissProgress()
self.performSegueWithIdentifier("Registration", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Registration" {
let vc = segue.destinationViewController.topViewController as RegistrationViewController
vc.user = snsUser
}
}
}
|
mit
|
97591492aba210c5e64d8e543498ac8e
| 28.613333 | 100 | 0.628829 | 5.199063 | false | false | false | false |
Zerounodue/splinxsChat
|
splinxsChat/broadcastTableViewController.swift
|
1
|
13453
|
//
// broadcastTableViewController.swift
// splinxsChat
//
// Created by Elia Kocher on 17.05.16.
// Copyright © 2016 BFH. All rights reserved.
//
import UIKit
import CoreData
class broadcastTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextViewDelegate, UIGestureRecognizerDelegate {
@IBOutlet weak var chatTableView: UITableView!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var isTypingLable: UILabel!
@IBOutlet weak var messageTextView: UITextView!
@IBOutlet weak var conBottomEditor: NSLayoutConstraint!
var nickname: String!
var persistentChatMessages = [NSManagedObject]()
//var chatMessages = [[String: AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(broadcastTableViewController.handleUserTypingNotification(_:)), name: "userTypingNotification", object: nil)
// Do any additional setup after loading the view.uitextviewtextdidchangenotification
//observe when keyboard is shown or hidden in order to adapt the layout
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(broadcastTableViewController.handleKeyboardDidShowNotification(_:)), name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(broadcastTableViewController.handleKeyboardDidHideNotification(_:)), name: UIKeyboardDidHideNotification, object: nil)
//hide keyboard when swiping down
let swipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(broadcastTableViewController.dismissKeyboard))
swipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Down
swipeGestureRecognizer.delegate = self
view.addGestureRecognizer(swipeGestureRecognizer)
persistentChatMessages.removeAll()
loadPersistentMessages()
socketIOcontroller.sharedInstance.getChatMessage { (messageInfo) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//add the new recived text in the chatMessages array
//self.chatMessages.append(messageInfo)
//
self.savePersistentMessage(messageInfo)
//reload the table in orde to display the new text
self.chatTableView.reloadData()
self.scrollToBottom()
})
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//sendButton.backgroundColor? = UIColor.greenColor()
//sendButton.tintColor? = UIColor.whiteColor()
configureTableView()
//configureNewsBannerLabel()
configureOtherUserActivityLabel()
messageTextView.delegate = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.scrollToBottom()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/*
// 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.
}
*/
// MARK: IBAction Methods
@IBAction func sendMessage(sender: AnyObject) {
//check if text is not empty
if messageTextView.text.characters.count > 0 {
socketIOcontroller.sharedInstance.sendMessage(messageTextView.text!, withNickname: nickname)
//clear the textfield
messageTextView.text = ""
//hide keyboard
messageTextView.resignFirstResponder()
}
}
// MARK: Custom Methods
func configureTableView() {
chatTableView.delegate = self
chatTableView.dataSource = self
chatTableView.registerNib(UINib(nibName: "ChatCell", bundle: nil), forCellReuseIdentifier: "idCellChat")
chatTableView.estimatedRowHeight = 90.0
chatTableView.rowHeight = UITableViewAutomaticDimension
chatTableView.tableFooterView = UIView(frame: CGRectZero)
}
func configureOtherUserActivityLabel() {
isTypingLable.hidden = true
isTypingLable.text = ""
}
//move the view containing the textview and send button up when keyboard is shown
func handleKeyboardDidShowNotification(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
conBottomEditor.constant = keyboardFrame.size.height
view.layoutIfNeeded()
}
}
}
//move the view containing the textview and send button down when keyboard is hidden
func handleKeyboardDidHideNotification(notification: NSNotification) {
conBottomEditor.constant = 0
view.layoutIfNeeded()
}
func scrollToBottom() {
let delay = 0.1 * Double(NSEC_PER_SEC)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay)), dispatch_get_main_queue()) { () -> Void in
if self.persistentChatMessages.count > 0 {
let lastRowIndexPath = NSIndexPath(forRow: self.persistentChatMessages.count - 1, inSection: 0)
self.chatTableView.scrollToRowAtIndexPath(lastRowIndexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
}
}
}
func dismissKeyboard() {
if messageTextView.isFirstResponder() {
messageTextView.resignFirstResponder()
socketIOcontroller.sharedInstance.sendStopTypingMessage(nickname)
}
}
// MARK: UITableView Delegate and Datasource Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return persistentChatMessages.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("idCellChat", forIndexPath: indexPath) as! ChatCell
//cell.removeConstraint(cell.leftConstraint)
//cell.removeConstraint(cell.rightConstraint)
let currentChatMessage = persistentChatMessages[indexPath.row]
let senderNickname = currentChatMessage.valueForKey("nickname") as? String
let message = currentChatMessage.valueForKey("message") as? String
let messageDate = currentChatMessage.valueForKey("dateTime") as? String
let isLocal = currentChatMessage.valueForKey("isLocal") as! Bool
//let senderNickname = currentChatMessage["nickname"] as! String
//let message = currentChatMessage["message"] as! String
//let messageDate = currentChatMessage["date"] as! String
//local message --> align to right
//if senderNickname == nickname {
if (isLocal){
/*
let trailingContraint = NSLayoutConstraint(item: cell,
attribute: NSLayoutAttribute.Trailing,
relatedBy: NSLayoutRelation.Equal,
toItem: cell.bubble,
attribute: NSLayoutAttribute.Trailing,
multiplier: 1.0,
constant: 10)
cell.addConstraint(trailingContraint)
*/
//cell.rightConstraint.constant = 10
cell.leftConstraint.priority = 250
cell.rightConstraint.priority = 750
cell.bubble.backgroundColor = UIColor.init(red: 40.0/255, green: 178.0/255, blue: 148.0/255, alpha: 1)
}
else{
/*
let leadingContraint = NSLayoutConstraint(item: cell.bubble,
attribute: NSLayoutAttribute.Leading,
relatedBy: NSLayoutRelation.Equal,
toItem: cell,
attribute: NSLayoutAttribute.Leading,
multiplier: 1.0,
constant: 10)
cell.addConstraint(leadingContraint)
*/
//cell.removeConstraint(cell.rightConstraint)
//cell.leftConstraint.constant = 10
//cell.rightConstraint.constant = 50
cell.leftConstraint.priority = 750
cell.rightConstraint.priority = 250
cell.bubble.backgroundColor = UIColor.init(red: 49.0/255, green: 189.0/255, blue: 199.0/255, alpha: 1.0)
//
}
//cell.widthConstraint.constant = 200
cell.nicknameLable.text = senderNickname! + ":"
cell.messageLable.text = message
cell.timeLable.text = messageDate
//cell.lblChatMessage.text = message
//cell.lblMessageDetails.text = "by \(senderNickname.uppercaseString) @ \(messageDate)"
//cell.lblChatMessage.textColor = UIColor.darkGrayColor()
cell.setNeedsLayout()
return cell
}
// MARK: UITextViewDelegate Methods
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
socketIOcontroller.sharedInstance.sendStartTypingMessage(nickname)
return true
}
// MARK: UIGestureRecognizerDelegate Methods
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
//show and hide "isTyping" message
func handleUserTypingNotification(notification: NSNotification) {
if let typingUsersDictionary = notification.object as? [String: AnyObject] {
var names = ""
var totalTypingUsers = 0
for (typingUser, _) in typingUsersDictionary {
if typingUser != nickname {
names = (names == "") ? typingUser : "\(names), \(typingUser)"
totalTypingUsers += 1
}
}
if totalTypingUsers > 0 {
let verb = (totalTypingUsers == 1) ? "is" : "are"
isTypingLable.text = "\(names) \(verb) typing..."
isTypingLable.hidden = false
}
else {
isTypingLable.hidden = true
}
}
}
func savePersistentMessage(messageInfo: [String: AnyObject]) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("Message", inManagedObjectContext:managedContext)
let message = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
let nick = messageInfo["nickname"] as! String
let mess = messageInfo["message"] as! String
let dat = messageInfo["date"] as! String
var isLocal:Bool
if ( messageInfo["nickname"] as! String == self.nickname){
isLocal=true
}
else{isLocal=false}
//let isLocal = messageInfo["nickname"] as! String ? "Online" : "Offline"
message.setValue(nick, forKey: "nickname")
message.setValue(mess, forKey: "message")
message.setValue(dat, forKey: "dateTime")
message.setValue(isLocal, forKey: "isLocal")
message.setValue("null", forKey: "room")
do {
//dont save it, it's saved in userTableViewController
//try managedContext.save()
persistentChatMessages.append(message)
} /*catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
*/
}
func loadPersistentMessages(){
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Message")
do {
let results =
try managedContext.executeFetchRequest(fetchRequest)
persistentChatMessages = results as! [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
}
|
mit
|
2064a8819e9af881adee15772aafeca7
| 38.681416 | 201 | 0.61463 | 5.818339 | false | false | false | false |
buyiyang/iosstar
|
iOSStar/General/Extension/UIViewController+Analysis.swift
|
3
|
2018
|
//
// UIViewController+Analysis.swift
// HappyTravel
//
// Created by J-bb on 16/12/20.
// Copyright © 2016年 陈奕涛. All rights reserved.
//
import Foundation
extension UIViewController {
// override open static func initialize() {
//
// guard self == UIViewController.self else {return}
//
// /**
// * 获取系统的viewWillAppear方法
// */
// let viewWillAppear = class_getInstanceMethod(self, #selector(UIViewController.viewWillAppear(_:)))
// /**
// * 获取自定义的viewWillAppear方法
// */
// let analysisViewWillAppear = class_getInstanceMethod(self, #selector(UIViewController.analysisViewWillAppear(animated:)))
//
// /**
// * 替换方法实现
// */
// method_exchangeImplementations(viewWillAppear, analysisViewWillAppear)
//
// /*****同上*****/
// let viewWillDisappear = class_getInstanceMethod(self, #selector(UIViewController.viewWillDisappear(_:)))
// let analysisViewWillDisAppear = class_getInstanceMethod(self, #selector(UIViewController.analysisViewWillDisAppear(animated:)))
//
// method_exchangeImplementations(viewWillDisappear, analysisViewWillDisAppear)
// }
//
//
//
// func analysisViewWillAppear(animated:Bool) {
//
// let classname = NSStringFromClass(self.classForCoder)
//
// MobClick.beginLogPageView(classname)
// /**
// * 因为此时方法实现已经替换,所以analysisViewWillAppear(animated) 相当于调用系统原来的 viewWillAppear
// */
// analysisViewWillAppear(animated: animated)
//
// }
// /**********同上*************/
// func analysisViewWillDisAppear(animated:Bool) {
//
// let classname = NSStringFromClass(self.classForCoder)
//
// MobClick.endLogPageView(classname)
//
//
// analysisViewWillDisAppear(animated: animated)
// }
}
|
gpl-3.0
|
f07b6599d0b34057545ed33bc148712f
| 29.790323 | 137 | 0.608172 | 4.348519 | false | false | false | false |
xuzhou524/Convenient-Swift
|
Common/XZClient.swift
|
1
|
1215
|
//
// XZClient.swift
// Convenient-Swift
//
// Created by gozap on 16/3/9.
// Copyright © 2016年 xuzhou. All rights reserved.
//
import UIKit
let KplacemarkName = "me.XZ.placemarkName"
let KweatherTefurbishTime = "me.XZ.weatherTefurbishTime"
class XZClient: NSObject {
static let sharedInstance = XZClient()
var username: String?
dynamic var weatherTefurbishTime: String?
fileprivate override init() {
super.init()
self.setupInMainThread()
}
func setupInMainThread() {
if Thread.isMainThread {
self.setup()
}
else {
DispatchQueue.main.sync(execute: { () -> Void in
self.setup()
})
}
}
func setup(){
if (XZSetting.sharedInstance[KplacemarkName] == nil){
self.username = "北京"
}else{
self.username = XZSetting.sharedInstance[KplacemarkName]
}
if (XZSetting.sharedInstance[KweatherTefurbishTime] == nil){
self.weatherTefurbishTime = "2016-01-01"
}else{
self.weatherTefurbishTime = XZSetting.sharedInstance[KweatherTefurbishTime]
}
}
}
|
mit
|
f5adf1135663b197f310707acb62aced
| 22.686275 | 87 | 0.582781 | 3.986799 | false | false | false | false |
igormatyushkin014/Verbose
|
Demo/VerboseDemo/VerboseDemo/AppDelegate.swift
|
1
|
3106
|
//
// AppDelegate.swift
// VerboseDemo
//
// Created by Igor Matyushkin on 07.11.15.
// Copyright © 2015 Igor Matyushkin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// MARK: Class variables & properties
// MARK: Class methods
// MARK: Initializers
// MARK: Deinitializer
deinit {
}
// MARK: Variables & properties
var window: UIWindow?
// MARK: Public methods
// MARK: Private methods
// MARK: Protocol methods
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Create window
let frameForWindow = UIScreen.mainScreen().bounds
window = UIWindow(frame: frameForWindow)
window!.backgroundColor = .whiteColor()
window!.makeKeyAndVisible()
// Switch to view controller
let mainViewController = MainViewController(nibName: "MainViewController", bundle: nil)
let navigationController = UINavigationController(rootViewController: mainViewController)
navigationController.navigationBarHidden = true
window!.rootViewController = navigationController
// Return result
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:.
}
}
|
mit
|
2ef0cb19bcd01c71bd8c4923663cf723
| 33.88764 | 285 | 0.692432 | 5.982659 | false | false | false | false |
rockgarden/swift_language
|
Playground/Algorithm.playground/Pages/Dynamic programming.xcplaygroundpage/Contents.swift
|
1
|
6350
|
//: Playground - noun: a place where people can play
import UIKit
/**
# 动态规划
首先要明白动态规划有以下几个专有名词:
初始状态,即此问题的最简单子问题的解。在斐波拉契数列里,最简单的问题是,一开始给定的第一个数和第二个数是几?自然我们可以得出是1
状态转移方程,即第n个问题的解和之前的 n - m 个问题解的关系。在这道题目里,我们已经有了状态转移方程F(n) = F(n - 1) + F(n - 2)
所以这题要求F(100),那我们只要知道F(99)和F(98)就行了;想知道F(99),我们只要知道F(98)和F(97)就行了;想要知道F(98),我们需要知道F(97)和F(96)。。。,以此类推,我们最后只要知道F(2)和F(1)的值,就可以推出F(100)。而F(2)和F(1)正是我们所谓的初始状态,即 F(2) = 1,F(1) =1。
*/
do {
func Fib(_ n: Int) -> Int {
// 定义初始状态
guard n > 0 else {
return 0
}
if n == 1 || n == 2 {
return 1
}
// 调用状态转移方程
return Fib(n - 1) + Fib(n - 2)
}
print(Fib(10))
}
/**
# 动态转移
虽然看上去十分高大上,但是它也存在两个致命缺点:
栈溢出:每一次递归,程序都会将当前的计算压入栈中。随着递归深度的加深,栈的高度也越来越高,直到超过计算机分配给当前进程的内存容量,程序就会崩溃。
数据溢出:因为动态规划是一种由简至繁的过程,其中积蓄的数据很有可能超过系统当前数据类型的最大值,导致崩溃。
而这两个bug,我们上面这道求解斐波拉契数列第100个数的题目就都遇到了。
首先,递归的次数很多,我们要从F(100) = F(99) + F(98) ,一直推理到F(3) = F(2) + F(1),这样很容易造成栈溢出。
其次,F(100)应该是一个很大的数。实际上F(40)就已经突破一亿,F(100)一定会造成整型数据溢出。
当然,这两个bug也有相应的解决方法。对付栈溢出,我们可以把递归写成循环的形式(所有的递归都可改写成循环);对付数据溢出,我们可以在程序每次计算中,加入数据溢出的检测,适时终止计算,抛出异常。
*/
do {
var nums = Array(repeating: 0, count: 100)
func Fib(_ n: Int) -> Int {
// 定义初始状态
guard n > 0 else {
return 0
}
if n == 1 || n == 2 {
return 1
}
// 如果已经计算过,直接调用,无需重复计算
if nums[n - 1] != 0 {
return nums[n - 1]
}
// 将计算后的值存入数组
nums[n - 1] = Fib(n - 1) + Fib(n - 2)
return nums[n - 1]
}
}
/**
缩小误差范围:将所有的单词构造成前缀树。然后对于扫描的内容,搜索出相应可能的单词。具体做法可以参考《Swift 算法实战之路:深度和广度优先搜索》一文中搜索单词的方法。
计算出最接近的单词:假如上一步,我们已经有了10个可能的单词,那么怎么确定最接近真实情况的单词呢?这里我们要定义两个单词的距离 -- 从第一个单词wordA,到第二个单词wordB,有三种操作:
删除一个字符
添加一个字符
替换一个字符
综合上述三种操作,用最少步骤将单词wordA变到单词wordB,我们就称这个值为两个单词之间的距离。比如 pr1ce -> price,只需要将 1 替换为 i 即可,所以两个单词之间的距离为1。pr1ce -> prize,要将 1 替换为 i ,再将 c 替换为 z ,所以两个单词之间的距离为2。相比于prize,price更为接近原来的单词。
现在问题转变为实现下面这个方法:
func wordDistance(_ wordA: String, wordB: String) -> Int { ... }
要解决这个复杂的问题,我们不如从一个简单的例子出发:求“abce”到“abdf”之间的距离。它们两之间的距离,无非是下面三种情况中的一种。
删除一个字符:假如已知 wordDistance("abc", "abdf") ,那么“abce”只需要删除一个字符到达“abc”,然后就可以得知“abce”到“abdf”之间的距离。
添加一个字符:假如已知 wordDistance("abce", "abd"),那么我们只要让“abd”添加一个字符到达“abdf”即可求出最终解。
替换一个字符:假如已知 wordDistance("abc", "abd"),那么就可以依此推出 wordDistance("abce", "abde") = wordDistance("abc", "abd")。故而只要将末尾的“e”替换成"f",就可以得出wordDistance("abce", "abdf")
这样我们就可以发现,求解任意两个单词之间的距离,只要知道之前单词组合的距离即可。我们用dp[i][j]表示第一个字符串wordA[0…i] 和第2个字符串wordB[0…j] 的最短编辑距离,那么这个动态规划的两个重要参数分别是:
初始状态:dp[0][j] = j,dp[i][0] = i
状态转移方程:dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1
再举例解释一下,"abc"到"xyz",dp[2][1]就是"ab"到"x"的距离,不难看出是2;dp[1][2]就是"a"到"xy"的距离,是2;dp[1][1]也就是"a"到"x"的距离,很显然就是1。所以dp[2][2]即"ab"到"xy"的距离是min(dp[2][1], dp[1][2], dp[1][1]) + 1就是2.
*/
do {
func wordDistance(_ wordA: String, _ wordB: String) -> Int {
let aChars = [Character](wordA.characters)
let bChars = [Character](wordB.characters)
let aLen = aChars.count
let bLen = bChars.count
var dp = Array(repeating: (Array(repeating: 0, count: bLen + 1)), count: aLen + 1)
for i in 0 ... aLen {
for j in 0 ... bLen {
// 初始情况
if i == 0 {
dp[i][j] = j
} else if j == 0 {
dp[i][j] = i
// 特殊情况
} else if aChars[i - 1] == bChars[j - 1] {
dp[i][j] = dp[i - 1][j - 1]
} else {
// 状态转移方程
dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1
}
}
}
return dp[aLen][bLen]
}
}
|
mit
|
bea71199ee6c3a73d87e5bcc4bfea34c
| 31.521368 | 176 | 0.56572 | 2.08667 | false | false | false | false |
BrisyIOS/TodayNewsSwift3.0
|
TodayNews-Swift3.0/TodayNews-Swift3.0/Classes/Home/Model/MediaInfoModel.swift
|
1
|
850
|
//
// MediaInfoModel.swift
// TodayNews-Swift3.0
//
// Created by zhangxu on 2016/10/27.
// Copyright © 2016年 zhangxu. All rights reserved.
//
import UIKit
class MediaInfoModel: NSObject {
var avatar_url: String?
var name: String?
var media_id: Int?
var user_verified: Int?
// MARK: - 字典转模型
class func modelWithDic(dic: [String: Any]?) -> MediaInfoModel? {
guard let dic = dic else {
return nil;
}
let mediaInfoModel = MediaInfoModel();
mediaInfoModel.avatar_url = dic["avatar_url"] as? String ?? "";
mediaInfoModel.name = dic["name"] as? String ?? "";
mediaInfoModel.media_id = dic["media_id"] as? Int ?? 0;
mediaInfoModel.user_verified = dic["user_verified"] as? Int ?? 0;
return mediaInfoModel;
}
}
|
apache-2.0
|
a82441dc7d1202a687b536acc71e1285
| 24.363636 | 73 | 0.589008 | 3.78733 | false | false | false | false |
Jauzee/showroom
|
Showroom/ViewControllers/NavigationStack/SecondViewController/SecondViewController.swift
|
2
|
1727
|
//
// SecondViewController.swift
// NavigationStackDemo
//
// Created by Alex K. on 29/02/16.
// Copyright © 2016 Alex K. All rights reserved.
//
import UIKit
class SecondViewController: UITableViewController {
var thinger: ThingerTapView? {
return (navigationController?.view.subviews.filter { $0 is ThingerTapView })?.first as? ThingerTapView
}
var hideNavBar = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
thinger?.show(delay: 2)
}
override func viewDidLoad() {
super.viewDidLoad()
_ = MenuPopUpViewController.showPopup(on: self, url: "https://github.com/Ramotion/navigation-stack") { [weak self] in
self?.hideNavBar = true
self?.navigationController?.dismiss(animated: true, completion: nil)
self?.navigationController?.dismiss(animated: true, completion: nil)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
thinger?.hide(delay: 0)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if hideNavBar == false { return }
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = true
}
@IBAction func backHandler(_ sender: AnyObject) {
let _ = navigationController?.popViewController(animated: true)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "push", sender: nil)
}
override open var shouldAutorotate: Bool {
return false
}
}
|
gpl-3.0
|
afa41035b50c19974a07ffd0fd501fdb
| 26.396825 | 121 | 0.705678 | 4.590426 | false | false | false | false |
AnirudhDas/AniruddhaDas.github.io
|
GuessImageGame/GuessImageGame/Controller/BaseViewController.swift
|
1
|
1628
|
import Foundation
import UIKit
/**
Base View Controller, sets up the NavigationBar and Background
*/
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
configureNavigationBar()
//self.view.backgroundColor = UIColor.white
self.addBackgroundImageView()
}
func setNavigationTitle(title: String) {
self.title = title
}
func configureNavigationBar() {
self.navigationController?.navigationBar.isHidden = false
self.navigationController?.navigationBar.barTintColor = UIColor.white
self.navigationItem.rightBarButtonItem?.tintColor = UIColor.white
self.navigationItem.leftBarButtonItem?.tintColor = UIColor.white
self.navigationController?.navigationBar.tintColor = UIColor.white
}
func addBackgroundImageView() {
var bgImage: UIImageView
let image: UIImage = BACKGROUND
bgImage = UIImageView(image: image)
bgImage.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(bgImage)
self.view.sendSubview(toBack: bgImage)
addConstraint(aView: bgImage)
}
func addConstraint(aView: AnyObject) {
aView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
aView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
aView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
aView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
}
}
|
apache-2.0
|
e5d977ab06c1e81ff983e5e2a57a8e03
| 36 | 98 | 0.701474 | 5.444816 | false | false | false | false |
fengxinsen/ReadX
|
ReadX/ReadBookViewController.swift
|
1
|
4727
|
//
// ReadXViewController.swift
// ReadX
//
// Created by video on 2017/2/21.
// Copyright © 2017年 Von. All rights reserved.
//
import Cocoa
import Kanna
protocol ReadBookTextViewKeyDwonDelegate {
func readBookTextViewKeyDown(aEvent: NSEvent)
}
class ReadBookTextView: NSTextView {
var readBookTextViewKeyDwonDelegate: ReadBookTextViewKeyDwonDelegate?
//响应键盘事件
override var acceptsFirstResponder: Bool {
return true
}
override func keyDown(with event: NSEvent) {
if event.keyCode == 123 || event.keyCode == 124 || event.keyCode == 49{
readBookTextViewKeyDwonDelegate?.readBookTextViewKeyDown(aEvent: event)
} else {
super.keyDown(with: event)
}
}
}
class ReadBookViewController: BaseViewController, ReadBookTextViewKeyDwonDelegate {
deinit {
print("rb xxx")
NotificationCenter.default.removeObserver(self, name: Book_Chapter_Notification, object: nil)
NotificationCenter.default.removeObserver(self, name: Book_TypeStyle_Notification, object: nil)
}
@IBOutlet var mScrollView: NSScrollView!
@IBOutlet var mTextView: ReadBookTextView!
fileprivate var book: Book?
var book_chapter_index = 0
override func viewDidLoad() {
super.viewDidLoad()
mTextView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
mTextView.readBookTextViewKeyDwonDelegate = self
mScrollView.verticalPageScroll = mTextView.bounds.size.height
NotificationCenter.default.addObserver(self, selector: #selector(notification(notification:)), name: Book_Chapter_Notification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(notification(notification:)), name: Book_TypeStyle_Notification, object: nil)
book = Single.shareSingle.currentBook
lastChapter()
}
override func viewDidAppear() {
super.viewDidAppear()
}
func notification(notification: Notification) {
let name = notification.name
switch name {
case Book_Chapter_Notification:
let bc = notification.object as! BookChapter
book_chapter_index = bc.chapterIndex
bookChapter(index: book_chapter_index)
case Book_TypeStyle_Notification:
let str = mTextView.textStorage?.string
contentTypeStyle(string: str!)
default:
print("\(notification)")
}
}
internal func readBookTextViewKeyDown(aEvent: NSEvent) {
switch aEvent.keyCode {
case 124:
print("右")
if book_chapter_index < (book?.bookChapters?.count)! {
book_chapter_index = book_chapter_index + 1
bookChapter(index: book_chapter_index)
}
case 123:
print("左")
if book_chapter_index >= 0 {
book_chapter_index = book_chapter_index - 1
bookChapter(index: book_chapter_index)
}
case 49:
print("空格")
print("\(mTextView.frame)")
// mTextView.scrollToVisible(NSRect.init(x: 0, y: <#T##Int#>, width: <#T##Int#>, height: <#T##Int#>))
mTextView.scroll(NSPoint(x: 1, y: mTextView.frame.size.height))
default:
print(aEvent.keyCode)
}
}
func lastChapter() {
book_chapter_index = Int((book?.bookReadLast)!)!
bookChapter(index: book_chapter_index)
}
func bookChapter(index: Int) {
let chapter = book!.bookChapters?[index]
var title = book!.bookName + " "
let num = (chapter?.chapterIndex.description)! + " "
print("num = \(num)")
title += num
title += (chapter?.chapterDesc)!
book?.bookReadLast = String(index)
Single.shareSingle.currentBook?.bookReadLast = String(index)
Single.shareSingle.currentBookChapter = chapter
weak var weakSelf = self
BookChapterContent(book: book!, chapter: chapter!) { (string) in
weakSelf?.view.window?.title = title
weakSelf?.contentTypeStyle(string: string)
}
}
func contentTypeStyle(string: String) {
let typeStyle = Single.shareSingle.currentTypeStyle
let attStr = string.reType(typeStyle)
mTextView.textStorage?.setAttributedString(attStr)
mTextView.scroll(NSPoint.init(x: 0, y: 0))
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
|
mit
|
e252d58a11ba9bd9bc52a14b2a11b262
| 31.895105 | 150 | 0.616709 | 4.450331 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Rocket.Chat/Controllers/Preferences/PreferencesNavigationController.swift
|
1
|
1166
|
//
// PreferencesNavigationController.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 1/11/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import UIKit
class PreferencesNavigationController: BaseNavigationController {
private var mediumScreenFrame: CGRect = .zero
private var fullScreenFrame: CGRect = .zero
private var frame: CGRect?
public var fullScreen: Bool = false {
didSet {
guard UIDevice.current.userInterfaceIdiom == .pad else { return }
frame = fullScreen ? fullScreenFrame : mediumScreenFrame
viewWillLayoutSubviews()
}
}
override func viewDidLoad() {
super.viewDidLoad()
mediumScreenFrame = CGRect(origin: .zero, size: CGSize(width: 540, height: 620))
if let frame = UIApplication.shared.keyWindow?.frame {
fullScreenFrame = frame
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
guard UIDevice.current.userInterfaceIdiom == .pad else { return }
if let frame = frame {
self.view.superview?.bounds = frame
}
}
}
|
mit
|
74247fc52598c25720b68325905c5b1e
| 24.326087 | 88 | 0.644635 | 4.978632 | false | false | false | false |
teacurran/alwaysawake-ios
|
Pods/p2.OAuth2/Sources/Base/OAuth2AuthConfig.swift
|
3
|
2728
|
//
// OAuth2AuthConfig.swift
// OAuth2
//
// Created by Pascal Pfiffner on 16/11/15.
// Copyright © 2015 Pascal Pfiffner. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#if os(OSX)
import Cocoa
#endif
/**
Simple struct to hold settings describing how authorization appears to the user.
*/
public struct OAuth2AuthConfig {
/// Sub-stuct holding configuration relevant to UI presentation.
public struct UI {
/// Title to propagate to views handled by OAuth2, such as OAuth2WebViewController.
public var title: String? = nil
// TODO: figure out a neat way to make this a UIBarButtonItem if compiled for iOS
/// By assigning your own UIBarButtonItem (!) you can override the back button that is shown in the iOS embedded web view (does NOT apply to `SFSafariViewController`).
public var backButton: AnyObject? = nil
/// Starting with iOS 9, `SFSafariViewController` will be used for embedded authorization instead of our custom class. You can turn this off here.
public var useSafariView = true
#if os(OSX)
/// Internally used to store default `NSWindowController` created to contain the web view controller.
var windowController: NSWindowController?
#elseif os(iOS)
/// Internally used to store the `SFSafariViewControllerDelegate`.
var safariViewDelegate: AnyObject?
#endif
}
/// Whether the receiver should use the request body instead of the Authorization header for the client secret; defaults to `false`.
public var secretInBody = false
/// Whether to use an embedded web view for authorization (true) or the OS browser (false, the default).
public var authorizeEmbedded = false
/// Whether to automatically dismiss the auto-presented authorization screen.
public var authorizeEmbeddedAutoDismiss = true
/// Context information for the authorization flow:
/// - iOS: the parent view controller to present from
/// - OS X: An NSWindow from which to present a modal sheet _or_
/// - OS X: A `((webViewController: NSViewController) -> Void)` block to execute with the web view controller for you to present
public var authorizeContext: AnyObject? = nil
/// UI-specific configuration.
public var ui = UI()
}
|
apache-2.0
|
42afad4b2b4e012f19d303af06fb19b3
| 37.408451 | 169 | 0.741107 | 4.25429 | false | true | false | false |
R0uter/polyv-ios-client-swift-demo
|
polyv-ios-client-swift-demo/polyvClasses/FMDBHelper.swift
|
1
|
2999
|
//
// FMDBHelper.swift
// polyv-ios-client-swift-demo
//
// Created by R0uter on 2017/3/30.
// Copyright © 2017年 R0uter. All rights reserved.
//
import Foundation
class FMDBHelper {
var DBName = ""
var queue:FMDatabaseQueue!
static let shared = FMDBHelper()
private init () {
DBName = get(path: "polyv.db")
print(DBName)
readyDownloadTable()
}
// 数据库存储路径(内部使用)
func get(path dbNme:String) ->String {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = path[0]
return documentsDirectory.appending("/"+dbNme)
}
//打开数据库
func readyDatabase() {
queue = FMDatabaseQueue(path: DBName)
}
}
//MARK: downloadTable
extension FMDBHelper {
func readyDownloadTable() {
readyDatabase()
queue.inDatabase {
let sql = "create table if not exists downloadlist (vid varchar(40),title varchar(100),duration varchar(20),filesize bigint,level int,percent int default 0,status int,primary key (vid))"
$0?.executeStatements(sql)
}
}
func addDownload(video:Video) {
queue.inDatabase{
$0?.executeUpdate("replace INTO downloadlist(vid,title,duration,filesize,level,percent,status) VALUES (?,?,?,?,?,?,0)", withArgumentsIn: [video.vid,video.title,video.duration,Int64(video.filesize),Int(video.level),Int(video.percent)])
}
}
func updateDownload(vid:String,percent:Double) {
queue.inDatabase {
$0?.executeUpdate("update downloadlist set percent=? where vid=?", withArgumentsIn: [Int(percent),vid])
}
}
func updateDownload(vid:String,status:Int) {
queue.inDatabase {
$0?.executeUpdate("update downloadlist set status=? where vid=?", withArgumentsIn: [status,vid])
}
}
func removeDownload(video:Video) {
queue.inDatabase {
$0?.executeUpdate("delete from downloadlist where vid=?", withArgumentsIn: [video.vid])
}
}
}
extension FMDBHelper {
func listDownLoadVideo()->[Video] {
var downloadVideos:[Video] = []
queue.inDatabase {
if let rs = $0?.executeQuery("select * from downloadlist", withArgumentsIn: []) {
while rs.next() {
let v = Video()
v.vid = rs.string(forColumn: "vid")
v.title = rs.string(forColumn: "title")
v.duration = rs.string(forColumn: "duration")
v.filesize = rs.longLongInt(forColumn: "filesize")
v.level = Int(rs.int(forColumn: "level"))
v.percent = Double(rs.int(forColumn: "percent"))
v.status = Int(rs.int(forColumn: "status"))
downloadVideos.append(v)
}
}
}
return downloadVideos
}
}
|
mit
|
ef422669128c3fdbf6ae75e6c95a96ac
| 31.933333 | 246 | 0.585358 | 4.228245 | false | false | false | false |
MaciejGad/GPSData
|
HttpParser.swift
|
1
|
4915
|
//
// HttpParser.swift
// Swifter
// Copyright (c) 2014 Damian Kołakowski. All rights reserved.
//
import Foundation
class HttpParser {
func err(reason: String) -> NSError {
return NSError(domain: "HttpParser", code: 0, userInfo: [NSLocalizedDescriptionKey : reason])
}
func nextHttpRequest(socket: CInt, error:NSErrorPointer = nil) -> HttpRequest? {
if let statusLine = nextLine(socket, error: error) {
let statusTokens = split(statusLine, { $0 == " " })
println(statusTokens)
if ( statusTokens.count < 3 ) {
if error != nil { error.memory = err("Invalid status line: \(statusLine)") }
return nil
}
let method = statusTokens[0]
let path = statusTokens[1]
let urlParams = extractUrlParams(path)
// TODO extract query parameters
if let headers = nextHeaders(socket, error: error) {
// TODO detect content-type and handle:
// 'application/x-www-form-urlencoded' -> Dictionary
// 'multipart' -> Dictionary
if let contentSize = headers["content-length"]?.toInt() {
let body = nextBody(socket, size: contentSize, error: error)
return HttpRequest(url: path, urlParams: urlParams, method: method, headers: headers, body: body, capturedUrlGroups: [])
}
return HttpRequest(url: path, urlParams: urlParams, method: method, headers: headers, body: nil, capturedUrlGroups: [])
}
}
return nil
}
private func extractUrlParams(url: String) -> [(String, String)] {
if let query = split(url, { $0 == "?" }).last {
return map(split(query, { $0 == "&" }), { (param:String) -> (String, String) in
let tokens = split(param, { $0 == "=" })
if tokens.count >= 2 {
let key = tokens[0].stringByRemovingPercentEncoding
let value = tokens[1].stringByRemovingPercentEncoding
if key != nil && value != nil { return (key!, value!) }
}
return ("","")
})
}
return []
}
private func nextBody(socket: CInt, size: Int , error:NSErrorPointer) -> String? {
var body = ""
var counter = 0;
while ( counter < size ) {
let c = nextUInt8(socket)
if ( c < 0 ) {
if error != nil { error.memory = err("IO error while reading body") }
return nil
}
body.append(UnicodeScalar(c))
counter++;
}
return body
}
private func nextHeaders(socket: CInt, error:NSErrorPointer) -> Dictionary<String, String>? {
var headers = Dictionary<String, String>()
while let headerLine = nextLine(socket, error: error) {
if ( headerLine.isEmpty ) {
return headers
}
let headerTokens = split(headerLine, { $0 == ":" })
if ( headerTokens.count >= 2 ) {
// RFC 2616 - "Hypertext Transfer Protocol -- HTTP/1.1", paragraph 4.2, "Message Headers":
// "Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive."
// We can keep lower case version.
let headerName = headerTokens[0].lowercaseString
let headerValue = headerTokens[1].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if ( !headerName.isEmpty && !headerValue.isEmpty ) {
headers.updateValue(headerValue, forKey: headerName)
}
}
}
return nil
}
private func nextUInt8(socket: CInt) -> Int {
var buffer = [UInt8](count: 1, repeatedValue: 0);
let next = recv(socket, &buffer, UInt(buffer.count), 0)
if next <= 0 { return next }
return Int(buffer[0])
}
private func nextLine(socket: CInt, error:NSErrorPointer) -> String? {
var characters: String = ""
var n = 0
do {
n = nextUInt8(socket)
if ( n > 13 /* CR */ ) { characters.append(Character(UnicodeScalar(n))) }
} while ( n > 0 && n != 10 /* NL */)
if ( n == -1 && characters.isEmpty ) {
if error != nil { error.memory = Socket.lastErr("recv(...) failed.") }
return nil
}
return characters
}
func supportsKeepAlive(headers: Dictionary<String, String>) -> Bool {
if let value = headers["connection"] {
return "keep-alive" == value.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).lowercaseString
}
return false
}
}
|
mit
|
df01c0fa00c8cb62a4f145d99119c26d
| 40.294118 | 140 | 0.542532 | 4.729548 | false | false | false | false |
JamieScanlon/AugmentKit
|
AugmentKit/AKCore/Primatives/AKAnimatable.swift
|
1
|
6277
|
//
// AKAnimatable.swift
// AugmentKit
//
// MIT License
//
// Copyright (c) 2018 JamieScanlon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
// MARK: - AKAnimatable
/**
Describes a animatable value. That is, a value that changes over time.
*/
public protocol AKAnimatable {
associatedtype Value
/**
Retrieve a value.
- Parameters:
- forTime: The current `TimeInterval`
- Returns: The value
*/
func value(forTime: TimeInterval) -> Value
}
// MARK: - AKPulsingAnimatable
/**
Describes an `AKAnimatable` that oscillates between a `minValue` and `maxValue` over a time `period`
*/
public protocol AKPulsingAnimatable: AKAnimatable {
/**
The minumum value.
*/
var minValue: Value { get }
/**
The maximum value.
*/
var maxValue: Value { get }
/**
The period.
*/
var period: TimeInterval { get }
/**
The offset to apply to the animation.
*/
var periodOffset: TimeInterval { get }
}
extension AKPulsingAnimatable where Value == Double {
/**
Retrieve a value.
Implementation of the `value(forTime:)` function when `AKAnimatable.Value` is a `Double`
- Parameters:
- forTime: The current `TimeInterval`
- Returns: The value
*/
public func value(forTime time: TimeInterval) -> Value {
let delta = maxValue - minValue
let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period
return minValue + delta * (0.5 + 0.5 * cos(2 * Double.pi * progress))
}
}
extension AKPulsingAnimatable where Value == Float {
/**
Retrieve a value.
Implementation of the `value(forTime:)` function when `AKAnimatable.Value` is a `Float`
- Parameters:
- forTime: The current `TimeInterval`
- Returns: The value
*/
public func value(forTime time: TimeInterval) -> Value {
let delta = Double(maxValue - minValue)
let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period
return minValue + Float(delta * (0.5 + 0.5 * cos(2 * Double.pi * progress)))
}
}
extension AKPulsingAnimatable where Value == Int {
/**
Retrieve a value.
Implementation of the `value(forTime:)` function when `AKAnimatable.Value` is an `Int`
- Parameters:
- forTime: The current `TimeInterval`
- Returns: The value
*/
public func value(forTime time: TimeInterval) -> Value {
let delta = Double(maxValue - minValue)
let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period
return minValue + Int(delta * (0.5 + 0.5 * cos(2 * Double.pi * progress)))
}
}
extension AKPulsingAnimatable where Value == UInt {
/**
Retrieve a value.
Implementation of the `value(forTime:)` function when `AKAnimatable.Value` is a `UInt`
- Parameters:
- forTime: The current `TimeInterval`
- Returns: The value
*/
public func value(forTime time: TimeInterval) -> Value {
let delta = Double(maxValue - minValue)
let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period
return minValue + UInt(delta * (0.5 + 0.5 * cos(2 * Double.pi * progress)))
}
}
extension AKPulsingAnimatable where Value == Any {
/**
Retrieve a value.
Implementation of the `value(forTime:)` function when `AKAnimatable.Value` is a `Any`.
This implementation checks if `Any` can be downcast to `double`, `Float`, `Int`, or `UInt` and performs the calculations, returning `minValue` otherwise
- Parameters:
- forTime: The current `TimeInterval`
- Returns: The value
*/
public func value(forTime time: TimeInterval) -> Value {
if let aMinValue = minValue as? Double, let aMaxValue = maxValue as? Double {
let delta = aMaxValue - aMinValue
let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period
return aMinValue + delta * (0.5 + 0.5 * cos(2 * Double.pi * progress))
} else if let aMinValue = minValue as? Float, let aMaxValue = maxValue as? Float {
let delta = Double(aMaxValue - aMinValue)
let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period
return aMinValue + Float(delta * (0.5 + 0.5 * cos(2 * Double.pi * progress)))
} else if let aMinValue = minValue as? Int, let aMaxValue = maxValue as? Int {
let delta = Double(aMaxValue - aMinValue)
let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period
return aMinValue + Int(delta * (0.5 + 0.5 * cos(2 * Double.pi * progress)))
} else if let aMinValue = minValue as? UInt, let aMaxValue = maxValue as? UInt {
let delta = Double(aMaxValue - aMinValue)
let progress = ((periodOffset + time).truncatingRemainder(dividingBy: period)) / period
return aMinValue + UInt(delta * (0.5 + 0.5 * cos(2 * Double.pi * progress)))
} else {
return minValue
}
}
}
|
mit
|
4e3ff3447fd11e4a82a5df22915684d1
| 35.707602 | 157 | 0.645531 | 4.287568 | false | false | false | false |
ben-ng/swift
|
test/attr/attr_ibaction.swift
|
10
|
7071
|
// RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
@IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{1-11=}}
var iboutlet_global: Int
@IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{1-11=}}
class IBOutletClassTy {}
@IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{1-11=}}
struct IBStructTy {}
@IBAction // expected-error {{only instance methods can be declared @IBAction}} {{1-11=}}
func IBFunction() -> () {}
class IBActionWrapperTy {
@IBAction
func click(_: AnyObject) -> () {} // no-warning
func outer(_: AnyObject) -> () {
@IBAction // expected-error {{only instance methods can be declared @IBAction}} {{5-15=}}
func inner(_: AnyObject) -> () {}
}
@IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{3-13=}}
var value : Void = ()
@IBAction
func process(x: AnyObject) -> Int {} // expected-error {{methods declared @IBAction must return 'Void' (not 'Int')}}
// @IBAction does /not/ semantically imply @objc.
@IBAction // expected-note {{attribute already specified here}}
@IBAction // expected-error {{duplicate attribute}}
func doMagic(_: AnyObject) -> () {}
@IBAction @objc
func moreMagic(_: AnyObject) -> () {} // no-warning
@objc @IBAction
func evenMoreMagic(_: AnyObject) -> () {} // no-warning
}
struct S { }
enum E { }
protocol P1 { }
protocol P2 { }
protocol CP1 : class { }
protocol CP2 : class { }
@objc protocol OP1 { }
@objc protocol OP2 { }
// Check which argument types @IBAction can take.
@objc class X {
// Class type
@IBAction func action1(_: X) {}
@IBAction func action2(_: X?) {}
@IBAction func action3(_: X!) {}
// AnyObject
@IBAction func action4(_: AnyObject) {}
@IBAction func action5(_: AnyObject?) {}
@IBAction func action6(_: AnyObject!) {}
// Any
@IBAction func action4a(_: Any) {}
@IBAction func action5a(_: Any?) {}
@IBAction func action6a(_: Any!) {}
// Protocol types
@IBAction func action7(_: P1) {} // expected-error{{argument to @IBAction method cannot have non-object type 'P1'}}
// expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{protocol 'P1' is not '@objc'}}
@IBAction func action8(_: CP1) {} // expected-error{{argument to @IBAction method cannot have non-object type 'CP1'}}
// expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{protocol 'CP1' is not '@objc'}}
@IBAction func action9(_: OP1) {}
@IBAction func action10(_: P1?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
@IBAction func action11(_: CP1?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
@IBAction func action12(_: OP1?) {}
@IBAction func action13(_: P1!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
@IBAction func action14(_: CP1!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
@IBAction func action15(_: OP1!) {}
// Class metatype
@IBAction func action15b(_: X.Type) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action16(_: X.Type?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action17(_: X.Type!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// AnyClass
@IBAction func action18(_: AnyClass) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action19(_: AnyClass?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action20(_: AnyClass!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// Protocol types
@IBAction func action21(_: P1.Type) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
@IBAction func action22(_: CP1.Type) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
@IBAction func action23(_: OP1.Type) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action24(_: P1.Type?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
@IBAction func action25(_: CP1.Type?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
@IBAction func action26(_: OP1.Type?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action27(_: P1.Type!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
//expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
@IBAction func action28(_: CP1.Type!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
//expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
@IBAction func action29(_: OP1.Type!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// Other bad cases
@IBAction func action30(_: S) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{Swift structs cannot be represented in Objective-C}}
@IBAction func action31(_: E) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{non-'@objc' enums cannot be represented in Objective-C}}
init() { }
}
|
apache-2.0
|
a659319840142a4e1f4804f62952d7d1
| 55.568 | 130 | 0.704851 | 4.06613 | false | false | false | false |
livefront/bonsai
|
Examples/Counters/Counters/Models/Clock.swift
|
1
|
692
|
import Bonsai
struct Clock: Model {
enum ActionType: Action {
case tick
case location(Location)
}
var subscription: Subscription<ActionType>? {
return .batch([
Time.every(ActionType.tick),
Location.track(ActionType.location)
])
}
var seconds: Int = 0
var latitude: Double = 0
var longitude: Double = 0
mutating func update(_ action: ActionType) -> Command<ActionType>? {
switch action {
case .tick:
seconds += 1
case .location(let location):
latitude = location.latitude
longitude = location.longitude
}
return nil
}
}
|
mit
|
3b350609923595fe287ad5dbbfb7a814
| 21.322581 | 72 | 0.563584 | 4.873239 | false | false | false | false |
ben-ng/swift
|
validation-test/compiler_crashers_fixed/01102-resolvetypedecl.swift
|
1
|
772
|
// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func c<e>() -> (e -> e) -> e {
e, e -> e) ->)func d(f: b) -> <e>(() -> e) -> b {
struct c<d : Sequence> {
var b: [c<d>] {
}
protocol a {
}
class b: a {
}
func f<T : Boolean>(b: T) {
}
func e() {
}
}
protocol c : b { func b
otocol A {
}
struct }
}
class a<b : b, d : b where b.d == d> {
}
protocol b {
typealias d
typealias e = a<c<h>, d>
}
struct c<d, e: b where d.c == e
|
apache-2.0
|
390041923dda90e188334e9dba7781fb
| 21.705882 | 79 | 0.619171 | 2.787004 | false | false | false | false |
nayzak/Swift-MVVM
|
Swift MVVM/App/BeerViewPage.swift
|
1
|
870
|
//
// BeerViewPage.swift
//
// Created by NayZaK on 06.03.15.
// Copyright (c) 2015 Amur.net. All rights reserved.
//
import UIKit
class BeerViewPage: Page {
typealias PMT = BeerViewPageModel
@IBOutlet weak var contentWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var abvLabel: UILabel!
@IBOutlet weak var breweryLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
contentWidthConstraint.constant = UIScreen.mainScreen().bounds.width
}
override func bindPageModel() {
super.bindPageModel()
let pm = pageModel as PMT
pm.viewModel >>> { [weak self] in self?.processViewModel($0); () }
}
private func processViewModel(vm: BeerViewModel) {
abvLabel.text = vm.abv
descriptionLabel.text = vm.description
breweryLabel.text = vm.breweryName
}
}
|
mit
|
a7796639772b9ad4e18c597179d91b75
| 23.885714 | 72 | 0.713793 | 3.832599 | false | false | false | false |
artsy/eigen
|
ios/Artsy/View_Controllers/Live_Auctions/ViewModels/LiveAuctionLotViewModel.swift
|
1
|
13540
|
import Foundation
import Interstellar
// Represents a single lot view
enum LotState {
case upcomingLot(isHighestBidder: Bool)
case liveLot
case closedLot(wasPassed: Bool)
}
func == (lhs: LotState, rhs: LotState) -> Bool {
switch (lhs, rhs) {
case (.upcomingLot, .upcomingLot): return true
case (.liveLot, .liveLot): return true
case let (.closedLot(lhsClosed), .closedLot(rhsClosed)) where lhsClosed == rhsClosed: return true
default: return false
}
}
typealias CurrentBid = (bid: String, reserve: String?)
protocol LiveAuctionLotViewModelType: AnyObject {
var numberOfDerivedEvents: Int { get }
func derivedEventAtPresentationIndex(_ index: Int) -> LiveAuctionEventViewModel
var lotArtist: String { get }
var lotArtistBlurb: String? { get }
var lotArtworkDescription: String? { get }
var lotArtworkMedium: String? { get }
var lotArtworkDimensions: String? { get }
var estimateString: String? { get }
var highEstimateOrEstimateCents: UInt64? { get }
var lotName: String { get }
var lotID: String { get }
var lotLabel: String? { get }
var lotEditionInfo: String? { get }
var lotArtworkCreationDate: String? { get }
var urlForThumbnail: URL? { get }
var urlForProfile: URL? { get }
var askingPrice: UInt64 { get }
var winningBidPrice: UInt64? { get }
var currencySymbol: String { get }
var numberOfBids: Int { get }
var imageAspectRatio: CGFloat { get }
var liveAuctionLotID: String { get }
var reserveStatusString: String { get }
var dateLotOpened: Date? { get }
var userIsBeingSoldTo: Bool { get }
var isBeingSold: Bool { get }
var userIsWinning: Bool { get }
var userIsFloorWinningBidder: Bool { get }
var usersTopBidCents: UInt64? { get }
var reserveStatusSignal: Observable<ARReserveStatus> { get }
var lotStateSignal: Observable<LotState> { get }
var askingPriceSignal: Observable<UInt64> { get }
var numberOfBidsSignal: Observable<Int> { get }
var currentBidSignal: Observable<CurrentBid> { get }
var newEventsSignal: Observable<[LiveAuctionEventViewModel]> { get }
}
extension LiveAuctionLotViewModelType {
var formattedLotIndexDisplayString: String {
guard let lotLabel = lotLabel else { return "" }
return "Lot \(lotLabel)"
}
var currentBidSignal: Observable<CurrentBid> {
let currencySymbol = self.currencySymbol
return askingPriceSignal.merge(reserveStatusSignal).map { (askingPrice, reserveStatus) -> CurrentBid in
let reserveString: String?
switch reserveStatus {
case .unknown: fallthrough
case .noReserve: reserveString = nil
case .reserveMet: reserveString = "(Reserve met)"
case .reserveNotMet: reserveString = "(Reserve not met)"
default: reserveString = nil
}
return (
bid: "Current Ask: \(askingPrice.convertToDollarString(currencySymbol))",
reserve: reserveString
)
}
}
}
class LiveAuctionLotViewModel: NSObject, LiveAuctionLotViewModelType {
fileprivate let model: LiveAuctionLot
fileprivate let bidderCredentials: BiddingCredentials
// This is the full event stream
fileprivate var fullEventList = [LiveAuctionEventViewModel]()
// This is the event stream once undos, and composite bids have
// done their work on the events
fileprivate var derivedEvents = [LiveAuctionEventViewModel]()
fileprivate typealias BiddingStatus = (status: ARLiveBiddingStatus, wasPassed: Bool, isHighestBidder: Bool)
fileprivate let biddingStatusSignal = Observable<BiddingStatus>()
fileprivate var soldStatus: String?
let reserveStatusSignal = Observable<ARReserveStatus>()
let lotStateSignal: Observable<LotState>
let askingPriceSignal = Observable<UInt64>()
let numberOfBidsSignal = Observable<Int>()
let newEventsSignal = Observable<[LiveAuctionEventViewModel]>()
var sellingToBidderID: String? = nil
var winningBidEventID: String? = nil
/// So you can differentiate whether your bid has been confirmed
/// by the floor or not
var floorWinningBidderID: String? = nil
/// The value of the highest bid the user has placed on this lot
var userTopBidCents: UInt64? = nil
/// Used to format dimensions as inches or centimeters. Do no modify this except under unit tests
var usersLocale = NSLocale.autoupdatingCurrent
init(lot: LiveAuctionLot, bidderCredentials: BiddingCredentials) {
self.model = lot
self.bidderCredentials = bidderCredentials
reserveStatusSignal.update(lot.reserveStatus)
askingPriceSignal.update(lot.askingPriceCents)
lotStateSignal = biddingStatusSignal.map { (biddingStatus, passed, isHighestBidder) -> LotState in
switch biddingStatus {
case .upcoming: fallthrough // Case that sale is not yet open
case .open: // Case that lot is open to leave max bids
return .upcomingLot(isHighestBidder: isHighestBidder)
case .onBlock: // Currently on the block
return .liveLot
case .complete: // Closed
return .closedLot(wasPassed: passed)
}
}
}
var lotArtworkDescription: String? {
return model.artwork.blurb
}
var lotArtworkMedium: String? {
return model.artwork.medium
}
var lotArtworkDimensions: String? {
if self.usersLocale.usesMetricSystem {
return model.artwork.dimensionsCM
} else {
return model.artwork.dimensionsInches
}
}
var lotLabel: String? {
return model.lotLabel as String?
}
var lotEditionInfo: String? {
return model.artwork.editionOf
}
var winningBidPrice: UInt64? {
return self.winningBidEvent?.bidAmountCents
}
var usersTopBidCents: UInt64? {
return userTopBidCents
}
var askingPrice: UInt64 {
return model.askingPriceCents
}
var numberOfBids: Int {
return model.onlineBidCount
}
var urlForThumbnail: URL? {
return model.urlForThumbnail()
}
var urlForProfile: URL? {
return model.urlForProfile()
}
var imageAspectRatio: CGFloat {
return model.imageAspectRatio()
}
var lotName: String {
return model.artworkTitle
}
var lotID: String {
return model.liveAuctionLotID
}
var lotArtworkCreationDate: String? {
return model.artworkDate
}
var lotArtist: String {
return model.artistName
}
var lotArtistBlurb: String? {
return model.artistBlurb
}
var liveAuctionLotID: String {
return model.liveAuctionLotID
}
var winningBidEvent: LiveAuctionEventViewModel? {
return fullEventList.filter({ $0.eventID == winningBidEventID }).last
}
var isBeingSold: Bool {
return sellingToBidderID != nil
}
var userIsBeingSoldTo: Bool {
guard let
bidderID = bidderCredentials.bidderID,
let sellingToBidderID = sellingToBidderID else { return false }
return bidderID == sellingToBidderID
}
var userIsWinning: Bool {
guard let
bidderID = bidderCredentials.bidderID,
let winningBidEvent = winningBidEvent else { return false }
return winningBidEvent.hasBidderID(bidderID)
}
var userIsFloorWinningBidder: Bool {
return bidderCredentials.bidderID == floorWinningBidderID
}
func findBidWithValue(_ amountCents: UInt64) -> LiveAuctionEventViewModel? {
return fullEventList.filter({ $0.isBid && $0.hasAmountCents(amountCents) }).first
}
// Want to avoid array searching + string->date processing every in timer loops
// so pre-cache createdAt when found.
fileprivate var _dateLotOpened: Date?
var dateLotOpened: Date? {
guard _dateLotOpened == nil else { return _dateLotOpened }
guard let opening = fullEventList.filter({ $0.isLotOpening }).first else { return nil }
_dateLotOpened = opening.dateEventCreated as Date
return _dateLotOpened
}
var currencySymbol: String {
return model.currencySymbol
}
var estimateString: String? {
return model.estimate
}
var highEstimateOrEstimateCents: UInt64? {
return model.highEstimateCents?.uint64Value ?? model.estimateCents?.uint64Value
}
var eventIDs: [String] {
return model.eventIDs
}
func eventWithID(_ string: String) -> LiveAuctionEventViewModel? {
return fullEventList.filter { $0.event.eventID == string }.first
}
var numberOfDerivedEvents: Int {
return derivedEvents.count
}
func derivedEventAtPresentationIndex(_ index: Int) -> LiveAuctionEventViewModel {
// Events are ordered FIFO, need to inverse for presentation
return derivedEvents[numberOfDerivedEvents - index - 1]
}
var reserveStatusString: String {
guard let status = reserveStatusSignal.peek() else {
return "unknown reserve"
}
switch status {
case .unknown: fallthrough
case .noReserve:
return "no reserve"
case .reserveMet:
return "reserve met"
case .reserveNotMet:
return "reserve not yet met"
default:
return "unknown reserve"
}
}
func updateReserveStatus(_ reserveStatusString: String) {
let updated = model.updateReserveStatus(with: reserveStatusString)
if updated {
reserveStatusSignal.update(model.reserveStatus)
}
}
func updateOnlineAskingPrice(_ askingPrice: UInt64) {
let updated = model.updateOnlineAskingPrice(askingPrice)
if updated {
askingPriceSignal.update(askingPrice)
}
}
func updateBiddingStatus(_ biddingStatus: String, wasPassed: Bool) {
model.updateBiddingStatus(with: biddingStatus)
biddingStatusSignal.update((status: model.biddingStatus, wasPassed: wasPassed, isHighestBidder: self.userIsWinning))
}
func updateOnlineBidCount(_ onlineBidCount: Int) {
model.onlineBidCount = onlineBidCount
numberOfBidsSignal.update(onlineBidCount)
}
func updateFloorWinningBidderID(_ floorWinningBidderID: String?) {
self.floorWinningBidderID = floorWinningBidderID
}
func updateSellingToBidder(_ sellingToBidderID: String?) {
self.sellingToBidderID = sellingToBidderID
}
func updateWinningBidEventID(_ winningBidEventId: String?) {
self.winningBidEventID = winningBidEventId
}
func addEvents(_ newEvents: [LiveEvent]) {
model.addEvents(newEvents.map { $0.eventID })
let newEventViewModels = newEvents.map { LiveAuctionEventViewModel(event: $0, currencySymbol: model.currencySymbol) }
fullEventList += newEventViewModels
updateExistingEventsWithLotState()
var allUserFacingEvents = fullEventList.filter { $0.isUserFacing }
if let winningBidEvent = allUserFacingEvents.remove(matching: { event in
guard let winningBidEventID = self.winningBidEventID else { return false }
return event.eventID == winningBidEventID
}) {
derivedEvents = allUserFacingEvents + [winningBidEvent]
} else {
derivedEvents = allUserFacingEvents
}
let newDerivedEvents = newEventViewModels.filter { $0.isUserFacing }
newEventsSignal.update(newDerivedEvents)
}
/// This isn't really very efficient, lots of loops to do lookups, maybe n^n?
fileprivate func updateExistingEventsWithLotState() {
// Undoes need applying
for undoEvent in fullEventList.filter({ $0.isUndo }) {
guard let
referenceEventID = undoEvent.undoLiveEventID,
let eventToUndo = eventWithID(referenceEventID) else { continue }
eventToUndo.cancel()
}
/// Setup Pending
for bidEvent in fullEventList.filter({ $0.isBidConfirmation }) {
guard let
amount = bidEvent.bidConfirmationAmount,
let eventToConfirm = findBidWithValue(amount) else { continue }
eventToConfirm.confirm()
}
/// Setup bidStatus, so an EventVM knows if it's top/owner by the user etc
for bidEvent in fullEventList.filter({ $0.isBid }) {
let isTopBid = (bidEvent.eventID == winningBidEvent?.eventID)
let isUser: Bool
if let bidderID = bidderCredentials.bidderID, bidderCredentials.canBid {
isUser = bidEvent.hasBidderID(bidderID)
} else {
isUser = false
}
if isUser && (userTopBidCents ?? 0) < (bidEvent.bidAmountCents ?? 0) {
userTopBidCents = bidEvent.bidAmountCents
}
let status: BidEventBidStatus
if bidEvent.isFloorBidder {
status = .bid(isMine: isUser, isTop: isTopBid, userIsFloorWinningBidder: false)
} else { // if bidEvent.isArtsyBidder {
status = .bid(isMine: isUser, isTop: isTopBid, userIsFloorWinningBidder: userIsFloorWinningBidder)
}
bidEvent.bidStatus = status
}
}
}
|
mit
|
77a3f2fc1bc724dc50494db279797548
| 31.16152 | 125 | 0.654579 | 4.62116 | false | false | false | false |
coderZsq/coderZsq.target.swift
|
StudyNotes/Swift Note/LiveBroadcast/Client/LiveBroadcast/Classes/Main/Extension/UIColor+Extension.swift
|
1
|
2104
|
//
// UIColor+Extension.swift
// LiveBroadcast
//
// Created by 朱双泉 on 2018/12/10.
// Copyright © 2018 Castie!. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1) {
self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a)
}
convenience init?(hex: String, alpha: CGFloat = 1) {
guard hex.count >= 6 else {
return nil
}
var tempHex = hex.uppercased()
if tempHex.hasPrefix("0x") || tempHex.hasPrefix("##") {
tempHex = (tempHex as NSString).substring(from: 2)
}
if tempHex.hasPrefix("#") {
tempHex = (tempHex as NSString).substring(from: 1)
}
var range = NSRange(location: 0, length: 2)
let rHex = (tempHex as NSString).substring(with: range)
range.location = 2
let gHex = (tempHex as NSString).substring(with: range)
range.location = 4
let bHex = (tempHex as NSString).substring(with: range)
var r: UInt32 = 0, g: UInt32 = 0, b: UInt32 = 0
Scanner(string: rHex).scanHexInt32(&r)
Scanner(string: gHex).scanHexInt32(&g)
Scanner(string: bHex).scanHexInt32(&b)
self.init(r: CGFloat(r), g: CGFloat(g), b: CGFloat(b))
}
class func randomColor() -> UIColor {
return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
}
class func getRGBDelta(_ firstColor: UIColor, _ secondColor: UIColor) -> (CGFloat, CGFloat, CGFloat) {
let firstRGB = firstColor.getRGB()
let secondRGB = secondColor.getRGB()
return (
firstRGB.0 - secondRGB.0,
firstRGB.1 - secondRGB.1,
firstRGB.2 - secondRGB.2
)
}
func getRGB() -> (CGFloat, CGFloat, CGFloat) {
guard let cmps = cgColor.components else {
fatalError("保证颜色是RGB方式传入")
}
return (cmps[0] * 255, cmps[1] * 255, cmps[2] * 255)
}
}
|
mit
|
57f314578ddc91936208566e7270b7e3
| 33.081967 | 133 | 0.575758 | 3.68617 | false | false | false | false |
ZhangHangwei/100_days_Swift
|
Project_31/Project_30/SearchResultViewController.swift
|
1
|
3278
|
//
// SearchResultViewController.swift
// Project_30
//
// Created by 章航伟 on 07/02/2017.
// Copyright © 2017 Harvie. All rights reserved.
//
import UIKit
class SearchResultViewController: UICollectionViewController {
let movieData = ["Mr. Donkey", "Tony and Susan", "The Day Will Come", "The Shawshank Redemption", "Léon", "Farewell My Concubine", "Forrest Gump", "La vita è bella", "Spirited Away", "Schindler's List", "Titanic","Inception", "WALL·E", "3 Idiots", "Les choristes", "Hachi: A Dog's Tale"]
fileprivate var filterData = [String]()
var showForm: ShowForm = .Featured
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
}
fileprivate func setupCollectionView() {
collectionView?.keyboardDismissMode = .onDrag
collectionView?.register(UINib(nibName: "FeaturedCell", bundle: nil), forCellWithReuseIdentifier: Identifier.FeaturedCell)
collectionView?.register(UINib(nibName: "ChartsCell", bundle: nil), forCellWithReuseIdentifier: Identifier.ChartsCell)
}
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filterData.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch showForm {
case .Featured:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Identifier.FeaturedCell, for: indexPath) as! FeaturedCell
cell.icon.image = UIImage(named: "\(indexPath.row).jpg")
cell.name.text = filterData[indexPath.row]
return cell
case .Charts:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Identifier.ChartsCell, for: indexPath) as! ChartsCell
cell.icon.image = UIImage(named: "\(indexPath.row).jpg")
cell.name.text = filterData[indexPath.row]
return cell
}
}
}
extension SearchResultViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
switch showForm {
case .Featured:
let width = (collectionView.bounds.width - 2 * 3.0) / 3.0
return CGSize(width: width, height: width * 1.5)
case .Charts:
return CGSize(width: collectionView.bounds.width, height: 100.0)
}
}
}
extension SearchResultViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let searchText = searchController.searchBar.text else {
return
}
filterData = movieData.filter {
return $0.range(of: searchText, options: .caseInsensitive) != nil
}
collectionView?.reloadData()
}
}
|
mit
|
2eb51a6aadacd2934855c8ade5fdebd5
| 33.765957 | 291 | 0.626989 | 5.279483 | false | false | false | false |
sssinsi/cocoapods_sample01
|
RSSReader/RSSReader/CompanyViewController.swift
|
1
|
2002
|
//
// CompanyViewController.swift
// CocoapodSample01
//
// Created by 福島 聖 on 2014/06/12.
// Copyright (c) 2014年 fukushima takashi. All rights reserved.
//
import UIKit
class CompanyViewController: UITableViewController,UITableViewDataSource, UITableViewDelegate{
var items:NSMutableArray! = nil
override func viewDidLoad(){
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView:UITableView!,heightForRowAtIndexPath indexPath:NSIndexPath!)->CGFloat{
return 100
}
override func numberOfSectionsInTableView(tableView:UITableView)->Int{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TechBlogURL.EndItem.toRaw()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"FeedCell")
if let item = TechBlogURL.fromRaw(indexPath.row){
cell.textLabel.text = item.name()
cell.textLabel.numberOfLines = 0
}
return cell
}
override func tableView(tableView:UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath){
self.performSegueWithIdentifier("selectBlog", sender: self)
}
override func prepareForSegue(segue:UIStoryboardSegue?,sender:AnyObject?){
if segue!.identifier == "selectBlog" {
let viewController : ViewController = segue!.destinationViewController as ViewController
var indexPath = self.tableView.indexPathForSelectedRow()
viewController.selectedIndex = indexPath.row
}
}
}
|
mit
|
ab5bf40581d56ee9e7e64e56de59e490
| 31.688525 | 118 | 0.683049 | 5.569832 | false | false | false | false |
aidudu/MyFish
|
MyFish/MyFish/AppDelegate.swift
|
1
|
3435
|
//
// AppDelegate.swift
// MyFish
//
// Created by cheny on 2017/6/29.
// Copyright © 2017年 LHTW. All rights reserved.
//
import UIKit
import IQKeyboardManagerSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow.init(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = UINavigationController.init(rootViewController:LoginController())
IQKeyboardManager.sharedManager().enable = true
return true
}
func afterLogin() {
let firstNav = UINavigationController.init(rootViewController: FirstController())
let chatNav = UINavigationController.init(rootViewController: ChatController())
let personNav = UINavigationController.init(rootViewController: PersonalController())
firstNav.title = "首页"
chatNav.title = "消息"
personNav.title = "我"
firstNav.tabBarItem.image = UIImage.init(named: "home_n")
chatNav.tabBarItem.image = UIImage.init(named: "xiaoxi_n")
personNav.tabBarItem.image = UIImage.init(named: "me_n")
firstNav.tabBarItem.selectedImage = UIImage.init(named: "home_s")
firstNav.tabBarItem.selectedImage = UIImage.init(named: "xiaoxi_s")
firstNav.tabBarItem.selectedImage = UIImage.init(named: "me_s")
let tabBar = UITabBarController.init()
tabBar.viewControllers = [firstNav,chatNav,personNav]
window?.rootViewController = tabBar
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
mit
|
0db21568610197e25a627ae99caf8960
| 42.316456 | 285 | 0.716248 | 5.321928 | false | false | false | false |
TrinadhKandula/MonkeyTestingiOS
|
samplePrj/PBDataTableView/PBDataTable/Classes/PBDataTableViewCell.swift
|
1
|
2353
|
//
// PBDataTableViewCell.swift
// PBDataTable
//
// Created by praveen b on 6/10/16.
// Copyright © 2016 Praveen. All rights reserved.
//
import UIKit
class PBDataTableViewCell: UITableViewCell {
var columnWidth: CGFloat = 80
@IBOutlet var leftBorderView: UIView!
@IBOutlet var rightBorderView: UIView!
@IBOutlet var bottomBorderView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
var labelXaxis: CGFloat = 0
for i in 0..<ApplicationDelegate.numberOfColumns {
let columnLbl = UILabel()
//If Last Column of the Cell is Button
if ApplicationDelegate.cellLastColumnButtonEnable == true && i == ApplicationDelegate.numberOfColumns-1 {
let editBtn = UIButton(type: .Custom)
editBtn.frame = CGRectMake(labelXaxis, (CGRectGetHeight(self.frame)-35)/2, 70,35)
editBtn.backgroundColor = UIColor(red: 64/255, green: 64/255, blue: 64/255, alpha: 1.0)
editBtn.tag = 100+i
editBtn.setTitle("Edit", forState: .Normal)
self.contentView.addSubview(editBtn)
}else {
columnLbl.frame = CGRectMake(labelXaxis, 0, columnWidth,CGRectGetHeight(self.frame))
columnLbl.textAlignment = .Center
columnLbl.font = UIFont(name: "Arial", size: 10)
columnLbl.tag = 100+i
columnLbl.adjustsFontSizeToFitWidth = true
self.contentView.addSubview(columnLbl)
}
if i != ApplicationDelegate.numberOfColumns-1 {
let innerBorderView = UIView()
innerBorderView.frame = CGRectMake(CGRectGetMaxX(columnLbl.frame)-1, 0, 1, CGRectGetHeight(self.frame))
innerBorderView.backgroundColor = UIColor(red: 64/255, green: 64/255, blue: 64/255, alpha: 1.0)
innerBorderView.tag = 200+i
self.contentView.addSubview(innerBorderView)
}
labelXaxis = labelXaxis + columnWidth
}
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
c8f37d2553e59d4527988ef3f4c2f43d
| 35.75 | 119 | 0.59949 | 4.761134 | false | false | false | false |
lucasmpaim/RMImagePicker
|
Source/RMAlbumPickerController.swift
|
1
|
11435
|
//
// RMAlbumPickerController.swift
// RMImagePicker
//
// Created by Riccardo Massari on 19/01/15.
// Copyright (c) 2015 Riccardo Massari. All rights reserved.
//
import UIKit
import Photos
let albumCellIdentifier = "albumCellId"
let albumRowHeigth = CGFloat(173)
protocol RMAssetSelectionDelegate {
func selectedAssets(assets: [PHAsset])
func cancelImagePicker()
func showMessage(picker: UICollectionViewController)
var maxImages: Int { get }
}
class UITableViewDetailCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .Subtitle, reuseIdentifier: reuseIdentifier)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class RMAlbumPickerController: UITableViewController, RMAssetSelectionDelegate, UIAlertViewDelegate, PHPhotoLibraryChangeObserver {
var assetsParent: RMAssetSelectionDelegate?
lazy var imageManager = PHCachingImageManager.defaultManager()
var allCollections: [PHFetchResult] = []
var maxImages: Int { return assetsParent!.maxImages }
func showMessage(picker: UICollectionViewController) {
self.assetsParent?.showMessage(picker)
}
override func viewDidLoad() {
super.viewDidLoad()
let cellNib = UINib(nibName: "RMAlbumCell", bundle: NSBundle(forClass: RMAlbumPickerController.self))
self.tableView.registerNib(cellNib, forCellReuseIdentifier: albumCellIdentifier)
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.navigationItem.title = NSLocalizedString("Albums", comment: "")
let cancelButton = UIBarButtonItem(
barButtonSystemItem: .Cancel,
target: self,
action: "cancelImagePicker")
self.navigationItem.rightBarButtonItem = cancelButton
PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
self.checkPhotoAuth()
let phFetchOptions = PHFetchOptions()
phFetchOptions.predicate = NSPredicate(format: "estimatedAssetCount > 0")
self.allCollections.append(
PHAssetCollection.fetchAssetCollectionsWithType(
.SmartAlbum,
subtype: .SmartAlbumUserLibrary,
options: nil
)
)
self.allCollections.append(
PHAssetCollection.fetchAssetCollectionsWithType(
.Album,
subtype: .Any,
options: phFetchOptions
)
)
}
func cancelImagePicker() {
self.assetsParent?.cancelImagePicker()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setToolbarHidden(true, animated: true)
}
override func viewDidDisappear(animated: Bool) {
PHPhotoLibrary.sharedPhotoLibrary().unregisterChangeObserver(self)
super.viewDidDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return self.allCollections.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return self.allCollections[section].count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: RMAlbumCell!
if let reCell = tableView.dequeueReusableCellWithIdentifier(albumCellIdentifier, forIndexPath: indexPath) as? RMAlbumCell {
cell = reCell
} else {
cell = NSBundle(forClass: RMAlbumPickerController.self).loadNibNamed("RMAlbumCell", owner: self, options: nil)[0] as! RMAlbumCell
}
// Increment the cell's tag
let currentTag = cell.tag + 1
cell.tag = currentTag
// Configure the cell...
let collection = self.allCollections[indexPath.section][indexPath.row] as! PHAssetCollection
var assetsCount: Int
var keyAssets: PHFetchResult!
if collection.assetCollectionType == .SmartAlbum {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
keyAssets = PHAsset.fetchAssetsInAssetCollection(collection, options: fetchOptions)
assetsCount = keyAssets.count
} else {
keyAssets = PHAsset.fetchKeyAssetsInAssetCollection(collection, options: nil)
assetsCount = collection.estimatedAssetCount
}
let scale = UIScreen.mainScreen().scale
let imageWidth = cell.poster1.bounds.width * scale
let imageHeight = cell.poster1.bounds.height * scale
for (idx, poster) in enumerate(cell.posterImgs) {
if idx < keyAssets.count {
self.imageManager.requestImageForAsset(
keyAssets[idx] as! PHAsset,
targetSize: CGSizeMake(imageWidth, imageHeight),
contentMode: .AspectFill,
options: nil,
resultHandler: { (image, info) -> Void in
if (cell.tag == currentTag) {
poster.image = image
}
})
} else {
if (cell.tag == currentTag) {
poster.image = nil
}
}
}
if (cell.tag == currentTag) {
cell.title.text = collection.localizedTitle
cell.count.text = "\(assetsCount)"
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let phFetchOptions = PHFetchOptions()
phFetchOptions.predicate = NSPredicate(format: "mediaType = %i", PHAssetMediaType.Image.rawValue)
let collection = self.allCollections[indexPath.section][indexPath.row] as! PHAssetCollection
let assets = PHAsset.fetchAssetsInAssetCollection(collection, options: phFetchOptions)
if assets.count > 0 {
let picker = RMAssetCollectionPicker()
picker.assetsParent = self
picker.assetsFetchResult = assets
picker.assetCollection = collection
self.navigationController?.pushViewController(picker, animated: true)
} else {
let placeholderVC = UIViewController(
nibName: "RMPlaceholderView",
bundle: NSBundle(forClass: RMAlbumPickerController.self)
)
self.navigationController?.pushViewController(placeholderVC, animated: true)
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return albumRowHeigth / UIScreen.mainScreen().scale
}
// MARK: - PHPhotoLibraryChangeObserver
func photoLibraryDidChange(changeInstance: PHChange!) {
// Call might come on any background queue. Re-dispatch to the main queue to handle it.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// check if there are changes to the assets (insertions, deletions, updates)
for (idx, fetchResult) in enumerate(self.allCollections) {
if let collectionChanges = changeInstance.changeDetailsForFetchResult(fetchResult) {
// get the new fetch result
self.allCollections[idx] = collectionChanges.fetchResultAfterChanges
if let tableView = self.tableView {
if (!collectionChanges.hasIncrementalChanges || collectionChanges.hasMoves) {
// we need to reload all if the incremental diffs are not available
tableView.reloadData()
} else {
// if we have incremental diffs, tell the collection view to animate insertions and deletions
self.tableView.beginUpdates()
if let removedIndexes = collectionChanges.removedIndexes {
tableView.deleteRowsAtIndexPaths(removedIndexes.rm_indexPathsFromIndexesWithSection(idx), withRowAnimation: .Automatic)
}
if let insertedIndexes = collectionChanges.insertedIndexes {
tableView.insertRowsAtIndexPaths(insertedIndexes.rm_indexPathsFromIndexesWithSection(idx), withRowAnimation: .Automatic)
}
if let changedIndexes = collectionChanges.changedIndexes {
tableView.reloadRowsAtIndexPaths(changedIndexes.rm_indexPathsFromIndexesWithSection(idx), withRowAnimation: .Automatic)
}
self.tableView.endUpdates()
}
}
}
}
})
}
// MARK: - RMAssetSelectionDelegate
func selectedAssets(assets: [PHAsset]) {
self.assetsParent?.selectedAssets(assets)
}
// MARK: - UIAlertViewDelegate
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == 1 {
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}
self.cancelImagePicker()
}
// MARK: - Utility
func checkPhotoAuth() {
PHPhotoLibrary.requestAuthorization { (status) -> Void in
switch status {
case .Restricted:
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let photoAuthAlert = UIAlertView(
title: NSLocalizedString("Access restricted", comment: "to the photo library"),
message: NSLocalizedString("This application needs access to your photo library but it seems that you're not authorized to grant this permission. Please contact someone who has higher privileges on the device.", comment: ""),
delegate: self,
cancelButtonTitle: NSLocalizedString("OK", comment: "")
)
photoAuthAlert.show()
})
case .Denied:
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let photoAuthAlert = UIAlertView(
title: NSLocalizedString("Please allow access", comment: "to the photo library"),
message: NSLocalizedString("This application needs access to your photo library. Please go to Settings > Privacy > Photos and switch this application to ON", comment: ""),
delegate: self,
cancelButtonTitle: NSLocalizedString("OK", comment: ""),
otherButtonTitles: NSLocalizedString("Settings", comment: "")
)
photoAuthAlert.show()
})
default:
break
}
}
}
}
|
mit
|
aaa3fff93f62a0f0b5b92e79f0bd649f
| 40.886447 | 250 | 0.617753 | 5.825267 | false | false | false | false |
gyro-n/PaymentsIos
|
GyronPayments/Classes/Models/Card.swift
|
1
|
651
|
//
// Card.swift
// Pods
//
// Created by David Ye on 2017/07/21.
// Copyright © 2016 gyron. All rights reserved.
//
//
import Foundation
open class Card: BaseModel {
public var id: String
public var name: String
public var secret: String
public var clientId: String
override init() {
id = ""
name = ""
secret = ""
clientId = ""
}
override open func mapFromObject(map: ResponseData) {
id = map["id"] as? String ?? ""
name = map["name"] as? String ?? ""
secret = map["secret"] as? String ?? ""
clientId = map["client_id"] as? String ?? ""
}
}
|
mit
|
616952ba91a266af5683bfbff99df02d
| 19.967742 | 57 | 0.541538 | 3.823529 | false | false | false | false |
magicmon/TWImageBrowser
|
Example/TWImageBrowser/ViewController.swift
|
1
|
3291
|
//
// ViewController.swift
// TWImageBrowser
//
// Created by Tae Woo Kang on 05/26/2016.
// Copyright (c) 2016 magicmon. All rights reserved.
//
import UIKit
import TWImageBrowser
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
let interactor = Interactor()
fileprivate let kTestCellMenuIdentifier = "kTestCellMenuIdentifier"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dequeuedCell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: kTestCellMenuIdentifier)
var cell: UITableViewCell? = nil
if let dequeuedCell = dequeuedCell {
cell = dequeuedCell
} else {
cell = UITableViewCell(style: .default, reuseIdentifier: kTestCellMenuIdentifier)
cell?.selectionStyle = .gray
}
switch indexPath.row {
case 0:
cell?.textLabel?.text = "Normal Type (Image)"
case 1:
cell?.textLabel?.text = "Normal Type (GIF)"
case 2:
cell?.textLabel?.text = "Browser Type"
default:
break
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch indexPath.row {
case 0:
performSegue(withIdentifier: "NormalSegue", sender: nil)
case 1:
if let controller = self.storyboard?.instantiateViewController(withIdentifier: "GIFViewController") {
self.navigationController?.pushViewController(controller, animated: true)
}
case 2:
if let controller = self.storyboard?.instantiateViewController(withIdentifier: "BannerController") {
self.navigationController?.pushViewController(controller, animated: true)
}
default:
break
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? UINavigationController {
destination.transitioningDelegate = self
if let vc = destination.viewControllers.first as? NormalController {
vc.interactor = interactor
}
}
}
}
extension ViewController: UIViewControllerTransitioningDelegate {
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return DismissAnimator()
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactor.hasStarted ? interactor : nil
}
}
|
mit
|
0cb020d51e3c827f8eb8980884d4f7d6
| 32.927835 | 144 | 0.649651 | 5.763573 | false | false | false | false |
johndpope/objc2swift
|
src/test/resources/instance_method_sample.swift
|
1
|
3121
|
class InstanceMethodSample: NSObject, Protocol1, Protocol2 {
func noParamNoRet() {
}
func oneIntParamNoRet(p1: Int) {
}
func twoIntParamsNoRet(n1: Int, opt2 n2: Int) {
}
func threeIntParamsNoRet(n1: Int, opt2 n2: Int, opt3 n3: Int) {
}
func noParamIntRet() -> Int {
}
func oneIntParamIntRet(n1: Int) -> Int {
}
func noParamUIntRet() -> UInt {
}
func noParamSIntRet() -> Int {
}
func oneUIntParamUIntRet(n1: UInt) -> UInt {
}
func noParamIdRet() -> AnyObject {
}
func noParamNoRetHasBody() {
}
func someParamSomeRetHasBody(p1: ClassB) -> ClassA {
}
func noParamLongRet() -> Int {
}
func noParamULongRet() -> UInt {
}
func noParamLongLongRet() -> Int64 {
}
func noParamULongLongRet() -> UInt64 {
}
func noParamShortRet() -> Int8 {
}
func noParamUShortRet() -> UInt8 {
}
func noParamFloatRet() -> Float {
}
func noParamDoubleRet() -> Double {
}
func oneFloatParamFloatRet(p1: Float) -> Float {
}
func oneFloatParamOneDoubleParamDoubleRet(p1: Float, dnum p2: Double) -> Double {
}
func noParamNoRetNoDef() {
}
func noParamNSNumberRetHasBody() -> NSNumber {
self.noParamIntRet()
self.oneIntParamIntRet(1)
}
func noParamNSStringRet() -> NSString {
}
func oneNSStringParamNSStringRet(p1: NSString) -> NSString {
}
func overloadSample(p1: NSString) -> NSString {
}
func overloadSample(p1: NSString, p2: NSString) -> NSString {
}
func overloadSample(p1: NSString, q2: NSNumber) -> NSString {
}
func extNameSample1(p1: NSString, p2: NSNumber) -> NSString {
}
func extNameSample2(p1: NSString, p2: NSNumber) -> NSString {
}
func extNameSample3(p1: NSString, pp p2: NSNumber) -> NSString {
}
func noParamNoRetNoDef2() {
}
func privateMethodSample(p1: NSString, pp p2: NSNumber) -> NSString {
}
func privateMethodSampleHasBody(p1: NSString, pp p2: NSNumber) -> NSString {
self.noParamIntRet()
self.oneIntParamIntRet(1)
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> NSString {
return nil
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.shouldShowSection(section) ? self.numberOfQueriesInSection(section) : 0
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var reuseId: NSString = (indexPath.section == YSSSearchPanelSectionFavorite) ? kFavKeywordCellIdentifier : kDefaultCellIdentifier
var cell: YSSSearchPanelTableViewCell = tableView.dequeueReusableCellWithIdentifier(reuseId)
cell.searchPanelViewController = self
cell.query = self.queryAtIndexPath(indexPath)
return cell
}
}
|
mit
|
3f4a18361a5f7a1eb5957765eaacc3e3
| 17.801205 | 137 | 0.634092 | 3.950633 | false | false | false | false |
naru-jpn/struct-archiver
|
Sources/CustomArchivable.swift
|
1
|
2802
|
//
// CustomArchivable.swift
// StructArchiver
//
// Created by naru on 2016/05/24.
// Copyright © 2016年 naru. All rights reserved.
//
import Foundation
/// Protocol for custom archivable struct
public protocol CustomArchivable: Archivable, ElementArchivable {
/// Closure to restore struct from unarchived dictionary.
static var restoreProcedure: ArchiveRestoreProcedure { get }
}
public extension CustomArchivable {
func archivable() -> Archivable {
var children: ArchivableDictionary = ArchivableDictionary()
Mirror(reflecting: self).children.forEach { label, value in
if let label = label, value = value as? Archivable {
if let elementArchivable: ElementArchivable = value as? ElementArchivable {
children[label] = elementArchivable.archivable()
} else {
children[label] = value
}
}
}
return children
}
public final var archivedIdentifier: String {
return "\(Mirror(reflecting: self).subjectType)"
}
public static var archivedIdentifier: String {
return "\(self)"
}
public var archivedDataLength: Int {
let archivableChildren: ArchivableDictionary = self.archivable() as! ArchivableDictionary
let elementsLength: Int = archivableChildren.keys.reduce(0) { (length, key) in
length + key.archivedDataLength
} + archivableChildren.values.reduce(0) { (length, value) in
length + value.archivedDataLength
}
return self.archivedIDLength + Int.ArchivedDataLength*(1+archivableChildren.keys.count*2) + elementsLength
}
public var archivedHeaderData: [NSData] {
let archivableChildren: ArchivableDictionary = self.archivable() as! ArchivableDictionary
return archivableChildren.archivedHeaderData
}
public var archivedBodyData: [NSData] {
let archivableChildren: ArchivableDictionary = self.archivable() as! ArchivableDictionary
return archivableChildren.archivedBodyData
}
public static var unarchiveProcedure: ArchiveUnarchiveProcedure {
return ArchivableDictionary.unarchiveProcedure
}
/// Store procedure to unarchive and restore data on memory.
public static func activateArchive() {
StructArchiver.registerUnarchiveProcedure(identifier: self.archivedIdentifier, procedure: self.unarchiveProcedure)
StructArchiver.registerRestoreProcedure(identifier: self.archivedIdentifier, procedure: self.restoreProcedure)
StructArchiver.registerUnarchiveProcedure(identifier: "Array<\(self.archivedIdentifier)>", procedure: Archivables.unarchiveProcedure)
}
}
|
mit
|
5812281723f47aeae9637c2884c0edcd
| 35.828947 | 141 | 0.679886 | 4.989305 | false | false | false | false |
OlegKetrar/AlertDispatcher
|
Sources/AlertUIKit.swift
|
1
|
3896
|
//
// AlertUIKit.swift
// AlertDispatcher
//
// Created by Oleg Ketrar on 10.02.17.
// Copyright © 2017 Oleg Ketrar. All rights reserved.
//
import UIKit
extension Alert {
/// Tint color for all alerts.
public static var tintColor: UIColor?
/// Default localized title for `OK` button.
public static var defaultOkeyTitle: String = {
return "Ok".localized(with: .UIKit)
}()
/// Default localized title for `Cancel` button.
public static var defaultCancelTitle: String = {
return "Cancel".localized(with: .UIKit)
}()
/// Recursivelly find top `UIViewController`.
public static var topViewController: UIViewController {
guard let rootVC = UIApplication.shared.keyWindow?.rootViewController else {
fatalError("UIApplication.keyWindow does not have rootViewController")
}
func presentedVC(to parent: UIViewController) -> UIViewController {
if let modal = parent.presentedViewController {
return presentedVC(to: modal)
} else {
return parent
}
}
return presentedVC(to: rootVC)
}
/// Simple alert with `OK` button.
public static func alert(
title: String,
message: String? = nil,
tintColor: UIColor? = Alert.tintColor,
cancelTitle: String = defaultOkeyTitle,
completion: @escaping () -> Void = {}) -> Alert {
return Alert { finish in
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: .alert)
let cancel = UIAlertAction(
title: cancelTitle,
style: .default,
handler: { _ in
delay { finish(); completion() }
})
alert.addAction(cancel)
if let tintColor = tintColor {
alert.view.tintColor = tintColor
}
Alert.topViewController.present(alert, animated: true)
// if system can't present alert,
// we need to unblock our alert queue
if alert.presentingViewController == nil {
finish()
}
}
}
/// Dialog with `ACTION` & `CANCEL` buttons (perform action with UI request).
public static func dialog(
title: String,
message: String? = nil,
tintColor: UIColor? = Alert.tintColor,
cancelTitle: String = defaultCancelTitle,
actionTitle: String = defaultOkeyTitle,
isDestructive: Bool = false,
actionClosure: @escaping () -> Void,
completion: @escaping () -> Void = {}) -> Alert {
return Alert { finish in
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: .alert)
let cancel = UIAlertAction(
title: cancelTitle,
style: .cancel,
handler: { _ in
delay { finish(); completion() }
})
let action = UIAlertAction(
title: actionTitle,
style: isDestructive ? .destructive : .default,
handler: { _ in
delay { finish(); actionClosure(); completion() }
})
alert.addAction(cancel)
alert.addAction(action)
alert.preferredAction = isDestructive ? cancel : action
if let tintColor = tintColor {
alert.view.tintColor = tintColor
}
Alert.topViewController.present(alert, animated: true)
// if system can't present alert,
// we need to unblock our alert queue
if alert.presentingViewController == nil {
finish()
}
}
}
}
|
mit
|
5e2f5419e0f467dbd7b8d0f5e2d670e2
| 28.732824 | 84 | 0.541463 | 5.387275 | false | false | false | false |
imxieyi/waifu2x-ios
|
waifu2x/MLModel+Prediction.swift
|
3
|
1066
|
//
// MLModel+Prediction.swift
// waifu2x-ios
//
// Created by 谢宜 on 2017/11/5.
// Copyright © 2017年 xieyi. All rights reserved.
//
import Foundation
import CoreML
/// Model Prediction Input Type
class Waifu2xInput: MLFeatureProvider {
/// input as whatever array of doubles
var input: MLMultiArray
var featureNames: Set<String> {
get {
return ["input"]
}
}
func featureValue(for featureName: String) -> MLFeatureValue? {
if (featureName == "input") {
return MLFeatureValue(multiArray: input)
}
return nil
}
init(_ input: MLMultiArray) {
self.input = input
}
}
// MARK: - Make coreml models more generic to use
extension MLModel {
public func prediction(input: MLMultiArray) throws -> MLMultiArray {
let input_ = Waifu2xInput(input)
let outFeatures = try self.prediction(from: input_)
let result = outFeatures.featureValue(for: "conv7")!.multiArrayValue!
return result
}
}
|
mit
|
19062d0d077702a9306622f7ed080287
| 21.531915 | 77 | 0.610954 | 4.136719 | false | false | false | false |
fluidpixel/SquashTracker
|
SquashTracker/SwiftCharts/Axis/ChartAxisYLowLayerDefault.swift
|
1
|
1794
|
//
// ChartAxisYLowLayerDefault.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
class ChartAxisYLowLayerDefault: ChartAxisYLayerDefault {
override var low: Bool {return true}
override var lineP1: CGPoint {
return CGPointMake(self.p1.x + self.lineOffset, self.p1.y)
}
override var lineP2: CGPoint {
return CGPointMake(self.p2.x + self.lineOffset, self.p2.y)
}
private lazy var labelsOffset: CGFloat = {
return self.axisTitleLabelsHeight + self.settings.axisTitleLabelsToLabelsSpacing
}()
private lazy var lineOffset: CGFloat = {
return self.labelsOffset + self.labelsMaxWidth + self.settings.labelsToAxisSpacingY + self.settings.axisStrokeWidth
}()
override func initDrawers() {
self.axisTitleLabelDrawers = self.generateAxisTitleLabelsDrawers(offset: 0)
self.labelDrawers = self.generateLabelDrawers(offset: self.labelsOffset)
self.lineDrawer = self.generateLineDrawer(offset: self.lineOffset)
}
override func generateLineDrawer(offset offset: CGFloat) -> ChartLineDrawer {
let halfStrokeWidth = self.settings.axisStrokeWidth / 2 // we want that the stroke ends at the end of the frame, not be in the middle of it
let p1 = CGPointMake(self.p1.x + offset - halfStrokeWidth, self.p1.y)
let p2 = CGPointMake(self.p2.x + offset - halfStrokeWidth, self.p2.y)
return ChartLineDrawer(p1: p1, p2: p2, color: self.settings.lineColor)
}
override func labelsX(offset offset: CGFloat, labelWidth: CGFloat) -> CGFloat {
let labelsXRight = self.p1.x + offset + self.labelsMaxWidth
return labelsXRight - labelWidth
}
}
|
gpl-2.0
|
1a3498f3c4635ca137c83801580f915a
| 36.375 | 147 | 0.693423 | 4.152778 | false | false | false | false |
Urinx/SublimeCode
|
Sublime/Sublime/GomokuViewController.swift
|
1
|
1712
|
//
// GameOfGoViewController.swift
// Sublime
//
// Created by Eular on 4/14/16.
// Copyright © 2016 Eular. All rights reserved.
//
import UIKit
class GomokuViewController: UIViewController {
let board = GomokuBoardView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Constant.CapeCod
board.onWin = {
self.view.Toast(message: "黑棋赢")
}
board.onLose = {
self.view.Toast(message: "白棋赢")
}
view.addSubview(board)
board.atCenter()
addCloseBtn()
addNewBtn()
}
func close() {
self.dismissViewControllerAnimated(true, completion: nil)
}
func addCloseBtn() {
let closeBtn = UIButton()
closeBtn.setTitle("<-", forState: .Normal)
closeBtn.setTitleColor(UIColor.grayColor(), forState: .Normal)
closeBtn.frame = CGRectMake(10, view.height - 20, 20, 10)
closeBtn.addTarget(self, action: #selector(self.close), forControlEvents: .TouchUpInside)
view.addSubview(closeBtn)
}
func addNewBtn() {
let newBtn = UIButton()
newBtn.setTitle("new", forState: .Normal)
newBtn.setTitleColor(UIColor.grayColor(), forState: .Normal)
newBtn.titleLabel?.font = newBtn.titleLabel?.font.fontWithSize(13)
newBtn.frame = CGRectMake(view.width - 40, view.height - 22, 30, 15)
newBtn.addTarget(self, action: #selector(board.reset), forControlEvents: .TouchUpInside)
view.addSubview(newBtn)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
|
gpl-3.0
|
faf602a9a4dc6c2406963a5d2d27de22
| 28.293103 | 97 | 0.621542 | 4.258145 | false | false | false | false |
johnno1962/eidolon
|
KioskTests/Bid Fulfillment/LoadingViewModelTests.swift
|
1
|
6971
|
import Quick
import Nimble
@testable
import Kiosk
import RxSwift
class LoadingViewModelTests: QuickSpec {
override func spec() {
var stubbedNetworkModel: StubBidderNetworkModel!
var subject: LoadingViewModel!
var disposeBag: DisposeBag!
beforeEach {
// The subject's reference to its network model is unowned, so we must take responsibility for it.
stubbedNetworkModel = StubBidderNetworkModel()
disposeBag = DisposeBag()
}
it("loads placeBidNetworkModel") {
subject = LoadingViewModel(provider: Networking.newStubbingNetworking(), bidNetworkModel: stubbedNetworkModel, placingBid: false, actionsComplete: Observable.never())
expect(subject.placeBidNetworkModel.bidDetails as AnyObject) === subject.bidderNetworkModel.bidDetails as AnyObject
}
it("loads bidCheckingModel") {
subject = LoadingViewModel(provider: Networking.newStubbingNetworking(), bidNetworkModel: stubbedNetworkModel, placingBid: false, actionsComplete: Observable.never())
expect(subject.bidCheckingModel.bidDetails as AnyObject) === subject.bidderNetworkModel.bidDetails
}
it("initializes with bidNetworkModel") {
let networkModel = StubBidderNetworkModel()
subject = LoadingViewModel(provider: Networking.newStubbingNetworking(), bidNetworkModel: networkModel, placingBid: false, actionsComplete: Observable.never())
expect(subject.bidderNetworkModel.bidDetails as AnyObject) === networkModel.bidDetails as AnyObject
}
it("initializes with placingBid = false") {
subject = LoadingViewModel(provider: Networking.newStubbingNetworking(), bidNetworkModel: stubbedNetworkModel, placingBid: false, actionsComplete: Observable.never())
expect(subject.placingBid) == false
}
it("initializes with placingBid = true") {
subject = LoadingViewModel(provider: Networking.newStubbingNetworking(), bidNetworkModel: stubbedNetworkModel, placingBid: true, actionsComplete: Observable.never())
expect(subject.placingBid) == true
}
it("binds createdNewBidder") {
subject = LoadingViewModel(provider: Networking.newStubbingNetworking(), bidNetworkModel: stubbedNetworkModel, placingBid: true, actionsComplete: Observable.never())
stubbedNetworkModel.createdNewBidderSubject.onNext(true)
expect(subject.createdNewBidder) == true
}
it("binds bidIsResolved") {
subject = LoadingViewModel(provider: Networking.newStubbingNetworking(), bidNetworkModel: stubbedNetworkModel, placingBid: true, actionsComplete: Observable.never())
subject.bidCheckingModel.bidIsResolved.value = true
expect(subject.bidIsResolved) == true
}
it("binds isHighestBidder") {
subject = LoadingViewModel(provider: Networking.newStubbingNetworking(), bidNetworkModel: stubbedNetworkModel, placingBid: true, actionsComplete: Observable.never())
subject.bidCheckingModel.isHighestBidder.value = true
expect(subject.isHighestBidder) == true
}
it("binds reserveNotMet") {
subject = LoadingViewModel(provider: Networking.newStubbingNetworking(), bidNetworkModel: stubbedNetworkModel, placingBid: true, actionsComplete: Observable.never())
subject.bidCheckingModel.reserveNotMet.value = true
expect(subject.reserveNotMet) == true
}
it("infers bidDetals") {
subject = LoadingViewModel(provider: Networking.newStubbingNetworking(), bidNetworkModel: stubbedNetworkModel, placingBid: true, actionsComplete: Observable.never())
expect(subject.bidDetails) === subject.bidderNetworkModel.bidDetails
}
it("creates a new bidder if necessary") {
subject = LoadingViewModel(provider: Networking.newStubbingNetworking(), bidNetworkModel: stubbedNetworkModel, placingBid: false, actionsComplete: Observable.never())
kioskWaitUntil { (done) in
subject.performActions().subscribeCompleted { done() }.addDisposableTo(disposeBag)
}
expect(subject.createdNewBidder) == true
}
describe("stubbed auxillary network models") {
var stubPlaceBidNetworkModel: StubPlaceBidNetworkModel!
var stubBidCheckingNetworkModel: StubBidCheckingNetworkModel!
beforeEach {
stubPlaceBidNetworkModel = StubPlaceBidNetworkModel()
stubBidCheckingNetworkModel = StubBidCheckingNetworkModel()
subject = LoadingViewModel(provider: Networking.newStubbingNetworking(), bidNetworkModel: stubbedNetworkModel, placingBid: true, actionsComplete: Observable.never())
subject.placeBidNetworkModel = stubPlaceBidNetworkModel
subject.bidCheckingModel = stubBidCheckingNetworkModel
}
it("places a bid if necessary") {
kioskWaitUntil { done in
subject.performActions().subscribeCompleted { done() }.addDisposableTo(disposeBag)
return
}
expect(stubPlaceBidNetworkModel.hasBid) == true
}
it("waits for bid resolution if bid was placed") {
kioskWaitUntil { done in
subject.performActions().subscribeCompleted { done() }.addDisposableTo(disposeBag)
}
expect(stubBidCheckingNetworkModel.checked) == true
}
}
}
}
let bidderID = "some-bidder-id"
class StubBidderNetworkModel: BidderNetworkModelType {
var createdNewBidderSubject = PublishSubject<Bool>()
var bidDetails: BidDetails = testBidDetails()
var createdNewUser: Observable<Bool> { return createdNewBidderSubject.asObservable().startWith(false) }
func createOrGetBidder() -> Observable<AuthorizedNetworking> {
createdNewBidderSubject.onNext(true)
return Observable.just(Networking.newAuthorizedStubbingNetworking())
}
}
class StubPlaceBidNetworkModel: PlaceBidNetworkModelType {
var hasBid = false
var bidDetails: BidDetails = testBidDetails()
func bid(provider: AuthorizedNetworking) -> Observable<String> {
hasBid = true
return Observable.just(bidderID)
}
}
class StubBidCheckingNetworkModel: BidCheckingNetworkModelType {
var checked = false
var bidIsResolved = Variable(false)
var isHighestBidder = Variable(false)
var reserveNotMet = Variable(false)
var bidDetails: BidDetails = testBidDetails()
let fulfillmentController: FulfillmentController = StubFulfillmentController()
func waitForBidResolution (bidderPositionId: String, provider: AuthorizedNetworking) -> Observable<Void> {
checked = true
return Observable.empty()
}
}
|
mit
|
1099b76a64d0cba14773c6761dbaf7e1
| 40.993976 | 181 | 0.689715 | 5.37057 | false | false | false | false |
Stitch7/mclient
|
mclient/PrivateMessages/Cells/PrivateMessagesConversationTableViewCell.swift
|
1
|
2764
|
//
// PrivateMessagesConversationTableViewCell.swift
// mclient
//
// Copyright © 2014 - 2019 Christopher Reitz. Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
//
class PrivateMessagesConversationTableViewCell: UITableViewCell {
@objc static let Identifier = "ConversationCell"
@IBOutlet weak var avatarImageView: UserAvatarImageView!
@IBOutlet weak var readSymbolView: MCLReadSymbolView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var lastMessageDateLabel: UILabel!
@IBOutlet weak var lastMessageTextLabel: UILabel!
@IBOutlet weak var arrowForwardImageView: UIImageView!
@objc var dateFormatter: DateFormatter?
@objc var bag: MCLDependencyBag? {
didSet {
guard let bag = bag else { return }
let theme = bag.themeManager.currentTheme
textLabel?.textColor = theme?.textColor()
detailTextLabel?.textColor = theme?.textColor()
let backgroundView = UIView(frame: frame)
backgroundView.backgroundColor = theme?.tableViewCellSelectedBackgroundColor()
selectedBackgroundView = backgroundView;
}
}
@objc var conversation: MCLPrivateMessageConversation? {
didSet {
guard let conversation = self.conversation else { return }
if let user = User(id: 0, username: conversation.username) {
avatarImageView.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
avatarImageView.user = user
}
usernameLabel.text = conversation.username
lastMessageDateLabel.text = dateFormatter?.string(from: conversation.lastMessage.date)
lastMessageTextLabel.text = conversation.lastMessage.subject
if conversation.hasUnreadMessages() {
readSymbolView.color = tintColor
lastMessageTextLabel.font = UIFont.boldSystemFont(ofSize: lastMessageTextLabel.font.pointSize)
} else {
readSymbolView.color = bag?.themeManager.currentTheme.tableViewCellBackgroundColor()
lastMessageTextLabel.font = UIFont.systemFont(ofSize: lastMessageTextLabel.font.pointSize)
}
lastMessageDateLabel.textColor = .gray
arrowForwardImageView.tintColor = .lightGray
arrowForwardImageView.image = arrowForwardImageView.image?.withRenderingMode(.alwaysTemplate)
bag?.privateMessagesManager.privateMessagesCache.load(privateMessage: conversation.lastMessage) { (cachedMessage) in
if let message = cachedMessage {
lastMessageTextLabel.text = message.text
}
}
}
}
}
|
mit
|
c8f773e97530b1169bd41f7fbe4aa509
| 39.043478 | 128 | 0.669924 | 5.503984 | false | false | false | false |
Ramotion/expanding-collection
|
Source/ExpandingViewController/ExpandingViewController.swift
|
1
|
4870
|
//
// PageViewController.swift
// TestCollectionView
//
// Created by Alex K. on 05/05/16.
// Copyright © 2016 Alex K. All rights reserved.
//
import UIKit
/// UIViewController with UICollectionView with custom transition method
open class ExpandingViewController: UIViewController {
/// The default size to use for cells. Height of open cell state
open var itemSize = CGSize(width: 256, height: 460)
/// The collection view object managed by this view controller.
open var collectionView: UICollectionView?
fileprivate var transitionDriver: TransitionDriver?
/// Index of current cell
open var currentIndex: Int {
guard let collectionView = self.collectionView else { return 0 }
let startOffset = (collectionView.bounds.size.width - itemSize.width) / 2
guard let collectionLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
return 0
}
let minimumLineSpacing = collectionLayout.minimumLineSpacing
let a = collectionView.contentOffset.x + startOffset + itemSize.width / 2
let b = itemSize.width + minimumLineSpacing
return Int(a / b)
}
}
// MARK: life cicle
extension ExpandingViewController {
open override func viewDidLoad() {
super.viewDidLoad()
commonInit()
}
}
// MARK: Transition
public extension ExpandingViewController {
/**
Pushes a view controller onto the receiver’s stack and updates the display with custom animation.
- parameter viewController: The table view controller to push onto the stack.
*/
func pushToViewController(_ viewController: ExpandingTableViewController) {
guard let collectionView = self.collectionView,
let navigationController = self.navigationController else {
return
}
viewController.transitionDriver = transitionDriver
let insets = viewController.automaticallyAdjustsScrollViewInsets
let tabBarHeight = insets == true ? navigationController.navigationBar.frame.size.height : 0
let stausBarHeight = insets == true ? UIApplication.shared.statusBarFrame.size.height : 0
let backImage = getBackImage(viewController, headerHeight: viewController.headerHeight)
transitionDriver?.pushTransitionAnimationIndex(currentIndex,
collecitionView: collectionView,
backImage: backImage,
headerHeight: viewController.headerHeight,
insets: tabBarHeight + stausBarHeight) { headerView in
viewController.tableView.tableHeaderView = headerView
self.navigationController?.pushViewController(viewController, animated: false)
}
}
}
// MARK: create
extension ExpandingViewController {
fileprivate func commonInit() {
let layout = PageCollectionLayout(itemSize: itemSize)
collectionView = PageCollectionView.createOnView(view,
layout: layout,
height: itemSize.height,
dataSource: self,
delegate: self)
if #available(iOS 10.0, *) {
collectionView?.isPrefetchingEnabled = false
}
transitionDriver = TransitionDriver(view: view)
}
}
// MARK: Helpers
extension ExpandingViewController {
fileprivate func getBackImage(_ viewController: UIViewController, headerHeight: CGFloat) -> UIImage? {
let imageSize = CGSize(width: viewController.view.bounds.width, height: viewController.view.bounds.height - headerHeight)
let imageFrame = CGRect(origin: CGPoint(x: 0, y: 0), size: imageSize)
return viewController.view.takeSnapshot(imageFrame)
}
}
// MARK: UICollectionViewDataSource
extension ExpandingViewController: UICollectionViewDataSource, UICollectionViewDelegate {
open func collectionView(_: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt _: IndexPath) {
guard case let cell as BasePageCollectionCell = cell else {
return
}
cell.configureCellViewConstraintsWithSize(itemSize)
}
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
open func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
fatalError("need emplementation in subclass")
}
open func collectionView(_: UICollectionView, cellForItemAt _: IndexPath) -> UICollectionViewCell {
fatalError("need emplementation in subclass")
}
}
|
mit
|
c63bf9d191b1a2c0a115b320b6c8e162
| 35.871212 | 129 | 0.651942 | 5.979115 | false | false | false | false |
jonesgithub/MLSwiftBasic
|
MLSwiftBasic/Classes/Base/MBBaseViewController.swift
|
8
|
4698
|
// github: https://github.com/MakeZL/MLSwiftBasic
// author: @email <[email protected]>
//
// MBBaseViewController.swift
// MakeBolo
//
// Created by 张磊 on 15/6/14.
// Copyright (c) 2015年 MakeZL. All rights reserved.
//
import UIKit
class MBBaseViewController: UIViewController,MBNavigationBarViewDelegate {
var isBack:Bool{
set{
self.navBar.back = newValue;
}
get{
return self.navBar.back
}
}
lazy var navBar:MBNavigationBarView = {
if self.view.viewWithTag(10000001) == nil {
var navBar = MBNavigationBarView()
navBar.tag = 10000001
navBar.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, TOP_Y)
navBar.autoresizingMask = .FlexibleWidth
navBar.delegate = self
navBar.backgroundColor = NAV_BG_COLOR
navBar.title = self.titleStr()
navBar.leftStr = self.leftStr()
navBar.rightStr = self.rightStr()
if (self.rightTitles().count > 0) {
navBar.rightTitles = self.rightTitles()
}
if (self.rightImgs().count > 0) {
navBar.rightImgs = self.rightImgs()
}
self.view.insertSubview(navBar, atIndex: 0)
if self.leftImg().isEmpty == false {
navBar.leftImage = self.leftImg()
navBar.leftButton.setImage(UIImage(named: self.leftImg()), forState: .Normal)
}
if self.titleImg().isEmpty == false {
navBar.titleImage = self.titleImg()
navBar.titleButton.setImage(UIImage(named: self.titleImg()), forState: .Normal)
}
if self.rightImg().isEmpty == false {
navBar.rightImage = self.rightImg()
navBar.rightButton.setImage(UIImage(named: self.rightImg()), forState: .Normal)
}
return navBar
}
return self.view.viewWithTag(10000001) as! MBNavigationBarView
}()
func setTitleStr(title:String!){
if var str:String = title{
self.navBar.title = str
}
}
func titleStr() -> String{
return ""
}
func leftStr() -> String {
return "";
}
func rightStr() -> String {
return "";
}
func titleImg() -> String {
return "";
}
func leftImg() -> String {
return "";
}
func rightImg() -> String {
return "";
}
func rightImgs() -> NSArray {
return []
}
func rightTitles() -> NSArray {
return []
}
func rightItemWidth() -> CGFloat {
return NAV_ITEM_RIGHT_W
}
func leftItemWidth() -> CGFloat {
return NAV_ITEM_LEFT_W
}
// <#navigationNavBarView Delegate>
func goBack() {
self.navigationController?.popViewControllerAnimated(true)
}
func rightClickAtIndexBtn(button:UIButton){
}
func titleClick() {
}
func leftClick(){
}
func rightClick(){
}
func setNavBarViewBackgroundColor(color :UIColor){
self.navBar.backgroundColor = color
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.removeFromSuperview()
self.view.backgroundColor = BG_COLOR
self.setupMenuClickEvent()
self.setupNavItemWidthOrHeight()
}
func setupMenuClickEvent(){
self.navBar.titleButton.addTarget(self, action: "titleClick", forControlEvents: .TouchUpInside)
self.navBar.leftButton.addTarget(self, action:"leftClick", forControlEvents: .TouchUpInside)
self.navBar.rightButton.addTarget(self, action:"rightClick", forControlEvents: .TouchUpInside)
for (var i = 0; i < self.navBar.rightTitles.count; i++){
self.navBar.rightTitles[i].addTarget(self, action: "rightClickAtIndexBtn:", forControlEvents: .TouchUpInside)
}
}
func setupNavItemWidthOrHeight(){
self.navBar.rightItemWidth = self.rightItemWidth()
self.navBar.leftItemWidth = self.leftItemWidth()
}
func addBottomLineView(view :UIView) -> UIView {
let lineView = UIView(frame: CGRectMake(0, CGRectGetMaxY(view.frame) - 1, view.frame.width, 1))
lineView.backgroundColor = UIColor(red: 230.0/256.0, green: 230.0/256.0, blue: 230.0/256.0, alpha: 1.0)
view.addSubview(lineView)
return lineView
}
}
|
mit
|
ee207d61199b530caff5bb713821a61f
| 26.763314 | 121 | 0.564152 | 4.564202 | false | false | false | false |
Johennes/firefox-ios
|
Sync/State.swift
|
1
|
19676
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
import SwiftKeychainWrapper
private let log = Logger.syncLogger
/*
* This file includes types that manage intra-sync and inter-sync metadata
* for the use of synchronizers and the state machine.
*
* See docs/sync.md for details on what exactly we need to persist.
*/
public struct Fetched<T: Equatable>: Equatable {
let value: T
let timestamp: Timestamp
}
public func ==<T: Equatable>(lhs: Fetched<T>, rhs: Fetched<T>) -> Bool {
return lhs.timestamp == rhs.timestamp &&
lhs.value == rhs.value
}
public enum LocalCommand: CustomStringConvertible, Hashable {
// We've seen something (a blank server, a changed global sync ID, a
// crypto/keys with a different meta/global) that requires us to reset all
// local engine timestamps (save the ones listed) and possibly re-upload.
case ResetAllEngines(except: Set<String>)
// We've seen something (a changed engine sync ID, a crypto/keys with a
// different per-engine bulk key) that requires us to reset our local engine
// timestamp and possibly re-upload.
case ResetEngine(engine: String)
// We've seen a change in meta/global: an engine has come or gone.
case EnableEngine(engine: String)
case DisableEngine(engine: String)
public func toJSON() -> JSON {
switch (self) {
case let .ResetAllEngines(except):
return JSON(["type": "ResetAllEngines", "except": Array(except).sort()])
case let .ResetEngine(engine):
return JSON(["type": "ResetEngine", "engine": engine])
case let .EnableEngine(engine):
return JSON(["type": "EnableEngine", "engine": engine])
case let .DisableEngine(engine):
return JSON(["type": "DisableEngine", "engine": engine])
}
}
public static func fromJSON(json: JSON) -> LocalCommand? {
if json.isError {
return nil
}
guard let type = json["type"].asString else {
return nil
}
switch type {
case "ResetAllEngines":
if let except = json["except"].asArray where except.every({$0.isString}) {
return .ResetAllEngines(except: Set(except.map({$0.asString!})))
}
return nil
case "ResetEngine":
if let engine = json["engine"].asString {
return .ResetEngine(engine: engine)
}
return nil
case "EnableEngine":
if let engine = json["engine"].asString {
return .EnableEngine(engine: engine)
}
return nil
case "DisableEngine":
if let engine = json["engine"].asString {
return .DisableEngine(engine: engine)
}
return nil
default:
return nil
}
}
public var description: String {
return self.toJSON().toString()
}
public var hashValue: Int {
return self.description.hashValue
}
}
public func ==(lhs: LocalCommand, rhs: LocalCommand) -> Bool {
switch (lhs, rhs) {
case (let .ResetAllEngines(exceptL), let .ResetAllEngines(exceptR)):
return exceptL == exceptR
case (let .ResetEngine(engineL), let .ResetEngine(engineR)):
return engineL == engineR
case (let .EnableEngine(engineL), let .EnableEngine(engineR)):
return engineL == engineR
case (let .DisableEngine(engineL), let .DisableEngine(engineR)):
return engineL == engineR
default:
return false
}
}
/*
* Persistence pref names.
* Note that syncKeyBundle isn't persisted by us.
*
* Note also that fetched keys aren't kept in prefs: we keep the timestamp ("PrefKeysTS"),
* and we keep a 'label'. This label is used to find the real fetched keys in the Keychain.
*/
private let PrefVersion = "_v"
private let PrefGlobal = "global"
private let PrefGlobalTS = "globalTS"
private let PrefKeyLabel = "keyLabel"
private let PrefKeysTS = "keysTS"
private let PrefLastFetched = "lastFetched"
private let PrefLocalCommands = "localCommands"
private let PrefClientName = "clientName"
private let PrefClientGUID = "clientGUID"
private let PrefEngineConfiguration = "engineConfiguration"
class PrefsBackoffStorage: BackoffStorage {
let prefs: Prefs
private let key = "timestamp"
init(prefs: Prefs) {
self.prefs = prefs
}
var serverBackoffUntilLocalTimestamp: Timestamp? {
get {
return self.prefs.unsignedLongForKey(self.key)
}
set(value) {
if let value = value {
self.prefs.setLong(value, forKey: self.key)
} else {
self.prefs.removeObjectForKey(self.key)
}
}
}
func clearServerBackoff() {
self.prefs.removeObjectForKey(self.key)
}
func isInBackoff(now: Timestamp) -> Timestamp? {
if let ts = self.serverBackoffUntilLocalTimestamp where now < ts {
return ts
}
return nil
}
}
/**
* The scratchpad consists of the following:
*
* 1. Cached records. We cache meta/global and crypto/keys until they change.
* 2. Metadata like timestamps, both for cached records and for server fetches.
* 3. User preferences -- engine enablement.
* 4. Client record state.
* 5. Local commands that have yet to be processed.
*
* Note that the scratchpad itself is immutable, but is a class passed by reference.
* Its mutable fields can be mutated, but you can't accidentally e.g., switch out
* meta/global and get confused.
*
* TODO: the Scratchpad needs to be loaded from persistent storage, and written
* back at certain points in the state machine (after a replayable action is taken).
*/
public class Scratchpad {
public class Builder {
var syncKeyBundle: KeyBundle // For the love of god, if you change this, invalidate keys, too!
private var global: Fetched<MetaGlobal>?
private var keys: Fetched<Keys>?
private var keyLabel: String
var localCommands: Set<LocalCommand>
var engineConfiguration: EngineConfiguration?
var clientGUID: String
var clientName: String
var prefs: Prefs
init(p: Scratchpad) {
self.syncKeyBundle = p.syncKeyBundle
self.prefs = p.prefs
self.global = p.global
self.keys = p.keys
self.keyLabel = p.keyLabel
self.localCommands = p.localCommands
self.engineConfiguration = p.engineConfiguration
self.clientGUID = p.clientGUID
self.clientName = p.clientName
}
public func clearLocalCommands() -> Builder {
self.localCommands.removeAll()
return self
}
public func addLocalCommandsFromKeys(keys: Fetched<Keys>?) -> Builder {
// Getting new keys can force local collection resets.
guard let freshKeys = keys?.value, staleKeys = self.keys?.value where staleKeys.valid else {
// Removing keys, or new keys and either we didn't have old keys or they weren't valid. Everybody gets a reset!
self.localCommands.insert(LocalCommand.ResetAllEngines(except: []))
return self
}
// New keys, and we have valid old keys.
if freshKeys.defaultBundle != staleKeys.defaultBundle {
// Default bundle has changed. Reset everything but collections that have unchanged bulk keys.
var except: Set<String> = Set()
// Symmetric difference, like an animal. Swift doesn't allow Hashable tuples; don't fight it.
for (collection, keyBundle) in staleKeys.collectionKeys {
if keyBundle == freshKeys.forCollection(collection) {
except.insert(collection)
}
}
for (collection, keyBundle) in freshKeys.collectionKeys {
if keyBundle == staleKeys.forCollection(collection) {
except.insert(collection)
}
}
self.localCommands.insert(.ResetAllEngines(except: except))
} else {
// Default bundle is the same. Reset collections that have changed bulk keys.
for (collection, keyBundle) in staleKeys.collectionKeys {
if keyBundle != freshKeys.forCollection(collection) {
self.localCommands.insert(.ResetEngine(engine: collection))
}
}
for (collection, keyBundle) in freshKeys.collectionKeys {
if keyBundle != staleKeys.forCollection(collection) {
self.localCommands.insert(.ResetEngine(engine: collection))
}
}
}
return self
}
public func setKeys(keys: Fetched<Keys>?) -> Builder {
self.keys = keys
return self
}
public func setGlobal(global: Fetched<MetaGlobal>?) -> Builder {
self.global = global
if let global = global {
// We always take the incoming meta/global's engine configuration.
self.engineConfiguration = global.value.engineConfiguration()
}
return self
}
public func setEngineConfiguration(engineConfiguration: EngineConfiguration?) -> Builder {
self.engineConfiguration = engineConfiguration
return self
}
public func build() -> Scratchpad {
return Scratchpad(
b: self.syncKeyBundle,
m: self.global,
k: self.keys,
keyLabel: self.keyLabel,
localCommands: self.localCommands,
engines: self.engineConfiguration,
clientGUID: self.clientGUID,
clientName: self.clientName,
persistingTo: self.prefs
)
}
}
public lazy var backoffStorage: BackoffStorage = {
return PrefsBackoffStorage(prefs: self.prefs.branch("backoff.storage"))
}()
public func evolve() -> Scratchpad.Builder {
return Scratchpad.Builder(p: self)
}
// This is never persisted.
let syncKeyBundle: KeyBundle
// Cached records.
// This cached meta/global is what we use to add or remove enabled engines. See also
// engineConfiguration, below.
// We also use it to detect when meta/global hasn't changed -- compare timestamps.
//
// Note that a Scratchpad held by a Ready state will have the current server meta/global
// here. That means we don't need to track syncIDs separately (which is how desktop and
// Android are implemented).
// If we don't have a meta/global, and thus we don't know syncIDs, it means we haven't
// synced with this server before, and we'll do a fresh sync.
let global: Fetched<MetaGlobal>?
// We don't store these keys (so-called "collection keys" or "bulk keys") in Prefs.
// Instead, we store a label, which is seeded when you first create a Scratchpad.
// This label is used to retrieve the real keys from your Keychain.
//
// Note that we also don't store the syncKeyBundle here. That's always created from kB,
// provided by the Firefox Account.
//
// Why don't we derive the label from your Sync Key? Firstly, we'd like to be able to
// clean up without having your key. Secondly, we don't want to accidentally load keys
// from the Keychain just because the Sync Key is the same -- e.g., after a node
// reassignment. Randomly generating a label offers all of the benefits with none of the
// problems, with only the cost of persisting that label alongside the rest of the state.
let keys: Fetched<Keys>?
let keyLabel: String
// Local commands.
var localCommands: Set<LocalCommand>
// Enablement states.
let engineConfiguration: EngineConfiguration?
// What's our client name?
let clientName: String
let clientGUID: String
// Where do we persist when told?
let prefs: Prefs
init(b: KeyBundle,
m: Fetched<MetaGlobal>?,
k: Fetched<Keys>?,
keyLabel: String,
localCommands: Set<LocalCommand>,
engines: EngineConfiguration?,
clientGUID: String,
clientName: String,
persistingTo prefs: Prefs
) {
self.syncKeyBundle = b
self.prefs = prefs
self.keys = k
self.keyLabel = keyLabel
self.global = m
self.engineConfiguration = engines
self.localCommands = localCommands
self.clientGUID = clientGUID
self.clientName = clientName
}
// This should never be used in the end; we'll unpickle instead.
// This should be a convenience initializer, but... Swift compiler bug?
init(b: KeyBundle, persistingTo prefs: Prefs) {
self.syncKeyBundle = b
self.prefs = prefs
self.keys = nil
self.keyLabel = Bytes.generateGUID()
self.global = nil
self.engineConfiguration = nil
self.localCommands = Set()
self.clientGUID = Bytes.generateGUID()
self.clientName = DeviceInfo.defaultClientName()
}
func freshStartWithGlobal(global: Fetched<MetaGlobal>) -> Scratchpad {
// TODO: I *think* a new keyLabel is unnecessary.
return self.evolve()
.setGlobal(global)
.addLocalCommandsFromKeys(nil)
.setKeys(nil)
.build()
}
private class func unpickleV1FromPrefs(prefs: Prefs, syncKeyBundle: KeyBundle) -> Scratchpad {
let b = Scratchpad(b: syncKeyBundle, persistingTo: prefs).evolve()
if let mg = prefs.stringForKey(PrefGlobal) {
if let mgTS = prefs.unsignedLongForKey(PrefGlobalTS) {
if let global = MetaGlobal.fromJSON(JSON.parse(mg)) {
b.setGlobal(Fetched(value: global, timestamp: mgTS))
} else {
log.error("Malformed meta/global in prefs. Ignoring.")
}
} else {
// This should never happen.
log.error("Found global in prefs, but not globalTS!")
}
}
if let keyLabel = prefs.stringForKey(PrefKeyLabel) {
b.keyLabel = keyLabel
if let ckTS = prefs.unsignedLongForKey(PrefKeysTS) {
if let keys = KeychainWrapper.defaultKeychainWrapper().stringForKey("keys." + keyLabel) {
// We serialize as JSON.
let keys = Keys(payload: KeysPayload(keys))
if keys.valid {
log.debug("Read keys from Keychain with label \(keyLabel).")
b.setKeys(Fetched(value: keys, timestamp: ckTS))
} else {
log.error("Invalid keys extracted from Keychain. Discarding.")
}
} else {
log.error("Found keysTS in prefs, but didn't find keys in Keychain!")
}
}
}
b.clientGUID = prefs.stringForKey(PrefClientGUID) ?? {
log.error("No value found in prefs for client GUID! Generating one.")
return Bytes.generateGUID()
}()
b.clientName = prefs.stringForKey(PrefClientName) ?? {
log.error("No value found in prefs for client name! Using default.")
return DeviceInfo.defaultClientName()
}()
if let localCommands: [String] = prefs.stringArrayForKey(PrefLocalCommands) {
b.localCommands = Set(localCommands.flatMap({LocalCommand.fromJSON(JSON.parse($0))}))
}
if let engineConfigurationString = prefs.stringForKey(PrefEngineConfiguration) {
if let engineConfiguration = EngineConfiguration.fromJSON(JSON.parse(engineConfigurationString)) {
b.engineConfiguration = engineConfiguration
} else {
log.error("Invalid engineConfiguration found in prefs. Discarding.")
}
}
return b.build()
}
/**
* Remove anything that might be left around after prefs is wiped.
*/
public class func clearFromPrefs(prefs: Prefs) {
if let keyLabel = prefs.stringForKey(PrefKeyLabel) {
log.debug("Removing saved key from keychain.")
KeychainWrapper.defaultKeychainWrapper().removeObjectForKey(keyLabel)
} else {
log.debug("No key label; nothing to remove from keychain.")
}
}
public class func restoreFromPrefs(prefs: Prefs, syncKeyBundle: KeyBundle) -> Scratchpad? {
if let ver = prefs.intForKey(PrefVersion) {
switch (ver) {
case 1:
return unpickleV1FromPrefs(prefs, syncKeyBundle: syncKeyBundle)
default:
return nil
}
}
log.debug("No scratchpad found in prefs.")
return nil
}
/**
* Persist our current state to our origin prefs.
* Note that calling this from multiple threads with either mutated or evolved
* scratchpads will cause sadness — individual writes are thread-safe, but the
* overall pseudo-transaction is not atomic.
*/
public func checkpoint() -> Scratchpad {
return pickle(self.prefs)
}
func pickle(prefs: Prefs) -> Scratchpad {
prefs.setInt(1, forKey: PrefVersion)
if let global = global {
prefs.setLong(global.timestamp, forKey: PrefGlobalTS)
prefs.setString(global.value.asPayload().toString(), forKey: PrefGlobal)
} else {
prefs.removeObjectForKey(PrefGlobal)
prefs.removeObjectForKey(PrefGlobalTS)
}
// We store the meat of your keys in the Keychain, using a random identifier that we persist in prefs.
prefs.setString(self.keyLabel, forKey: PrefKeyLabel)
if let keys = self.keys {
let payload = keys.value.asPayload().toString(false)
let label = "keys." + self.keyLabel
log.debug("Storing keys in Keychain with label \(label).")
prefs.setString(self.keyLabel, forKey: PrefKeyLabel)
prefs.setLong(keys.timestamp, forKey: PrefKeysTS)
// TODO: I could have sworn that we could specify kSecAttrAccessibleAfterFirstUnlock here.
KeychainWrapper.defaultKeychainWrapper().setString(payload, forKey: label)
} else {
log.debug("Removing keys from Keychain.")
KeychainWrapper.defaultKeychainWrapper().removeObjectForKey(self.keyLabel)
}
prefs.setString(clientName, forKey: PrefClientName)
prefs.setString(clientGUID, forKey: PrefClientGUID)
let localCommands: [String] = Array(self.localCommands).map({$0.toJSON().toString()})
prefs.setObject(localCommands, forKey: PrefLocalCommands)
if let engineConfiguration = self.engineConfiguration {
prefs.setString(engineConfiguration.toJSON().toString(), forKey: PrefEngineConfiguration)
} else {
prefs.removeObjectForKey(PrefEngineConfiguration)
}
return self
}
}
|
mpl-2.0
|
ddff0e41202ee7e48ae3b1d43cad16dc
| 36.332068 | 128 | 0.611924 | 4.896466 | false | true | false | false |
zhangjk4859/animal-plant_pool
|
animal-plant_pool/animal-plant_pool/日记/Controller/DairyVC.swift
|
1
|
5653
|
//
// DairyVC.swift
// animal-plant_pool
//
// Created by 张俊凯 on 2017/2/10.
// Copyright © 2017年 张俊凯. All rights reserved.
//
import UIKit
class DairyVC: UIViewController {
//图片背景
var weatherView:UIImageView?
//点击波纹图片
var rippView:UIView?
//宠物和植物日记本图标
var apView:AnimalPlantView?
override func viewDidLoad() {
super.viewDidLoad()
//设置基础视图
setBasicFeathers()
//设置天气图片
weatherView = setWeatherView(imageName:"weather_sun_day_small")
var viewFrame = weatherView?.frame
viewFrame?.size.width -= 60
viewFrame?.origin.x += 30
weatherView?.frame = viewFrame!
let height = weatherView?.frame.height
weatherView?.layer.cornerRadius = height! * 0.5
weatherView?.layer.masksToBounds = true
view.addSubview(weatherView!);
//放动物和植物标签,一个view包裹两个imageView
apView = AnimalPlantView(frame: CGRect(x: 0, y: (weatherView?.frame)!.maxY , width: view.width, height: 130))
view.addSubview(apView!)
}
//点击图片效果
func tapView(_ tap: UITapGestureRecognizer){
//产生波纹
circleAffect(tap: tap)
//动画放大原理分两步
//第一,取消圆形切割,放大宽度
UIView.animate(withDuration: 1, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
var viewFrame = self.weatherView?.frame
viewFrame?.size.width = UIScreen.main.bounds.width
viewFrame?.origin.x = 0
self.weatherView?.frame = viewFrame!
self.weatherView?.layer.cornerRadius = 0
self.weatherView?.layer.masksToBounds = false
}) { (Bool) in // 第一次动画完成后
//更换大图片,往下挪
self.weatherView = self.setWeatherView(imageName: "weather_sun_day_big")
var viewFrame = self.weatherView?.frame
viewFrame?.origin.y = (viewFrame?.origin.y)! - (UIScreen.main.bounds.height * 0.5 - (viewFrame?.size.height)!)
viewFrame?.size = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 0.5)
self.weatherView?.frame = viewFrame!
//动画开始往下挪
UIView.animate(withDuration: 2, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
viewFrame?.origin.y = 64
self.weatherView?.frame = viewFrame!
self.apView?.y = (self.weatherView?.frame)!.maxY
}) { (Bool) in
}
}
}
//设置天气图片
private func setWeatherView(imageName:String)->UIImageView{
if weatherView == nil {
weatherView = UIImageView(image: UIImage(named:imageName))
//往下挪
weatherView?.frame.origin.y += 64
let tap = UITapGestureRecognizer(target: self, action:#selector(self.tapView(_:)))
weatherView?.addGestureRecognizer(tap)
weatherView?.isUserInteractionEnabled = true
}else{
weatherView?.image = UIImage(named: imageName)
}
return weatherView!
}
//产生波纹的动画效果
private func circleAffect(tap: UITapGestureRecognizer){
let locationPoint = tap.location(in:weatherView)
weatherView?.addSubview(rippView!)
rippView?.center = locationPoint
rippView?.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
UIView.animate(withDuration: 0.1, animations: {
self.rippView?.alpha = 0.5
})
UIView.animate(withDuration: 0.4, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
self.rippView?.transform = CGAffineTransform(scaleX: 1,y: 1);
self.rippView?.alpha=0;
}) { (Bool) in
self.rippView?.removeFromSuperview()
}
}
//设置基础视图
private func setBasicFeathers(){
//设置波纹图片
rippView = UIView()
rippView?.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
rippView?.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.3)
rippView?.layer.cornerRadius = 100
rippView?.layer.masksToBounds = true
//设置导航栏右边图标
let img = UIImage(named: "release")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
let item = UIBarButtonItem(image: img, style: UIBarButtonItemStyle.plain, target: self, action: nil)
self.navigationItem.rightBarButtonItem = item
//设置背景为白色
view.backgroundColor = RGBA(r: 210, g: 210, b: 210, a: 1.0)
}
//备用代码
private func test(){
// //图片本身旋转
// let rotation = CGAffineTransform(rotationAngle: CGFloat(M_PI))
// if self.weatherView?.transform == rotation{
//
// UIView.animate(withDuration: 1, animations: {
// self.weatherView?.transform = CGAffineTransform.identity
// })
// }else{
// UIView.animate(withDuration: 1, animations: {
// self.weatherView?.transform = rotation
// })
// }
}
}
|
mit
|
18c15fed2150269050a66daf574c3173
| 34.453333 | 126 | 0.568447 | 4.278359 | false | false | false | false |
Maturelittleman/ImitateQQMusicDemo
|
QQMusic/QQMusic/Classes/Other/Category/UIView+Extension.swift
|
1
|
2334
|
//
// UIView+Extension.swift
// QQZone
//
// Created by 王顺子 on 16/3/29.
// Copyright © 2016年 小码哥. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
public var x: CGFloat{
get{
return self.frame.origin.x
}
set{
var r = self.frame
r.origin.x = newValue
self.frame = r
}
}
public var y: CGFloat{
get{
return self.frame.origin.y
}
set{
var r = self.frame
r.origin.y = newValue
self.frame = r
}
}
/// 右边界的x值
public var rightX: CGFloat{
get{
return self.x + self.width
}
set{
var r = self.frame
r.origin.x = newValue - frame.size.width
self.frame = r
}
}
/// 下边界的y值
public var bottomY: CGFloat{
get{
return self.y + self.height
}
set{
var r = self.frame
r.origin.y = newValue - frame.size.height
self.frame = r
}
}
public var centerX : CGFloat{
get{
return self.center.x
}
set{
self.center = CGPoint(x: newValue, y: self.center.y)
}
}
public var centerY : CGFloat{
get{
return self.center.y
}
set{
self.center = CGPoint(x: self.center.x, y: newValue)
}
}
public var width: CGFloat{
get{
return self.frame.size.width
}
set{
var r = self.frame
r.size.width = newValue
self.frame = r
}
}
public var height: CGFloat{
get{
return self.frame.size.height
}
set{
var r = self.frame
r.size.height = newValue
self.frame = r
}
}
public var origin: CGPoint{
get{
return self.frame.origin
}
set{
self.x = newValue.x
self.y = newValue.y
}
}
public var size: CGSize{
get{
return self.frame.size
}
set{
self.width = newValue.width
self.height = newValue.height
}
}
}
|
apache-2.0
|
8ab6a136eb8966c5bfe4339a0f8bb0c6
| 18.491525 | 64 | 0.447151 | 4.112701 | false | false | false | false |
nmdias/FeedKit
|
Example iOS/Extensions/FeedTableViewController + TableViewLayout.swift
|
1
|
1776
|
//
// FeedTableViewController + TableViewLayout.swift
//
// Copyright (c) 2016 - 2018 Nuno Manuel Dias
//
// 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 FeedTableViewController {
enum TableViewLayout {
case title, link, description, date, items
init?(indexPath: IndexPath) {
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: self = .title
case 1: self = .link
case 2: self = .description
case 3: self = .date
default: return nil
}
case 1: self = .items
default: return nil
}
}
}
}
|
mit
|
a352f85377d5a2e691f5b376befd6780
| 38.466667 | 82 | 0.661036 | 4.637076 | false | false | false | false |
apple/swift-corelibs-foundation
|
Sources/Foundation/NotificationQueue.swift
|
1
|
7400
|
// 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
//
@_implementationOnly import CoreFoundation
extension NotificationQueue {
public enum PostingStyle : UInt {
case whenIdle = 1
case asap = 2
case now = 3
}
public struct NotificationCoalescing : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let none = NotificationCoalescing([])
public static let onName = NotificationCoalescing(rawValue: 1 << 0)
public static let onSender = NotificationCoalescing(rawValue: 1 << 1)
}
}
open class NotificationQueue: NSObject {
internal typealias NotificationQueueList = NSMutableArray
internal typealias NSNotificationListEntry = (Notification, [RunLoop.Mode]) // Notification ans list of modes the notification may be posted in.
internal typealias NSNotificationList = [NSNotificationListEntry] // The list of notifications to post
internal let notificationCenter: NotificationCenter
internal var asapList = NSNotificationList()
internal var idleList = NSNotificationList()
internal final lazy var idleRunloopObserver: CFRunLoopObserver = {
return CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, CFOptionFlags(kCFRunLoopBeforeTimers), true, 0) {[weak self] observer, activity in
self!.notifyQueues(.whenIdle)
}
}()
internal final lazy var asapRunloopObserver: CFRunLoopObserver = {
return CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, CFOptionFlags(kCFRunLoopBeforeWaiting | kCFRunLoopExit), true, 0) {[weak self] observer, activity in
self!.notifyQueues(.asap)
}
}()
// The NSNotificationQueue instance is associated with current thread.
// The _notificationQueueList represents a list of notification queues related to the current thread.
private static var _notificationQueueList = NSThreadSpecific<NSMutableArray>()
internal static var notificationQueueList: NotificationQueueList {
return _notificationQueueList.get() {
return NSMutableArray()
}
}
// The default notification queue for the current thread.
private static var _defaultQueue = NSThreadSpecific<NotificationQueue>()
open class var `default`: NotificationQueue {
return _defaultQueue.get() {
return NotificationQueue(notificationCenter: NotificationCenter.default)
}
}
public init(notificationCenter: NotificationCenter) {
self.notificationCenter = notificationCenter
super.init()
NotificationQueue.registerQueue(self)
}
deinit {
NotificationQueue.unregisterQueue(self)
removeRunloopObserver(self.idleRunloopObserver)
removeRunloopObserver(self.asapRunloopObserver)
}
open func enqueue(_ notification: Notification, postingStyle: PostingStyle) {
enqueue(notification, postingStyle: postingStyle, coalesceMask: [.onName, .onSender], forModes: nil)
}
open func enqueue(_ notification: Notification, postingStyle: PostingStyle, coalesceMask: NotificationCoalescing, forModes modes: [RunLoop.Mode]?) {
var runloopModes: [RunLoop.Mode] = [.default]
if let modes = modes {
runloopModes = modes
}
if !coalesceMask.isEmpty {
self.dequeueNotifications(matching: notification, coalesceMask: coalesceMask)
}
switch postingStyle {
case .now:
let currentMode = RunLoop.current.currentMode
if currentMode == nil || runloopModes.contains(currentMode!) {
self.notificationCenter.post(notification)
}
case .asap: // post at the end of the current notification callout or timer
addRunloopObserver(self.asapRunloopObserver)
self.asapList.append((notification, runloopModes))
case .whenIdle: // wait until the runloop is idle, then post the notification
addRunloopObserver(self.idleRunloopObserver)
self.idleList.append((notification, runloopModes))
}
}
open func dequeueNotifications(matching notification: Notification, coalesceMask: NotificationCoalescing) {
var predicate: (NSNotificationListEntry) -> Bool
switch coalesceMask {
case [.onName, .onSender]:
predicate = { entry in
return __SwiftValue.store(notification.object) !== __SwiftValue.store(entry.0.object) || notification.name != entry.0.name
}
case [.onName]:
predicate = { entry in
return notification.name != entry.0.name
}
case [.onSender]:
predicate = { entry in
return __SwiftValue.store(notification.object) !== __SwiftValue.store(entry.0.object)
}
default:
return
}
self.asapList = self.asapList.filter(predicate)
self.idleList = self.idleList.filter(predicate)
}
// MARK: Private
private final func addRunloopObserver(_ observer: CFRunLoopObserver) {
CFRunLoopAddObserver(RunLoop.current._cfRunLoop, observer, kCFRunLoopDefaultMode)
CFRunLoopAddObserver(RunLoop.current._cfRunLoop, observer, kCFRunLoopCommonModes)
}
private final func removeRunloopObserver(_ observer: CFRunLoopObserver) {
CFRunLoopRemoveObserver(RunLoop.current._cfRunLoop, observer, kCFRunLoopDefaultMode)
CFRunLoopRemoveObserver(RunLoop.current._cfRunLoop, observer, kCFRunLoopCommonModes)
}
private func notify(_ currentMode: RunLoop.Mode?, notificationList: inout NSNotificationList) {
for (idx, (notification, modes)) in notificationList.enumerated().reversed() {
if currentMode == nil || modes.contains(currentMode!) {
self.notificationCenter.post(notification)
notificationList.remove(at: idx)
}
}
}
/**
Gets queues from the notificationQueueList and posts all notification from the list related to the postingStyle parameter.
*/
private func notifyQueues(_ postingStyle: PostingStyle) {
let currentMode = RunLoop.current.currentMode
for queue in NotificationQueue.notificationQueueList {
let notificationQueue = queue as! NotificationQueue
if postingStyle == .whenIdle {
notificationQueue.notify(currentMode, notificationList: ¬ificationQueue.idleList)
} else {
notificationQueue.notify(currentMode, notificationList: ¬ificationQueue.asapList)
}
}
}
private static func registerQueue(_ notificationQueue: NotificationQueue) {
self.notificationQueueList.add(notificationQueue)
}
private static func unregisterQueue(_ notificationQueue: NotificationQueue) {
guard self.notificationQueueList.index(of: notificationQueue) != NSNotFound else {
return
}
self.notificationQueueList.remove(notificationQueue)
}
}
|
apache-2.0
|
651dfcb6ee1b1d86fce11f1e5d32595d
| 40.573034 | 171 | 0.685541 | 5.473373 | false | false | false | false |
endoze/BaseTask
|
BaseTask/BaseTask.swift
|
1
|
6003
|
//
// BaseTask.swift
// BaseTask
//
// Created by Endoze on 4/20/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
/**
Enum representing the different types of HTTP methods.
*/
@objc public enum HTTPMethod: Int {
/**
* HTTP Get
*/
case Get
/**
* HTTP Post
*/
case Post
/**
* HTTP Put
*/
case Put
/**
* HTTP Patch
*/
case Patch
/**
* HTTP Delete
*/
case Delete
}
/**
* Protocol that describes an object that can parse a dictionary into the correct format for an http request body.
*/
@objc public protocol BodyParseable {
/**
This method accepts a dictionary and returns NSData or nil. The return of this method is used as the http requests body.
- parameter bodyDictionary: Dictionary containing values being sent in the body of an http request.
- returns: NSData or nil.
*/
func parsedBody(bodyDictionary: [String: AnyObject]?) -> NSData?
}
/**
* Protocol that describes an object that can parse a response from an http request into another form. Objects that implment this protocol can be chained together to do multistep processing of values returned from an http request.
*/
@objc public protocol ResponseParseable {
/**
This method accepts an object and returns another object or nil. An example could be transforming NSData into an NSDictionary.
- parameter data: Data from the http response or from another ResponseParseable.
- returns: Returns an object or nil.
*/
func parsedObject(data: AnyObject?) -> AnyObject?
}
/// BaseTask is a class designed to be subclassed. It helps in defining an API interface to a web service.
public class BaseTask: NSObject {
/// Closure that captures what to do when an http request completes and a response sent back.
public typealias CompletionHandler = (parsedObject: AnyObject?, response: NSURLResponse?, error: NSError?) -> Void
/// Closure that captures logic on how to validate an http response sent back from a server.
public typealias ValidationHandler = (response: NSURLResponse, data: NSData?, error: NSErrorPointer) -> Bool
/// The session to use when making requests.
public var session: NSURLSession
/// The default body parser to use when sending requests.
public var defaultBodyParser: BodyParseable = BodyParser()
/// The default chain of response parsers to use when parsing an http response body.
public var defaultResponseParsers: [ResponseParseable] = []
/// The closure to use when validating http response bodies.
public var validationHandler: ValidationHandler = { response, data, error in
return true
}
/**
This is the default initializer for BaseTask. It defaults to using a session created from the standard shared session configuration.
- parameter session: NSURLSession to use when making requests. Defaults to using a session created from the standard shared session configuration.
- returns: An instance of BaseTask.
*/
public init(session: NSURLSession = NSURLSession(configuration: NSURLSession.sharedSession().configuration)) {
self.session = session
}
/**
This is the workhorse method that creates new instances of NSURLSessionDataTask created based on the parameters passed in.
- parameter url: URL that you are sending your requests to.
- parameter bodyDictionary: Dictionary representing the data sent in the http request body.
- parameter httpMethod: HTTP method to use when making the request.
- parameter httpHeaders: HTTP headers to use when making the request.
- parameter bodyParser: Body parser to use when parsing the bodyDictionary.
- parameter responseParsers: Chain of response parsers to use when parsing an http response body.
- parameter dispatchQueue: Dispatch queue to run the completion handler on.
- parameter completion: Closure that captures logic to execute after completion of the request/response cycle.
- returns: Returns a ready to go NSURLSessionDataTask configured based on the parameters passed in. Calling resume on it starts your request.
*/
public func makeHTTPRequest(url: NSURL,
bodyDictionary: [String: AnyObject]?,
httpMethod: HTTPMethod,
httpHeaders: [HTTPHeader]?,
bodyParser: BodyParseable?,
responseParsers: [ResponseParseable]?,
dispatchQueue: dispatch_queue_t = dispatch_get_main_queue(),
completion: CompletionHandler) -> NSURLSessionDataTask {
let request: NSURLRequest
let bodyData: NSData?
let bodyParserToUse = bodyParser ?? defaultBodyParser
let responseParsersToUse = responseParsers ?? defaultResponseParsers
if let bodyDictionary = bodyDictionary {
bodyData = bodyParserToUse.parsedBody(bodyDictionary)
} else {
bodyData = nil
}
switch httpMethod {
case .Get: request = NSURLRequest.getRequest(url, headers: httpHeaders)
case .Put: request = NSURLRequest.putRequest(url, body: bodyData, headers: httpHeaders)
case .Patch: request = NSURLRequest.patchRequest(url, body: bodyData, headers: httpHeaders)
case .Delete: request = NSURLRequest.deleteRequest(url, headers: httpHeaders)
case .Post: request = NSURLRequest.postRequest(url, body: bodyData, headers: httpHeaders)
}
return session.dataTaskWithRequest(request, completionHandler: { data, response, error in
var parsedObject: AnyObject?
var internalError: NSError? = error
if let response = response, data = data {
if internalError == nil {
let isValidated = self.validationHandler(response: response, data: data, error: &internalError)
if internalError == nil && isValidated {
parsedObject = responseParsersToUse.reduce(data as AnyObject) { $1.parsedObject($0) }
}
}
}
dispatch_async(dispatchQueue, { () -> Void in
completion(parsedObject: parsedObject, response: response, error: internalError)
})
})
}
}
|
mit
|
ec84369aacccc6d1cff084e8e101e9dc
| 35.603659 | 231 | 0.717094 | 4.778662 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.