repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
parrotbait/CorkWeather | Pods/SWLogger/SWLogger/Log.swift | 1 | 4762 | //
// Logger.swift
// Cork Weather
//
// Created by Eddie Long on 07/09/2017.
// Copyright © 2017 eddielong. All rights reserved.
//
import Foundation
public class Log {
typealias LogHandlers = [LogHandler]
#if DEBUG
private static var logLevel : LogLevel = .debug
#else
private static var logLevel : LogLevel = .warning
#endif
private static var tagFilters = [String]()
private static var logHandlers = LogHandlers()
public static var enableDefaultLogHandler = true
private static let defaultLogHandler = DefaultLogHandler()
public class func setLevel(_ level : LogLevel) {
logLevel = level;
}
public class func getLevel() -> LogLevel {
return logLevel
}
public class func setTagFilters(tags : [String]) {
tagFilters = tags;
}
public class func addHandler(_ handler : LogHandler) {
logHandlers.append(handler)
}
public class func removeHandler(_ handler : LogHandler) {
logHandlers = logHandlers.filter() { $0 !== handler }
}
public class func hasHandler(_ handler : LogHandler) -> Bool {
return !logHandlers.filter() { $0 === handler }.isEmpty
}
public class func log(message: String,
level: LogLevel = .debug,
tag: String = "",
extra : Any = NSNull.init(),
fileName: String = #file,
line: Int = #line,
column: Int = #column,
funcName: String = #function) {
// Check log level
if level.rawValue < logLevel.rawValue {
return;
}
// Check filters
if !tagFilters.isEmpty {
// Ignore empty tags
if tag.isEmpty {
return
}
// Ignore tags not being asked for
if !tagFilters.contains(tag) {
return
}
}
let line = LogLine.init(message: message, filename: fileName, funcName: funcName, line: line, column: column, extra: extra)
if enableDefaultLogHandler {
defaultLogHandler.logMessage(log: line, tag: tag, level: level)
}
// Now pass onto the handlers
for handler in logHandlers {
handler.logMessage(log: line, tag: tag, level: level)
}
}
// Verbose
public class func v(_ message: String,
_ tag: String = "",
extra : Any = NSNull.init(),
fileName: String = #file,
line: Int = #line,
column: Int = #column,
funcName: String = #function) {
Log.log(message: message, level: .verbose, tag: tag, extra: extra, fileName: fileName, line: line, column: column, funcName: funcName)
}
// Debug
public class func d(_ message: String,
_ tag: String = "",
extra : Any = NSNull.init(),
fileName: String = #file,
line: Int = #line,
column: Int = #column,
funcName: String = #function) {
Log.log(message: message, level: .debug, tag: tag, extra: extra, fileName: fileName, line: line, column: column, funcName: funcName)
}
// Info
public class func i(_ message: String,
_ tag: String = "",
extra : Any = NSNull.init(),
fileName: String = #file,
line: Int = #line,
column: Int = #column,
funcName: String = #function) {
Log.log(message: message, level: .info, tag: tag, extra: extra, fileName: fileName, line: line, column: column, funcName: funcName)
}
// Warning
public class func w(_ message: String,
_ tag: String = "",
extra : Any = NSNull.init(),
fileName: String = #file,
line: Int = #line,
column: Int = #column,
funcName: String = #function) {
Log.log(message: message, level: .warning, tag: tag, extra: extra, fileName: fileName, line: line, column: column, funcName: funcName)
}
// Error
public class func e(_ message: String,
_ tag: String = "",
extra : Any = NSNull.init(),
fileName: String = #file,
line: Int = #line,
column: Int = #column,
funcName: String = #function) {
Log.log(message: message, level: .error, tag: tag, extra: extra, fileName: fileName, line: line, column: column, funcName: funcName)
}
}
| mit | 906ef1dae4209811c0f072ca808762e4 | 32.765957 | 142 | 0.520059 | 4.653959 | false | false | false | false |
stripe/stripe-ios | StripeCardScan/StripeCardScan/Source/CardScan/MLRuntime/PredictionAPI.swift | 1 | 2126 | //
// PredictionAPI.swift
// CardScan
//
// Created by Zain on 8/6/19.
//
import Foundation
struct Result {
var pickedBoxProbs: [Float]
var pickedLabels: [Int]
var pickedBoxes: [[Float]]
init() {
pickedBoxProbs = [Float]()
pickedLabels = [Int]()
pickedBoxes = [[Float]]()
}
}
struct PredictionAPI {
/// * A utitliy struct that applies non-max supression to each class
/// * picks out the remaining boxes, the class probabilities for classes
/// * that are kept and composes all the information in one place to be returned as
/// * an object.
func predictionAPI(
scores: [[Float]],
boxes: [[Float]],
probThreshold: Float,
iouThreshold: Float,
candidateSize: Int,
topK: Int
) -> Result {
var pickedBoxes: [[Float]] = [[Float]]()
var pickedLabels: [Int] = [Int]()
var pickedBoxProbs: [Float] = [Float]()
for classIndex in 1..<scores[0].count {
var probs: [Float] = [Float]()
var subsetBoxes: [[Float]] = [[Float]]()
var indicies: [Int] = [Int]()
for rowIndex in 0..<scores.count {
if scores[rowIndex][classIndex] > probThreshold {
probs.append(scores[rowIndex][classIndex])
subsetBoxes.append(boxes[rowIndex])
}
}
if probs.count == 0 {
continue
}
indicies = NMS.hardNMS(
subsetBoxes: subsetBoxes,
probs: probs,
iouThreshold: iouThreshold,
topK: topK,
candidateSize: candidateSize
)
for idx in indicies {
pickedBoxProbs.append(probs[idx])
pickedBoxes.append(subsetBoxes[idx])
pickedLabels.append(classIndex)
}
}
var result: Result = Result()
result.pickedBoxProbs = pickedBoxProbs
result.pickedLabels = pickedLabels
result.pickedBoxes = pickedBoxes
return result
}
}
| mit | 18d56b1c368e2f4b3f7f284841be2ee5 | 26.25641 | 87 | 0.531985 | 4.338776 | false | false | false | false |
luckymarmot/ThemeKit | Sources/ThemeImage.swift | 1 | 17053 | //
// ThemeImage.swift
// ThemeKit
//
// Created by Nuno Grilo on 03/10/2016.
// Copyright © 2016 Paw & Nuno Grilo. All rights reserved.
//
import Foundation
private var _cachedImages: NSCache<NSNumber, ThemeImage> = NSCache()
private var _cachedThemeImages: NSCache<NSNumber, NSImage> = NSCache()
/**
`ThemeImage` is a `NSImage` subclass that dynamically changes its colors
whenever a new theme is make current.
Theme-aware means you don't need to check any conditions when choosing which
image to draw. E.g.:
```
ThemeImage.logoImage.draw(in: bounds)
```
The drawing code will draw with different image depending on the selected
theme. Unless some drawing cache is being done, there's no need to refresh the
UI after changing the current theme.
Defining theme-aware images
---------------------------
The recommended way of adding your own dynamic images is as follows:
1. **Add a `ThemeImage` class extension** (or `TKThemeImage` category on
Objective-C) to add class methods for your images. E.g.:
In Swift:
```
extension ThemeImage {
static var logoImage: ThemeImage {
return ThemeImage.image(with: #function)
}
}
```
In Objective-C:
```
@interface TKThemeImage (Demo)
+ (TKThemeImage*)logoImage;
@end
@implementation TKThemeImage (Demo)
+ (TKThemeImage*)logoImage {
return [TKThemeImage imageWithSelector:_cmd];
}
@end
```
2. **Add Class Extensions on any `Theme` you want to support** (e.g., `LightTheme`
and `DarkTheme` - `TKLightTheme` and `TKDarkTheme` on Objective-C) to provide
instance methods for each theme image class method defined on (1). E.g.:
In Swift:
```
extension LightTheme {
var logoImage: NSImage? {
return NSImage(named: "MyLightLogo")
}
}
extension DarkTheme {
var logoImage: NSImage? {
return NSImage(contentsOfFile: "somewhere/MyDarkLogo.png")
}
}
```
In Objective-C:
```
@interface TKLightTheme (Demo) @end
@implementation TKLightTheme (Demo)
- (NSImage*)logoImage
{
return [NSImage imageNamed:@"MyLightLogo"];
}
@end
@interface TKDarkTheme (Demo) @end
@implementation TKDarkTheme (Demo)
- (NSImage*)logoImage
{
return [NSImage alloc] initWithContentsOfFile:@"somewhere/MyDarkLogo.png"];
}
@end
```
3. If supporting `UserTheme`'s, **define properties on user theme files** (`.theme`)
for each theme image class method defined on (1). E.g.:
```
displayName = Sample User Theme
identifier = com.luckymarmot.ThemeKit.SampleUserTheme
darkTheme = false
logoImage = image(named:MyLogo)
//logoImage = image(file:../some/path/MyLogo.png)
```
Fallback images
---------------
Unimplemented properties/methods on target theme class will default to
`fallbackImage`. This too, can be customized per theme.
Please check `ThemeColor` for theme-aware colors and `ThemeGradient` for theme-aware gradients.
*/
@objc(TKThemeImage)
open class ThemeImage: NSImage {
// MARK: -
// MARK: Properties
/// `ThemeImage` image selector used as theme instance method for same
/// selector or, if inexistent, as argument in the theme instance method `themeAsset(_:)`.
@objc public var themeImageSelector: Selector? {
didSet {
// recache image now and on theme change
recacheImage()
registerThemeChangeNotifications()
}
}
/// Resolved Image from current theme (dynamically changes with the current theme).
@objc public var resolvedThemeImage: NSImage = NSImage(size: NSSize.zero)
// MARK: -
// MARK: Creating Images
/// Create a new ThemeImage instance for the specified selector.
///
/// Returns an image returned by calling `selector` on current theme as an instance method or,
/// if unavailable, the result of calling `themeAsset(_:)` on the current theme.
///
/// - parameter selector: Selector for image method.
///
/// - returns: A `ThemeImage` instance for the specified selector.
@objc(imageWithSelector:)
public class func image(with selector: Selector) -> ThemeImage {
let cacheKey = CacheKey(selector: selector)
if let cachedImage = _cachedImages.object(forKey: cacheKey) {
return cachedImage
} else {
let image = ThemeImage(with: selector)
_cachedImages.setObject(image, forKey: cacheKey)
return image
}
}
/// Image for a specific theme.
///
/// - parameter theme: A `Theme` instance.
/// - parameter selector: An image selector.
///
/// - returns: Resolved image for specified selector on given theme.
@objc(imageForTheme:selector:)
public class func image(for theme: Theme, selector: Selector) -> NSImage? {
let cacheKey = CacheKey(selector: selector, theme: theme)
var image = _cachedThemeImages.object(forKey: cacheKey)
if image == nil {
// Theme provides this asset?
image = theme.themeAsset(NSStringFromSelector(selector)) as? NSImage
// Otherwise, use fallback image
if image == nil {
image = fallbackImage(for: theme, selector: selector)
}
// Cache it
if let themeImage = image {
_cachedThemeImages.setObject(themeImage, forKey: cacheKey)
}
}
return image
}
/// Current theme image, but respecting view appearance and any window
/// specific theme (if set).
///
/// If a `NSWindow.windowTheme` was set, it will be used instead.
/// Some views may be using a different appearance than the theme appearance.
/// In thoses cases, image won't be resolved using current theme, but from
/// either `lightTheme` or `darkTheme`, depending of whether view appearance
/// is light or dark, respectively.
///
/// - parameter view: A `NSView` instance.
/// - parameter selector: An image selector.
///
/// - returns: Resolved image for specified selector on given view.
@objc(imageForView:selector:)
public class func image(for view: NSView, selector: Selector) -> NSImage? {
// if a custom window theme was set, use the appropriate asset
if let windowTheme = view.window?.windowTheme {
return ThemeImage.image(for: windowTheme, selector: selector)
}
let theme = ThemeManager.shared.effectiveTheme
let viewAppearance = view.appearance
let aquaAppearance = NSAppearance(named: NSAppearance.Name.aqua)
let lightAppearance = NSAppearance(named: NSAppearance.Name.vibrantLight)
let darkAppearance = NSAppearance(named: NSAppearance.Name.vibrantDark)
// using a dark theme but control is on a light surface => use light theme instead
if theme.isDarkTheme &&
(viewAppearance == lightAppearance || viewAppearance == aquaAppearance) {
return ThemeImage.image(for: ThemeManager.lightTheme, selector: selector)
} else if theme.isLightTheme && viewAppearance == darkAppearance {
return ThemeImage.image(for: ThemeManager.darkTheme, selector: selector)
}
// otherwise, return current theme image
return ThemeImage.image(with: selector)
}
/// Returns a new `ThemeImage` for the given selector.
///
/// - parameter selector: A image selector.
///
/// - returns: A `ThemeImage` instance.
@objc convenience init(with selector: Selector) {
self.init(size: NSSize.zero)
// initialize properties
themeImageSelector = selector
// cache image
recacheImage()
// recache on theme change
registerThemeChangeNotifications()
}
deinit {
NotificationCenter.default.removeObserver(self, name: .didChangeTheme, object: nil)
}
/// Register to recache on theme changes.
@objc func registerThemeChangeNotifications() {
NotificationCenter.default.removeObserver(self, name: .didChangeTheme, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(recacheImage), name: .didChangeTheme, object: nil)
}
/// Forces dynamic color resolution into `resolvedThemeImage` and cache it.
/// You should not need to manually call this function.
@objc open func recacheImage() {
// If it is a UserTheme we actually want to discard theme cached values
if ThemeManager.shared.effectiveTheme.isUserTheme {
ThemeImage.emptyCache()
}
// Recache resolved image
if let selector = themeImageSelector,
let newImage = ThemeImage.image(for: ThemeManager.shared.effectiveTheme, selector: selector) {
resolvedThemeImage = newImage
}
}
/// Clear all caches.
/// You should not need to manually call this function.
@objc class open func emptyCache() {
_cachedImages.removeAllObjects()
_cachedThemeImages.removeAllObjects()
}
/// Fallback image for a specific theme and selector.
@objc class func fallbackImage(for theme: Theme, selector: Selector) -> NSImage? {
var fallbackImage: NSImage?
// try with theme provided `fallbackImage` method
if let themeFallbackImage = theme.fallbackImage as? NSImage {
fallbackImage = themeFallbackImage
}
// try with theme asset `fallbackImage`
if fallbackImage == nil, let themeAsset = theme.themeAsset("fallbackImage") as? NSImage {
fallbackImage = themeAsset
}
// otherwise just use default fallback image
return fallbackImage ?? theme.defaultFallbackImage
}
// MARK: - NSImage Overrides
override open var size: NSSize {
get {
return resolvedThemeImage.size
}
set {
resolvedThemeImage.size = newValue
}
}
override open func setName(_ string: NSImage.Name?) -> Bool {
return resolvedThemeImage.setName(string)
}
override open func name() -> NSImage.Name? {
return resolvedThemeImage.name()
}
override open var backgroundColor: NSColor {
get {
return resolvedThemeImage.backgroundColor
}
set {
resolvedThemeImage.backgroundColor = newValue
}
}
override open var usesEPSOnResolutionMismatch: Bool {
get {
return resolvedThemeImage.usesEPSOnResolutionMismatch
}
set {
resolvedThemeImage.usesEPSOnResolutionMismatch = newValue
}
}
override open var prefersColorMatch: Bool {
get {
return resolvedThemeImage.prefersColorMatch
}
set {
resolvedThemeImage.prefersColorMatch = newValue
}
}
override open var matchesOnMultipleResolution: Bool {
get {
return resolvedThemeImage.matchesOnMultipleResolution
}
set {
resolvedThemeImage.matchesOnMultipleResolution = newValue
}
}
override open var matchesOnlyOnBestFittingAxis: Bool {
get {
return resolvedThemeImage.matchesOnlyOnBestFittingAxis
}
set {
resolvedThemeImage.matchesOnlyOnBestFittingAxis = newValue
}
}
override open func draw(at point: NSPoint, from fromRect: NSRect, operation op: NSCompositingOperation, fraction delta: CGFloat) {
resolvedThemeImage.draw(at: point, from: fromRect, operation: op, fraction: delta)
}
override open func draw(in rect: NSRect, from fromRect: NSRect, operation op: NSCompositingOperation, fraction delta: CGFloat) {
resolvedThemeImage.draw(in: rect, from: fromRect, operation: op, fraction: delta)
}
override open func draw(in dstSpacePortionRect: NSRect, from srcSpacePortionRect: NSRect, operation op: NSCompositingOperation, fraction requestedAlpha: CGFloat, respectFlipped respectContextIsFlipped: Bool, hints: [NSImageRep.HintKey: Any]?) {
resolvedThemeImage.draw(in: dstSpacePortionRect, from: srcSpacePortionRect, operation: op, fraction: requestedAlpha, respectFlipped: respectContextIsFlipped, hints: hints)
}
override open func drawRepresentation(_ imageRep: NSImageRep, in rect: NSRect) -> Bool {
return resolvedThemeImage.drawRepresentation(imageRep, in: rect)
}
override open func draw(in rect: NSRect) {
resolvedThemeImage.draw(in: rect)
}
override open func recache() {
resolvedThemeImage.recache()
}
override open var tiffRepresentation: Data? {
return resolvedThemeImage.tiffRepresentation
}
override open func tiffRepresentation(using comp: NSBitmapImageRep.TIFFCompression, factor: Float) -> Data? {
return resolvedThemeImage.tiffRepresentation(using: comp, factor: factor)
}
override open var representations: [NSImageRep] {
return resolvedThemeImage.representations
}
override open func addRepresentations(_ imageReps: [NSImageRep]) {
resolvedThemeImage.addRepresentations(imageReps)
}
override open func addRepresentation(_ imageRep: NSImageRep) {
resolvedThemeImage.addRepresentation(imageRep)
}
override open func removeRepresentation(_ imageRep: NSImageRep) {
resolvedThemeImage.removeRepresentation(imageRep)
}
override open var isValid: Bool {
return resolvedThemeImage.isValid
}
override open func lockFocus() {
resolvedThemeImage.lockFocus()
}
override open func lockFocusFlipped(_ flipped: Bool) {
resolvedThemeImage.lockFocusFlipped(flipped)
}
override open func unlockFocus() {
resolvedThemeImage.unlockFocus()
}
override open var delegate: NSImageDelegate? {
get {
return resolvedThemeImage.delegate
}
set {
resolvedThemeImage.delegate = newValue
}
}
override open func cancelIncrementalLoad() {
resolvedThemeImage.cancelIncrementalLoad()
}
override open var cacheMode: NSImage.CacheMode {
get {
return resolvedThemeImage.cacheMode
}
set {
resolvedThemeImage.cacheMode = newValue
}
}
override open var alignmentRect: NSRect {
get {
return resolvedThemeImage.alignmentRect
}
set {
resolvedThemeImage.alignmentRect = newValue
}
}
override open var isTemplate: Bool {
get {
return resolvedThemeImage.isTemplate
}
set {
resolvedThemeImage.isTemplate = newValue
}
}
override open var accessibilityDescription: String? {
get {
return resolvedThemeImage.accessibilityDescription
}
set {
resolvedThemeImage.accessibilityDescription = newValue
}
}
override open func cgImage(forProposedRect proposedDestRect: UnsafeMutablePointer<NSRect>?, context referenceContext: NSGraphicsContext?, hints: [NSImageRep.HintKey: Any]?) -> CGImage? {
return resolvedThemeImage.cgImage(forProposedRect: proposedDestRect, context: referenceContext, hints: hints)
}
override open func bestRepresentation(for rect: NSRect, context referenceContext: NSGraphicsContext?, hints: [NSImageRep.HintKey: Any]?) -> NSImageRep? {
return resolvedThemeImage.bestRepresentation(for: rect, context: referenceContext, hints: hints)
}
override open func hitTest(_ testRectDestSpace: NSRect, withDestinationRect imageRectDestSpace: NSRect, context: NSGraphicsContext?, hints: [NSImageRep.HintKey: Any]?, flipped: Bool) -> Bool {
return resolvedThemeImage.hitTest(testRectDestSpace, withDestinationRect: imageRectDestSpace, context: context, hints: hints, flipped: flipped)
}
override open func recommendedLayerContentsScale(_ preferredContentsScale: CGFloat) -> CGFloat {
return resolvedThemeImage.recommendedLayerContentsScale(preferredContentsScale)
}
override open func layerContents(forContentsScale layerContentsScale: CGFloat) -> Any {
return resolvedThemeImage.layerContents(forContentsScale: layerContentsScale)
}
override open var capInsets: NSEdgeInsets {
get {
return resolvedThemeImage.capInsets
}
set {
resolvedThemeImage.capInsets = newValue
}
}
override open var resizingMode: NSImage.ResizingMode {
get {
return resolvedThemeImage.resizingMode
}
set {
resolvedThemeImage.resizingMode = newValue
}
}
}
| mit | 79cefda80675cb72c5de5137bb608407 | 31.356736 | 248 | 0.649719 | 4.830595 | false | false | false | false |
open-telemetry/opentelemetry-swift | Sources/OpenTelemetryApi/Trace/PropagatedSpanBuilder.swift | 1 | 2108 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
/// No-op implementation of the SpanBuilder
class PropagatedSpanBuilder: SpanBuilder {
private var tracer: Tracer
private var isRootSpan: Bool = false
private var spanContext: SpanContext?
private var spanName: String
init(tracer: Tracer, spanName: String) {
self.tracer = tracer
self.spanName = spanName
}
@discardableResult public func startSpan() -> Span {
if spanContext == nil, !isRootSpan {
spanContext = OpenTelemetry.instance.contextProvider.activeSpan?.context
}
return PropagatedSpan(name: spanName,
context: spanContext ?? SpanContext.create(traceId: TraceId.random(),
spanId: SpanId.random(),
traceFlags: TraceFlags(),
traceState: TraceState()))
}
@discardableResult public func setParent(_ parent: Span) -> Self {
spanContext = parent.context
return self
}
@discardableResult public func setParent(_ parent: SpanContext) -> Self {
spanContext = parent
return self
}
@discardableResult public func setNoParent() -> Self {
isRootSpan = true
return self
}
@discardableResult public func addLink(spanContext: SpanContext) -> Self {
return self
}
@discardableResult public func addLink(spanContext: SpanContext, attributes: [String: AttributeValue]) -> Self {
return self
}
@discardableResult public func setSpanKind(spanKind: SpanKind) -> Self {
return self
}
@discardableResult public func setStartTime(time: Date) -> Self {
return self
}
public func setAttribute(key: String, value: AttributeValue) -> Self {
return self
}
func setActive(_ active: Bool) -> Self {
return self
}
}
| apache-2.0 | 1eeb47c49ef16745af31b38a24d1a19f | 29.550725 | 116 | 0.583491 | 5.296482 | false | false | false | false |
MoralAlberto/SlackWebAPIKit | Example/Tests/Unit/Data/Interceptor/AccessTokenAdapterSpec.swift | 1 | 998 | import Quick
import Nimble
import Alamofire
@testable import SlackWebAPIKit
class AccessTokenAdapterSpec: QuickSpec {
override func spec() {
describe("\(String(describing: AccessTokenAdapter.self)) Spec") {
context("check request interceptor") {
let sut = AccessTokenAdapter(accessToken: "1234567890")
let sessionManager = SessionManager()
beforeEach {
sessionManager.adapter = sut
}
it("a token is inserted in every request") {
let url = URL(string: "https://slack.com/api/")
let request = URLRequest(url: url!)
let finalRequest = try! sessionManager.adapter!.adapt(request)
expect(finalRequest.url?.absoluteString).to(equal("https://slack.com/api/?token=1234567890"))
}
}
}
}
}
| mit | 2739f775536b047d7142370fae346583 | 33.413793 | 113 | 0.522044 | 5.768786 | false | true | false | false |
mobilabsolutions/jenkins-ios | JenkinsiOSTodayExtension/FavoriteTableViewCell.swift | 1 | 2053 | //
// FavoriteTableViewCell.swift
// JenkinsiOSTodayExtension
//
// Created by Robert on 23.08.18.
// Copyright © 2018 MobiLab Solutions. All rights reserved.
//
import UIKit
class FavoriteTableViewCell: UITableViewCell {
@IBOutlet var container: UIView!
@IBOutlet var statusImageView: UIImageView!
@IBOutlet var nameLabel: UILabel!
@IBOutlet var detailLabel: UILabel!
@IBOutlet var separator: UIView!
var favoritable: Favoratible? {
didSet {
updateUI()
}
}
override func awakeFromNib() {
super.awakeFromNib()
container.layer.cornerRadius = 5
container.backgroundColor = Constants.UI.backgroundColor.withAlphaComponent(0.1)
separator.backgroundColor = separator.backgroundColor?.withAlphaComponent(0.1)
contentView.backgroundColor = .clear
nameLabel.textColor = .black
detailLabel.textColor = Constants.UI.greyBlue
}
private func updateUI() {
guard let favoritable = favoritable
else { updateForLoading(); return }
if let job = favoritable as? Job {
nameLabel.text = job.name
detailLabel.text = job.healthReport.first?.description
if let color = job.color?.rawValue {
statusImageView.image = UIImage(named: color + "Circle")
}
} else if let build = favoritable as? Build {
nameLabel.text = build.fullDisplayName ?? build.displayName ?? "Build #\(build.number)"
if let duration = build.duration {
detailLabel.text = build.duration != nil ? "Duration: \(duration.toString())" : nil
}
if let result = build.result?.lowercased() {
statusImageView.image = UIImage(named: result + "Circle")
}
}
}
private func updateForLoading() {
nameLabel.text = "Loading..."
detailLabel.text = "Loading Favorite"
statusImageView.image = UIImage(named: "emptyCircle")
selectionStyle = .none
}
}
| mit | f0fb5cadd5c4d15589edf947cf74c6ae | 31.0625 | 99 | 0.625244 | 4.783217 | false | false | false | false |
sstepashka/CountDown-for-iOS | CountDown/CountDownTimeLabel.swift | 1 | 2653 | //
// CountDownTimeLabel.swift
// CountDown
//
// Created by Kuragin Dmitriy on 12/02/2017.
// Copyright © 2017 Kuragin Dmitriy. All rights reserved.
//
import Foundation
import UIKit
private let minimumTimeForRedraw = 0.0097
private let defaultFont = UIFont(name: "HelveticaNeue-Light", size: 400.0)
private let defaultTextColor: UIColor = .white
@IBDesignable
class CountDownTimeLabel: UIView {
fileprivate var label: UILabel! {
didSet {
guard let label = label else {
fatalError("'label' didn't loaded.")
}
self.addSubview(label)
let views = ["label": label]
let constraits = [NSLayoutConstraint]
.constraints("H:|-0-[label]-0-|", views: views)
.constraints("V:|-0-[label]-0-|", views: views)
constraits.activate()
}
}
private var prevTimeInterval: TimeInterval? = .none
override init(frame: CGRect) {
super.init(frame: frame)
defaultSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
defaultSetup()
}
func defaultSetup() {
let label = UILabel(frame: bounds)
label.translatesAutoresizingMaskIntoConstraints = false
label.font = defaultFont
label.baselineAdjustment = .alignCenters
label.textColor = defaultTextColor
label.adjustsFontSizeToFitWidth = true
label.text = .none
label.textAlignment = .center
label.minimumScaleFactor = 0.01
label.numberOfLines = 1
label.setContentCompressionResistancePriority(UILayoutPriority.defaultHigh, for: .vertical)
label.setContentCompressionResistancePriority(UILayoutPriority.defaultHigh, for: .horizontal)
self.backgroundColor = .clear
self.label = label
}
var timeInterval: TimeInterval? = .none {
didSet{
if let timeInterval = timeInterval {
// if let prevTimeInterval = prevTimeInterval {
// if abs(prevTimeInterval - timeInterval) < minimumTimeForRedraw {
// return
// }
// }
// prevTimeInterval = timeInterval
label.text = timeInterval.countDownString
} else {
label.text = .none
}
}
}
}
extension CountDownTimeLabel {
override func prepareForInterfaceBuilder() {
label.text = "29:98"
}
}
| apache-2.0 | 71a3d5c4535273583c91864f54255e8e | 27.516129 | 101 | 0.570136 | 5.261905 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift | 24 | 2861 | //
// MainScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Dispatch
#if !os(Linux)
import Foundation
#endif
/**
Abstracts work that needs to be performed on `DispatchQueue.main`. In case `schedule` methods are called from `DispatchQueue.main`, it will perform action immediately without scheduling.
This scheduler is usually used to perform UI work.
Main scheduler is a specialization of `SerialDispatchQueueScheduler`.
This scheduler is optimized for `observeOn` operator. To ensure observable sequence is subscribed on main thread using `subscribeOn`
operator please use `ConcurrentMainScheduler` because it is more optimized for that purpose.
*/
public final class MainScheduler : SerialDispatchQueueScheduler {
private let _mainQueue: DispatchQueue
let numberEnqueued = AtomicInt(0)
/// Initializes new instance of `MainScheduler`.
public init() {
self._mainQueue = DispatchQueue.main
super.init(serialQueue: self._mainQueue)
}
/// Singleton instance of `MainScheduler`
public static let instance = MainScheduler()
/// Singleton instance of `MainScheduler` that always schedules work asynchronously
/// and doesn't perform optimizations for calls scheduled from main queue.
public static let asyncInstance = SerialDispatchQueueScheduler(serialQueue: DispatchQueue.main)
/// In case this method is called on a background thread it will throw an exception.
public class func ensureExecutingOnScheduler(errorMessage: String? = nil) {
if !DispatchQueue.isMain {
rxFatalError(errorMessage ?? "Executing on background thread. Please use `MainScheduler.instance.schedule` to schedule work on main thread.")
}
}
/// In case this method is running on a background thread it will throw an exception.
public class func ensureRunningOnMainThread(errorMessage: String? = nil) {
#if !os(Linux) // isMainThread is not implemented in Linux Foundation
guard Thread.isMainThread else {
rxFatalError(errorMessage ?? "Running on background thread.")
}
#endif
}
override func scheduleInternal<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
let previousNumberEnqueued = increment(self.numberEnqueued)
if DispatchQueue.isMain && previousNumberEnqueued == 0 {
let disposable = action(state)
decrement(self.numberEnqueued)
return disposable
}
let cancel = SingleAssignmentDisposable()
self._mainQueue.async {
if !cancel.isDisposed {
_ = action(state)
}
decrement(self.numberEnqueued)
}
return cancel
}
}
| mit | 6fb7cd62bb6c7d612ff3c9f188d9a58c | 34.75 | 186 | 0.696503 | 5.238095 | false | false | false | false |
davidbutz/ChristmasFamDuels | iOS/Boat Aware/LineView.swift | 1 | 1320 | //
// LineView.swift
// Boat Aware
//
// Created by Adam Douglass on 6/28/16.
// Copyright © 2016 Thrive Engineering. All rights reserved.
//
import UIKit
class LineView : UIView {
var width : CGFloat = 2.0;
var startPosition : CGPoint?
var endPosition : CGPoint?
init(frame: CGRect, lineWidth: CGFloat, leftMargin: CGFloat, rightMargin: CGFloat) {
super.init(frame: frame);
self.opaque = false;
let yPos = width / 2.0;
self.width = lineWidth;
self.startPosition = CGPoint(x: leftMargin, y: yPos);
self.endPosition = CGPoint(x: frame.width - rightMargin, y: yPos);
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
override func drawRect(rect: CGRect) {
super.drawRect(rect);
if (startPosition != nil && endPosition != nil) {
let context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, UIColor.darkGrayColor().CGColor);
CGContextSetLineWidth(context, self.width);
CGContextMoveToPoint(context, (startPosition?.x)!, (startPosition?.y)!);
CGContextAddLineToPoint(context, (endPosition?.x)!, (endPosition?.y)!);
CGContextStrokePath(context);
}
}
}
| mit | 8962b1d1f0658202d72f44c0c1435887 | 31.170732 | 88 | 0.619409 | 4.532646 | false | false | false | false |
Workday/DrawAction | DrawAction/DrawGradient.swift | 1 | 9613 | /*
* Copyright 2016 Workday, Inc.
*
* This software is available under the MIT license.
* Please see the LICENSE.txt file in this project.
*/
import Foundation
/// Action that draws a linear or radial gradient in the current rect
final public class DrawGradient : DrawAction {
fileprivate let cgColors: [CGColor]
fileprivate let locations: [CGFloat]?
fileprivate var extendEdges: Bool = false
// Linear
fileprivate let startPoint: CGPoint
fileprivate let endPoint: CGPoint
// Radial
fileprivate let radial: Bool
fileprivate let startRadius: CGFloat
fileprivate let endRadius: CGFloat
// Cache of draw objects
fileprivate var gradientCache: CGGradient? = nil
// MARK: Linear initializers
/**
Initializes a linear DrawGradient
- parameter colors: colors to use in the gradient
- parameter startPoint: CGPoint in the unit coordinate system that specifies where the gradient starts. e.g., a point of (0.5, 0) would start the gradient at the top middle of the rect.
- parameter endPoint: CGPoint in the unit coordinate system that specifies where the gradient ends
- parameter locations: If supplied, specifies the relative location along the gradient line where the color stops occur. Must be a value from 0-1. Each location corresponds to a color in the color array. If nil, the locations are spread uniformly from 0 - 1, with the first color having a value of 0 and the last color having a value of 1
- parameter extendEdges: If true the starting and ending colors will continue to draw beyond the start and end point respectively.
*/
public init(colors: [UIColor], startPoint: CGPoint, endPoint: CGPoint, locations: [CGFloat]?, extendEdges: Bool) {
self.cgColors = DrawGradient.cgColorsFromUIColors(colors)
self.startPoint = startPoint
self.endPoint = endPoint
self.locations = locations
self.extendEdges = extendEdges
radial = false
startRadius = 0
endRadius = 0
super.init()
}
/**
Initializes a linear DrawGradient that does not extend edges
- parameter colors: colors to use in the gradient
- parameter startPoint: CGPoint in the unit coordinate system that specifies where the gradient starts. e.g., a point of (0.5, 0) would start the gradient at the top middle of the rect.
- parameter endPoint: CGPoint in the unit coordinate system that specifies where the gradient ends
- parameter locations: If supplied, specifies the relative location along the gradient line where the color stops occur. Must be a value from 0-1. Each location corresponds to a color in the color array. If nil, the locations are spread uniformly from 0 - 1, with the first color having a value of 0 and the last color having a value of 1
*/
convenience public init(colors: [UIColor], startPoint: CGPoint, endPoint: CGPoint, locations: [CGFloat]?) {
self.init(colors: colors, startPoint: startPoint, endPoint: endPoint, locations: locations, extendEdges: false)
}
/**
Initializes a linear DrawGradient that's either horizontal or vertical
- parameter colors: colors to use in the gradient
- parameter horizontal: If true, specifies a start point and end point to draw the gradient horizontally across the rect. Otherwise it will draw it vertically across the rect.
- parameter locations: If supplied, specifies the relative location along the gradient line where the color stops occur. Must be a value from 0-1. Each location corresponds to a color in the color array. If nil, the locations are spread uniformly from 0 - 1, with the first color having a value of 0 and the last color having a value of 1
*/
convenience public init(colors: [UIColor], horizontal: Bool, locations: [CGFloat]?) {
if horizontal {
self.init(colors: colors, startPoint: CGPoint(x:0, y: 0.5), endPoint: CGPoint(x:1, y: 0.5), locations: locations)
} else {
self.init(colors: colors, startPoint: CGPoint(x:0.5, y: 0), endPoint: CGPoint(x:0.5, y: 1), locations: locations)
}
}
/**
Initializes a linear DrawGradient that's either horizontal or vertical with default locations
- parameter colors: colors to use in the gradient
- parameter horizontal: If true, specifies a start point and end point to draw the gradient horizontally across the rect. Otherwise it will draw it vertically across the rect.
*/
convenience public init(colors: [UIColor], horizontal: Bool) {
self.init(colors: colors, horizontal: horizontal, locations: nil)
}
// MARK: Radial initializers
/**
Initializes a radial DrawGradient
- parameter colors: colors to use in the gradient
- parameter startRadius: CGFloat specifying at which radius the first color begins. The origin of the circle is the center of the current rect
- parameter endRadius: CGFloat specifycing at which radius the last color ends.
- parameter locations: If supplied, specifies the relative location along the gradient radii where the color stops occur. Must be a value from 0-1. Each location corresponds to a color in the color array. If nil, the locations are spread uniformly from 0 - 1, with the first color having a value of 0 and the last color having a value of 1
- parameter extendEdges: If true the starting and ending colors will continue to draw beyond the start and end point respectively.
*/
public init(colors: [UIColor], startRadius: CGFloat, endRadius: CGFloat, locations: [CGFloat]?, extendEdges: Bool) {
self.cgColors = DrawGradient.cgColorsFromUIColors(colors)
self.startRadius = startRadius
self.endRadius = endRadius
self.locations = locations
self.extendEdges = extendEdges
radial = true
startPoint = CGPoint.zero
endPoint = CGPoint.zero
super.init()
}
/**
Initializes a radial DrawGradient that does not extend edges
- parameter colors: colors to use in the gradient
- parameter startRadius: CGFloat specifying at which radius the first color begins. The origin of the circle is the center of the current rect
- parameter endRadius: CGFloat specifycing at which radius the last color ends.
- parameter locations: If supplied, specifies the relative location along the gradient radii where the color stops occur. Must be a value from 0-1. Each location corresponds to a color in the color array. If nil, the locations are spread uniformly from 0 - 1, with the first color having a value of 0 and the last color having a value of 1
*/
convenience public init(colors: [UIColor], startRadius: CGFloat, endRadius: CGFloat, locations: [CGFloat]?) {
self.init(colors: colors, startRadius: startRadius, endRadius: endRadius, locations: locations, extendEdges: false)
}
/**
Initializes a radial DrawGradient with the default locations
- parameter colors: colors to use in the gradient
- parameter startRadius: CGFloat specifying at which radius the first color begins. The origin of the circle is the center of the current rect
- parameter endRadius: CGFloat specifycing at which radius the last color ends.
*/
convenience public init(colors: [UIColor], startRadius: CGFloat, endRadius: CGFloat) {
self.init(colors: colors, startRadius: startRadius, endRadius: endRadius, locations: nil)
}
// MARK:
override func performActionInContext(_ context: DrawContext) {
if gradientCache == nil {
let colorSpace = CGColorSpaceCreateDeviceRGB()
if let locations = locations {
locations.withUnsafeBufferPointer { locationBuffer in
gradientCache = CGGradient(colorsSpace: colorSpace, colors: cgColors as CFArray, locations: locationBuffer.baseAddress)
}
} else {
gradientCache = CGGradient(colorsSpace: colorSpace, colors: cgColors as CFArray, locations: nil)
}
}
guard let gradient = gradientCache else {
assert(false, "Somehow do not have a gradient")
return
}
let rect = context.rect
let options: CGGradientDrawingOptions = extendEdges ? [.drawsBeforeStartLocation, .drawsAfterEndLocation] : []
if radial {
let center = CGPoint(x: rect.midX, y: rect.midY)
let minDimension = min(rect.width, rect.height) / 2
context.graphicsContext.drawRadialGradient(gradient, startCenter: center, startRadius: startRadius * minDimension, endCenter: center, endRadius: endRadius * minDimension, options: options)
} else {
let start = pointInRect(rect, fromNormalizedPoint: startPoint)
let end = pointInRect(rect, fromNormalizedPoint: endPoint)
context.graphicsContext.drawLinearGradient(gradient, start: start, end: end, options: options)
}
next?.performActionInContext(context)
}
// MARK: Helpers
fileprivate func pointInRect(_ rect: CGRect, fromNormalizedPoint point: CGPoint) -> CGPoint {
var newPoint = CGPoint()
newPoint.x = rect.minX + rect.width*point.x
newPoint.y = rect.minY + rect.height*point.y
return newPoint
}
// class function so we don't break the swift initializer contract
fileprivate class func cgColorsFromUIColors(_ colors: [UIColor]) -> [CGColor] {
return colors.map{ $0.cgColor }
}
}
| mit | 091a50aa9fbecf7eac99bc4eea870b35 | 50.682796 | 344 | 0.700614 | 4.892112 | false | false | false | false |
davidozhang/spycodes | Spycodes/Views/SCTimelineViewCell.swift | 1 | 491 | import UIKit
class SCTimelineViewCell: SCTableViewCell {
fileprivate static let primaryLabelExtendedLeadingSpace: CGFloat = 8
fileprivate static let primaryLabelDefaultLeadingSpace: CGFloat = 4
@IBOutlet weak var teamIndicatorView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
self.primaryLabel.numberOfLines = 2
self.primaryLabel.lineBreakMode = .byTruncatingHead
self.primaryLabel.adjustsFontSizeToFitWidth = true
}
}
| mit | c9bfe8c70009972f3f6431e1bb8c9d2c | 29.6875 | 72 | 0.747454 | 5.395604 | false | false | false | false |
Urinx/SomeCodes | Swift/swiftDemo/SpriteKit/test/test/GameScene.swift | 1 | 1308 | //
// GameScene.swift
// test
//
// Created by Eular on 15/4/23.
// Copyright (c) 2015年 Eular. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
myLabel.text = "Hello, World!";
myLabel.fontSize = 65;
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
self.addChild(myLabel)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
let sprite = SKSpriteNode(imageNamed:"Spaceship")
sprite.xScale = 0.5
sprite.yScale = 0.5
sprite.position = location
let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)
sprite.runAction(SKAction.repeatActionForever(action))
self.addChild(sprite)
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
| gpl-2.0 | 3bd6e1ec022c736e92aaac019e4b4585 | 28.022222 | 93 | 0.580398 | 4.731884 | false | false | false | false |
iqingchen/DouYuZhiBo | DY/DY/Classes/Main/Model/AnchorGroup.swift | 1 | 948 | //
// AnchorGroup.swift
// DY
//
// Created by zhang on 16/12/2.
// Copyright © 2016年 zhang. All rights reserved.
//
import UIKit
class AnchorGroup: BaseGameModel {
/// 该组中对应的房间信息
var room_list : [[String : NSObject]]? {
didSet{
guard let room_list = room_list else {return}
for dict in room_list {
anchors.append(AnchorModel(dict: dict))
}
}
}
/// 组显示的图标
var icon_name : String = "home_header_normal"
///定义主播模型对象数组
lazy var anchors : [AnchorModel] = [AnchorModel]()
/*
override func setValue(_ value: Any?, forKey key: String) {
if key == "room_list" {
if let dataArr = value as? [[String : NSObject]] {
for dic in dataArr {
anchors.append(AnchorModel(dict: dic))
}
}
}
}*/
}
| mit | bf04df5069f7c8cc1126d0cc8f2b4d3b | 23.135135 | 63 | 0.513998 | 4.077626 | false | false | false | false |
JGiola/swift-corelibs-foundation | Foundation/NSSwiftRuntime.swift | 1 | 17936 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
// Re-export Darwin and Glibc by importing Foundation
// This mimics the behavior of the swift sdk overlay on Darwin
#if os(macOS) || os(iOS)
@_exported import Darwin
#elseif os(Linux) || os(Android) || CYGWIN
@_exported import Glibc
#endif
@_exported import Dispatch
#if os(Android) // shim required for bzero
@_transparent func bzero(_ ptr: UnsafeMutableRawPointer, _ size: size_t) {
memset(ptr, 0, size)
}
#endif
#if !_runtime(_ObjC)
/// The Objective-C BOOL type.
///
/// On 64-bit iOS, the Objective-C BOOL type is a typedef of C/C++
/// bool. Elsewhere, it is "signed char". The Clang importer imports it as
/// ObjCBool.
@_fixed_layout
public struct ObjCBool : ExpressibleByBooleanLiteral {
#if os(macOS) || (os(iOS) && (arch(i386) || arch(arm)))
// On macOS and 32-bit iOS, Objective-C's BOOL type is a "signed char".
var _value: Int8
init(_ value: Int8) {
self._value = value
}
public init(_ value: Bool) {
self._value = value ? 1 : 0
}
#else
// Everywhere else it is C/C++'s "Bool"
var _value: Bool
public init(_ value: Bool) {
self._value = value
}
#endif
/// The value of `self`, expressed as a `Bool`.
public var boolValue: Bool {
#if os(macOS) || (os(iOS) && (arch(i386) || arch(arm)))
return _value != 0
#else
return _value
#endif
}
/// Create an instance initialized to `value`.
@_transparent
public init(booleanLiteral value: Bool) {
self.init(value)
}
}
extension ObjCBool : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: boolValue)
}
}
extension ObjCBool : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return self.boolValue.description
}
}
#endif
@usableFromInline
internal class __NSCFType : NSObject {
private var _cfinfo : _CFInfo
override init() {
// This is not actually called; _CFRuntimeCreateInstance will initialize _cfinfo
_cfinfo = _CFInfo(typeID: 0)
}
override var hash: Int {
return Int(bitPattern: CFHash(self))
}
override func isEqual(_ value: Any?) -> Bool {
guard let other = value as? NSObject else { return false }
return CFEqual(self, other)
}
override var description: String {
return CFCopyDescription(unsafeBitCast(self, to: CFTypeRef.self))._swiftObject
}
deinit {
_CFDeinit(self)
}
}
internal func _CFSwiftGetTypeID(_ cf: AnyObject) -> CFTypeID {
return (cf as! NSObject)._cfTypeID
}
internal func _CFSwiftCopyWithZone(_ cf: CFTypeRef, _ zone: CFTypeRef?) -> Unmanaged<CFTypeRef> {
return Unmanaged<CFTypeRef>.passRetained((cf as! NSObject).copy() as! NSObject)
}
internal func _CFSwiftGetHash(_ cf: AnyObject) -> CFHashCode {
return CFHashCode(bitPattern: (cf as! NSObject).hash)
}
internal func _CFSwiftIsEqual(_ cf1: AnyObject, cf2: AnyObject) -> Bool {
return (cf1 as! NSObject).isEqual(cf2)
}
// Ivars in _NSCF* types must be zeroed via an unsafe accessor to avoid deinit of potentially unsafe memory to accces as an object/struct etc since it is stored via a foreign object graph
internal func _CFZeroUnsafeIvars<T>(_ arg: inout T) {
withUnsafeMutablePointer(to: &arg) { (ptr: UnsafeMutablePointer<T>) -> Void in
bzero(UnsafeMutableRawPointer(ptr), MemoryLayout<T>.size)
}
}
@usableFromInline
@_cdecl("__CFSwiftGetBaseClass")
internal func __CFSwiftGetBaseClass() -> UnsafeRawPointer {
return unsafeBitCast(__NSCFType.self, to:UnsafeRawPointer.self)
}
@usableFromInline
@_cdecl("__CFInitializeSwift")
internal func __CFInitializeSwift() {
_CFRuntimeBridgeTypeToClass(CFStringGetTypeID(), unsafeBitCast(_NSCFString.self, to: UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(CFArrayGetTypeID(), unsafeBitCast(_NSCFArray.self, to: UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(CFDictionaryGetTypeID(), unsafeBitCast(_NSCFDictionary.self, to: UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(CFSetGetTypeID(), unsafeBitCast(_NSCFSet.self, to: UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(CFBooleanGetTypeID(), unsafeBitCast(__NSCFBoolean.self, to: UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(CFNumberGetTypeID(), unsafeBitCast(NSNumber.self, to: UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(CFDataGetTypeID(), unsafeBitCast(NSData.self, to: UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(CFDateGetTypeID(), unsafeBitCast(NSDate.self, to: UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(CFURLGetTypeID(), unsafeBitCast(NSURL.self, to: UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(CFCalendarGetTypeID(), unsafeBitCast(NSCalendar.self, to: UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(CFLocaleGetTypeID(), unsafeBitCast(NSLocale.self, to: UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(CFTimeZoneGetTypeID(), unsafeBitCast(NSTimeZone.self, to: UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(CFCharacterSetGetTypeID(), unsafeBitCast(_NSCFCharacterSet.self, to: UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(_CFKeyedArchiverUIDGetTypeID(), unsafeBitCast(_NSKeyedArchiverUID.self, to: UnsafeRawPointer.self))
// _CFRuntimeBridgeTypeToClass(CFErrorGetTypeID(), unsafeBitCast(NSError.self, UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(CFAttributedStringGetTypeID(), unsafeBitCast(NSMutableAttributedString.self, to: UnsafeRawPointer.self))
// _CFRuntimeBridgeTypeToClass(CFReadStreamGetTypeID(), unsafeBitCast(InputStream.self, UnsafeRawPointer.self))
// _CFRuntimeBridgeTypeToClass(CFWriteStreamGetTypeID(), unsafeBitCast(OutputStream.self, UnsafeRawPointer.self))
_CFRuntimeBridgeTypeToClass(CFRunLoopTimerGetTypeID(), unsafeBitCast(Timer.self, to: UnsafeRawPointer.self))
__CFSwiftBridge.NSObject.isEqual = _CFSwiftIsEqual
__CFSwiftBridge.NSObject.hash = _CFSwiftGetHash
__CFSwiftBridge.NSObject._cfTypeID = _CFSwiftGetTypeID
__CFSwiftBridge.NSObject.copyWithZone = _CFSwiftCopyWithZone
__CFSwiftBridge.NSSet.count = _CFSwiftSetGetCount
__CFSwiftBridge.NSSet.countForKey = _CFSwiftSetGetCountOfValue
__CFSwiftBridge.NSSet.containsObject = _CFSwiftSetContainsValue
__CFSwiftBridge.NSSet.__getValue = _CFSwiftSetGetValue
__CFSwiftBridge.NSSet.getValueIfPresent = _CFSwiftSetGetValueIfPresent
__CFSwiftBridge.NSSet.getObjects = _CFSwiftSetGetValues
__CFSwiftBridge.NSSet.copy = _CFSwiftSetCreateCopy
__CFSwiftBridge.NSSet.__apply = _CFSwiftSetApplyFunction
__CFSwiftBridge.NSSet.member = _CFSwiftSetMember
__CFSwiftBridge.NSMutableSet.addObject = _CFSwiftSetAddValue
__CFSwiftBridge.NSMutableSet.replaceObject = _CFSwiftSetReplaceValue
__CFSwiftBridge.NSMutableSet.setObject = _CFSwiftSetSetValue
__CFSwiftBridge.NSMutableSet.removeObject = _CFSwiftSetRemoveValue
__CFSwiftBridge.NSMutableSet.removeAllObjects = _CFSwiftSetRemoveAllValues
__CFSwiftBridge.NSArray.count = _CFSwiftArrayGetCount
__CFSwiftBridge.NSArray.objectAtIndex = _CFSwiftArrayGetValueAtIndex
__CFSwiftBridge.NSArray.getObjects = _CFSwiftArrayGetValues
__CFSwiftBridge.NSMutableArray.addObject = _CFSwiftArrayAppendValue
__CFSwiftBridge.NSMutableArray.setObject = _CFSwiftArraySetValueAtIndex
__CFSwiftBridge.NSMutableArray.replaceObjectAtIndex = _CFSwiftArrayReplaceValueAtIndex
__CFSwiftBridge.NSMutableArray.insertObject = _CFSwiftArrayInsertValueAtIndex
__CFSwiftBridge.NSMutableArray.exchangeObjectAtIndex = _CFSwiftArrayExchangeValuesAtIndices
__CFSwiftBridge.NSMutableArray.removeObjectAtIndex = _CFSwiftArrayRemoveValueAtIndex
__CFSwiftBridge.NSMutableArray.removeAllObjects = _CFSwiftArrayRemoveAllValues
__CFSwiftBridge.NSMutableArray.replaceObjectsInRange = _CFSwiftArrayReplaceValues
__CFSwiftBridge.NSDictionary.count = _CFSwiftDictionaryGetCount
__CFSwiftBridge.NSDictionary.countForKey = _CFSwiftDictionaryGetCountOfKey
__CFSwiftBridge.NSDictionary.containsKey = _CFSwiftDictionaryContainsKey
__CFSwiftBridge.NSDictionary.objectForKey = _CFSwiftDictionaryGetValue
__CFSwiftBridge.NSDictionary._getValueIfPresent = _CFSwiftDictionaryGetValueIfPresent
__CFSwiftBridge.NSDictionary.containsObject = _CFSwiftDictionaryContainsValue
__CFSwiftBridge.NSDictionary.countForObject = _CFSwiftDictionaryGetCountOfValue
__CFSwiftBridge.NSDictionary.getObjects = _CFSwiftDictionaryGetValuesAndKeys
__CFSwiftBridge.NSDictionary.__apply = _CFSwiftDictionaryApplyFunction
__CFSwiftBridge.NSDictionary.copy = _CFSwiftDictionaryCreateCopy
__CFSwiftBridge.NSMutableDictionary.__addObject = _CFSwiftDictionaryAddValue
__CFSwiftBridge.NSMutableDictionary.replaceObject = _CFSwiftDictionaryReplaceValue
__CFSwiftBridge.NSMutableDictionary.__setObject = _CFSwiftDictionarySetValue
__CFSwiftBridge.NSMutableDictionary.removeObjectForKey = _CFSwiftDictionaryRemoveValue
__CFSwiftBridge.NSMutableDictionary.removeAllObjects = _CFSwiftDictionaryRemoveAllValues
__CFSwiftBridge.NSString._createSubstringWithRange = _CFSwiftStringCreateWithSubstring
__CFSwiftBridge.NSString.copy = _CFSwiftStringCreateCopy
__CFSwiftBridge.NSString.mutableCopy = _CFSwiftStringCreateMutableCopy
__CFSwiftBridge.NSString.length = _CFSwiftStringGetLength
__CFSwiftBridge.NSString.characterAtIndex = _CFSwiftStringGetCharacterAtIndex
__CFSwiftBridge.NSString.getCharacters = _CFSwiftStringGetCharacters
__CFSwiftBridge.NSString.__getBytes = _CFSwiftStringGetBytes
__CFSwiftBridge.NSString._fastCStringContents = _CFSwiftStringFastCStringContents
__CFSwiftBridge.NSString._fastCharacterContents = _CFSwiftStringFastContents
__CFSwiftBridge.NSString._getCString = _CFSwiftStringGetCString
__CFSwiftBridge.NSString._encodingCantBeStoredInEightBitCFString = _CFSwiftStringIsUnicode
__CFSwiftBridge.NSMutableString.insertString = _CFSwiftStringInsert
__CFSwiftBridge.NSMutableString.deleteCharactersInRange = _CFSwiftStringDelete
__CFSwiftBridge.NSMutableString.replaceCharactersInRange = _CFSwiftStringReplace
__CFSwiftBridge.NSMutableString.setString = _CFSwiftStringReplaceAll
__CFSwiftBridge.NSMutableString.appendString = _CFSwiftStringAppend
__CFSwiftBridge.NSMutableString.appendCharacters = _CFSwiftStringAppendCharacters
__CFSwiftBridge.NSMutableString._cfAppendCString = _CFSwiftStringAppendCString
__CFSwiftBridge.NSXMLParser.currentParser = _NSXMLParserCurrentParser
__CFSwiftBridge.NSXMLParser._xmlExternalEntityWithURL = _NSXMLParserExternalEntityWithURL
__CFSwiftBridge.NSXMLParser.getContext = _NSXMLParserGetContext
__CFSwiftBridge.NSXMLParser.internalSubset = _NSXMLParserInternalSubset
__CFSwiftBridge.NSXMLParser.isStandalone = _NSXMLParserIsStandalone
__CFSwiftBridge.NSXMLParser.hasInternalSubset = _NSXMLParserHasInternalSubset
__CFSwiftBridge.NSXMLParser.hasExternalSubset = _NSXMLParserHasExternalSubset
__CFSwiftBridge.NSXMLParser.getEntity = _NSXMLParserGetEntity
__CFSwiftBridge.NSXMLParser.notationDecl = _NSXMLParserNotationDecl
__CFSwiftBridge.NSXMLParser.attributeDecl = _NSXMLParserAttributeDecl
__CFSwiftBridge.NSXMLParser.elementDecl = _NSXMLParserElementDecl
__CFSwiftBridge.NSXMLParser.unparsedEntityDecl = _NSXMLParserUnparsedEntityDecl
__CFSwiftBridge.NSXMLParser.startDocument = _NSXMLParserStartDocument
__CFSwiftBridge.NSXMLParser.endDocument = _NSXMLParserEndDocument
__CFSwiftBridge.NSXMLParser.startElementNs = _NSXMLParserStartElementNs
__CFSwiftBridge.NSXMLParser.endElementNs = _NSXMLParserEndElementNs
__CFSwiftBridge.NSXMLParser.characters = _NSXMLParserCharacters
__CFSwiftBridge.NSXMLParser.processingInstruction = _NSXMLParserProcessingInstruction
__CFSwiftBridge.NSXMLParser.cdataBlock = _NSXMLParserCdataBlock
__CFSwiftBridge.NSXMLParser.comment = _NSXMLParserComment
__CFSwiftBridge.NSXMLParser.externalSubset = _NSXMLParserExternalSubset
__CFSwiftBridge.NSRunLoop._new = _NSRunLoopNew
__CFSwiftBridge.NSCharacterSet._expandedCFCharacterSet = _CFSwiftCharacterSetExpandedCFCharacterSet
__CFSwiftBridge.NSCharacterSet._retainedBitmapRepresentation = _CFSwiftCharacterSetRetainedBitmapRepresentation
__CFSwiftBridge.NSCharacterSet.characterIsMember = _CFSwiftCharacterSetCharacterIsMember
__CFSwiftBridge.NSCharacterSet.mutableCopy = _CFSwiftCharacterSetMutableCopy
__CFSwiftBridge.NSCharacterSet.longCharacterIsMember = _CFSwiftCharacterSetLongCharacterIsMember
__CFSwiftBridge.NSCharacterSet.hasMemberInPlane = _CFSwiftCharacterSetHasMemberInPlane
__CFSwiftBridge.NSCharacterSet.invertedSet = _CFSwiftCharacterSetInverted
__CFSwiftBridge.NSMutableCharacterSet.addCharactersInRange = _CFSwiftMutableSetAddCharactersInRange
__CFSwiftBridge.NSMutableCharacterSet.removeCharactersInRange = _CFSwiftMutableSetRemoveCharactersInRange
__CFSwiftBridge.NSMutableCharacterSet.addCharactersInString = _CFSwiftMutableSetAddCharactersInString
__CFSwiftBridge.NSMutableCharacterSet.removeCharactersInString = _CFSwiftMutableSetRemoveCharactersInString
__CFSwiftBridge.NSMutableCharacterSet.formUnionWithCharacterSet = _CFSwiftMutableSetFormUnionWithCharacterSet
__CFSwiftBridge.NSMutableCharacterSet.formIntersectionWithCharacterSet = _CFSwiftMutableSetFormIntersectionWithCharacterSet
__CFSwiftBridge.NSMutableCharacterSet.invert = _CFSwiftMutableSetInvert
__CFSwiftBridge.NSNumber._cfNumberGetType = _CFSwiftNumberGetType
__CFSwiftBridge.NSNumber._getValue = _CFSwiftNumberGetValue
__CFSwiftBridge.NSNumber.boolValue = _CFSwiftNumberGetBoolValue
__CFSwiftBridge.NSData.copy = _CFSwiftDataCreateCopy
__CFSwiftBridge.NSCalendar.calendarIdentifier = _CFSwiftCalendarGetCalendarIdentifier
__CFSwiftBridge.NSCalendar.copyLocale = _CFSwiftCalendarCopyLocale
__CFSwiftBridge.NSCalendar.setLocale = _CFSwiftCalendarSetLocale
__CFSwiftBridge.NSCalendar.copyTimeZone = _CFSwiftCalendarCopyTimeZone
__CFSwiftBridge.NSCalendar.setTimeZone = _CFSwiftCalendarSetTimeZone
__CFSwiftBridge.NSCalendar.firstWeekday = _CFSwiftCalendarGetFirstWeekday
__CFSwiftBridge.NSCalendar.setFirstWeekday = _CFSwiftCalendarSetFirstWeekday
__CFSwiftBridge.NSCalendar.minimumDaysInFirstWeek = _CFSwiftCalendarGetMinimumDaysInFirstWeek
__CFSwiftBridge.NSCalendar.setMinimumDaysInFirstWeek = _CFSwiftCalendarSetMinimumDaysInFirstWeek
__CFSwiftBridge.NSCalendar.copyGregorianStartDate = _CFSwiftCalendarCopyGregorianStartDate
__CFSwiftBridge.NSCalendar.setGregorianStartDate = _CFSwiftCalendarSetGregorianStartDate
// __CFDefaultEightBitStringEncoding = UInt32(kCFStringEncodingUTF8)
}
public func === (lhs: AnyClass, rhs: AnyClass) -> Bool {
return unsafeBitCast(lhs, to: UnsafeRawPointer.self) == unsafeBitCast(rhs, to: UnsafeRawPointer.self)
}
/// Swift extensions for common operations in Foundation that use unsafe things...
extension NSObject {
static func unretainedReference<R: NSObject>(_ value: UnsafeRawPointer) -> R {
return unsafeBitCast(value, to: R.self)
}
static func unretainedReference<R: NSObject>(_ value: UnsafeMutableRawPointer) -> R {
return unretainedReference(UnsafeRawPointer(value))
}
static func releaseReference(_ value: UnsafeRawPointer) {
_CFSwiftRelease(UnsafeMutableRawPointer(mutating: value))
}
static func releaseReference(_ value: UnsafeMutableRawPointer) {
_CFSwiftRelease(value)
}
func withRetainedReference<T, R>(_ work: (UnsafePointer<T>) -> R) -> R {
let selfPtr = Unmanaged.passRetained(self).toOpaque().assumingMemoryBound(to: T.self)
return work(selfPtr)
}
func withRetainedReference<T, R>(_ work: (UnsafeMutablePointer<T>) -> R) -> R {
let selfPtr = Unmanaged.passRetained(self).toOpaque().assumingMemoryBound(to: T.self)
return work(selfPtr)
}
func withUnretainedReference<T, R>(_ work: (UnsafePointer<T>) -> R) -> R {
let selfPtr = Unmanaged.passUnretained(self).toOpaque().assumingMemoryBound(to: T.self)
return work(selfPtr)
}
func withUnretainedReference<T, R>(_ work: (UnsafeMutablePointer<T>) -> R) -> R {
let selfPtr = Unmanaged.passUnretained(self).toOpaque().assumingMemoryBound(to: T.self)
return work(selfPtr)
}
}
extension Array {
internal mutating func withUnsafeMutablePointerOrAllocation<R>(_ count: Int, fastpath: UnsafeMutablePointer<Element>? = nil, body: (UnsafeMutablePointer<Element>) -> R) -> R {
if let fastpath = fastpath {
return body(fastpath)
} else if self.count > count {
let buffer = UnsafeMutablePointer<Element>.allocate(capacity: count)
let res = body(buffer)
buffer.deinitialize(count: count)
buffer.deallocate()
return res
} else {
return withUnsafeMutableBufferPointer() { (bufferPtr: inout UnsafeMutableBufferPointer<Element>) -> R in
return body(bufferPtr.baseAddress!)
}
}
}
}
#if os(macOS) || os(iOS)
internal typealias _DarwinCompatibleBoolean = DarwinBoolean
#else
internal typealias _DarwinCompatibleBoolean = Bool
#endif
| apache-2.0 | fc3107aea186193482ddf1c000e41554 | 46.829333 | 187 | 0.761597 | 5.325416 | false | false | false | false |
chitaranjan/Album | MYAlbum/MYAlbum/MYAlbumConstants.swift | 1 | 2143 |
import Foundation
struct AppColors {
static let AppBGColor = UIColor(hexString: "ffffff")
}
struct URLConstants {
static let BaseURL: String = "http://192.168.1.11:8005/"
static let imgDomain : String = "http://192.168.1.11/album/"
}
var _userLogin = ""
var _userPassword = ""
class AlertView: NSObject {
static func showAlert(_ targetVC: UIViewController, title: String, message: AnyObject) {
let alertController = UIAlertController(title: title, message: message as? String, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
targetVC.present(alertController, animated: true, completion: nil)
}
}
public extension UIDevice {
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8 , value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
switch identifier {
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "i386", "x86_64": return "Simulator"
default: return identifier
}
}
}
| mit | 561e4c555626e1f97f5decc210aeb31d | 37.963636 | 114 | 0.539897 | 4.598712 | false | false | false | false |
xwu/swift | test/Generics/sr15009.swift | 1 | 489 | // RUN: %target-typecheck-verify-swift -debug-generic-signatures -requirement-machine-protocol-signatures=on 2>&1 | %FileCheck %s
// CHECK: sr15009.(file).P@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.A.B, Self.A : Q>
protocol P { associatedtype A: Q where A.B == Self }
// CHECK: sr15009.(file).Q@
// CHECK-NEXT: Requirement signature: <Self where Self : CaseIterable, Self == Self.B.A, Self.B : P>
protocol Q: CaseIterable { associatedtype B: P where B.A == Self }
| apache-2.0 | 946bfcebb5f116f5c46c344c9055fd7b | 53.333333 | 129 | 0.701431 | 3.26 | false | false | false | false |
psobot/hangover | Hangover/TextMapper.swift | 1 | 1807 | //
// TextMapper.swift
// Hangover
//
// Created by Peter Sobot on 6/28/15.
// Copyright © 2015 Peter Sobot. All rights reserved.
//
import Cocoa
class TextMapper {
class func segmentsForInput(text: String) -> [ChatMessageSegment] {
let textWithUnicodeEmoji = EmojiMapper.replaceEmoticonsWithEmoji(text)
return [ChatMessageSegment(text: textWithUnicodeEmoji)]
}
class func attributedStringForText(text: String) -> NSAttributedString {
let attrString = NSMutableAttributedString(string: text)
let style = NSMutableParagraphStyle()
style.lineBreakMode = NSLineBreakMode.ByWordWrapping
let linkDetector = try! NSDataDetector(types: NSTextCheckingType.Link.rawValue)
for match in linkDetector.matchesInString(text, options: [], range: NSMakeRange(0, text.characters.count)) {
if let url = match.URL {
attrString.addAttribute(NSLinkAttributeName, value: url, range: match.range)
attrString.addAttribute(NSForegroundColorAttributeName, value: NSColor.blueColor(), range: match.range)
attrString.addAttribute(
NSUnderlineStyleAttributeName,
value: NSNumber(integer: NSUnderlineStyle.StyleSingle.rawValue),
range: match.range
)
}
}
// TODO: Move this paragraph style and font stuff to the view
attrString.addAttribute(
NSFontAttributeName,
value: NSFont.systemFontOfSize(12),
range: NSMakeRange(0, attrString.length)
)
attrString.addAttribute(
NSParagraphStyleAttributeName,
value: style,
range: NSMakeRange(0, attrString.length)
)
return attrString
}
} | mit | 086bd4c491bef6ce1679a28df43a3f5a | 34.431373 | 119 | 0.645072 | 5.280702 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceApplication/Sources/EurofurenceApplication/Content Router/Routes/Login/LoginRoute.swift | 1 | 1641 | import ComponentBase
import RouterCore
import UIKit.UIViewController
public struct LoginRoute {
private let loginModuleFactory: LoginComponentFactory
private let modalWireframe: ModalWireframe
public init(
loginModuleFactory: LoginComponentFactory,
modalWireframe: ModalWireframe
) {
self.loginModuleFactory = loginModuleFactory
self.modalWireframe = modalWireframe
}
}
// MARK: - Route
extension LoginRoute: Route {
public typealias Parameter = LoginRouteable
public func route(_ content: LoginRouteable) {
let delegate = MapResponseToBlock(completionHandler: content.completionHandler)
let contentController = loginModuleFactory.makeLoginModule(delegate)
delegate.viewController = contentController
modalWireframe.presentModalContentController(contentController)
}
private class MapResponseToBlock: LoginComponentDelegate {
private let completionHandler: (Bool) -> Void
weak var viewController: UIViewController?
init(completionHandler: @escaping (Bool) -> Void) {
self.completionHandler = completionHandler
}
func loginModuleDidCancelLogin() {
finalize(success: false)
}
func loginModuleDidLoginSuccessfully() {
finalize(success: true)
}
private func finalize(success: Bool) {
viewController?.dismiss(animated: true) { [completionHandler] in
completionHandler(success)
}
}
}
}
| mit | aeabe955987f73e96e650b0509f85a9a | 26.813559 | 87 | 0.648995 | 5.924188 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/gliding-collection-master/GlidingCollectionDemo/Extensions/FileManager.swift | 4 | 816 | //
// FileManager.swift
// GlidingCollection
//
// Created by Abdurahim Jauzee on 10/03/2017.
// Copyright © 2017 Ramotion Inc. All rights reserved.
//
import Foundation
extension FileManager {
func fileUrls(for types: String..., fileName: String) -> [URL] {
let bundlePath = Bundle.main.bundlePath
let directoryEnumerator = enumerator(atPath: bundlePath)
var paths = [URL]()
while let path = directoryEnumerator?.nextObject() as? String {
let url = URL(fileURLWithPath: path)
for type in types {
if
url.path.lowercased().contains(fileName.lowercased())
&& url.path.contains(type) {
let url = Bundle.main.bundleURL.appendingPathComponent(path)
paths.append(url)
}
}
}
return paths
}
}
| mit | bc0034a53f4d3a3f73aad8e0218c9f30 | 22.285714 | 70 | 0.625767 | 4.179487 | false | false | false | false |
markd2/BorkMore | BorkMore/Document.swift | 1 | 2232 | //
// Document.swift
// BorkMore
//
// Created by Mark Dalrymple on 4/25/15.
// Copyright (c) 2015 Borkware. All rights reserved.
//
import Cocoa
class Document: NSDocument {
override init() {
super.init()
// Add your subclass-specific initialization here.
}
override func windowControllerDidLoadNib(aController: NSWindowController) {
super.windowControllerDidLoadNib(aController)
// Add any code here that needs to be executed once the windowController has loaded the document's window.
}
override class func autosavesInPlace() -> Bool {
return true
}
override func makeWindowControllers() {
// Returns the Storyboard that contains your Document window.
let storyboard = NSStoryboard(name: "Main", bundle: nil)!
let windowController = storyboard.instantiateControllerWithIdentifier("Document Window Controller") as! NSWindowController
self.addWindowController(windowController)
}
override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? {
// Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil.
// You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
return nil
}
override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool {
// Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false.
// You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead.
// If you override either of these, you should also override -isEntireFileLoaded to return NO if the contents are lazily loaded.
outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
return false
}
}
| mit | 04cae83b78b099c604ef8da2b01a1a09 | 42.764706 | 186 | 0.719982 | 4.873362 | false | false | false | false |
mario-kang/HClient | HClient/mainMenu.swift | 1 | 11716 | //
// mainMenu.swift
// HClient
//
// Created by 강희찬 on 2017. 7. 18..
// Copyright © 2017년 mario-kang. All rights reserved.
//
import UIKit
import SafariServices
class MainmenuCell: UITableViewCell {
@IBOutlet weak var DJImage: UIImageView!
@IBOutlet weak var DJSeries: UILabel!
@IBOutlet weak var DJTitle: UILabel!
@IBOutlet weak var DJLang: UILabel!
@IBOutlet weak var DJTag: UILabel!
@IBOutlet weak var DJArtist: UILabel!
}
class mainMenu: UITableViewController, UIViewControllerPreviewingDelegate {
var activityController:UIActivityIndicatorView!
var arr:[Any] = []
var arr2:[Any] = []
var arr3:[Any] = []
var celllist:[String] = []
var pages = false
var page:UInt = 0
var previewingContext:Any?
override func viewDidLoad() {
super.viewDidLoad()
activityController = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
activityController?.autoresizingMask = [.flexibleBottomMargin, .flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin]
activityController.activityIndicatorViewStyle = .whiteLarge
pages = false
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 154.0
if self.traitCollection.forceTouchCapability == UIForceTouchCapability.available {
self.previewingContext = self.registerForPreviewing(with: self as UIViewControllerPreviewingDelegate, sourceView: self.view)
}
page = 1
downloadTask(page)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr2.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MainmenuCell = tableView.dequeueReusableCell(withIdentifier: "list", for: indexPath) as! MainmenuCell
let list:String = arr[indexPath.row] as! String
let ar = list.components(separatedBy: "</a></h1>")
let title = ar[0].components(separatedBy: ".html\">")[2]
let etc = ar[1].components(separatedBy: "</div>")
let artlist = etc[0].components(separatedBy: "list\">")[1]
var artist = ""
if artlist.contains("N/A") {
artist.append("N/A")
}
else {
let a = artlist.components(separatedBy: "</a></li>")
let b = a.count-2
for i in 0...b {
artist.append(a[i].components(separatedBy: ".html\">")[1])
if i != b {
artist.append(", ")
}
}
}
let etc1 = etc[1].components(separatedBy: "</td>")
var series = NSLocalizedString("Series: ", comment: "")
if etc1[1].contains("N/A") {
series.append("N/A")
}
else {
let a = etc1[1].components(separatedBy: "</a></li>")
let b = a.count-2
for i in 0...b {
series.append(a[i].components(separatedBy: ".html\">")[1])
if i != b {
series.append(", ")
}
}
}
var language = NSLocalizedString("Language: ", comment: "")
if etc1[5].contains("N/A") {
language.append("N/A")
}
else {
language.append(etc1[5].components(separatedBy: ".html\">")[1].components(separatedBy: "</a>")[0])
}
var tag1 = NSLocalizedString("Tags: ", comment: "")
let taga = etc1[7].components(separatedBy: "</a></li>")
let tagb = taga.count
if tagb == 1 {
tag1.append("N/A")
}
else {
for i in 0...tagb-2 {
tag1.append(taga[i].components(separatedBy: ".html\">")[1])
if i != tagb-2 {
tag1.append(", ")
}
}
}
let session = URLSession.shared
let request = URLRequest(url: URL(string:arr2[indexPath.row] as! String)!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60.0)
if arr3[indexPath.row] is UIImage {
cell.DJImage.image = arr3[indexPath.row] as? UIImage
}
else {
cell.DJImage.image = nil
}
if !(celllist.contains(where: {$0 == "\(indexPath.row)"})) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
let sessionTask = session.dataTask(with: request, completionHandler: { (data, _, error) in
if error == nil {
let image = UIImage(data: data!)
self.arr3[indexPath.row] = image!
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
cell.DJImage.image = image
}
}
})
sessionTask.resume()
}
cell.DJImage.contentMode = .scaleAspectFit
cell.DJTitle.text = Strings.decode(title)
cell.DJArtist.text = Strings.decode(artist)
cell.DJSeries.text = Strings.decode(series)
cell.DJLang.text = Strings.decode(language)
cell.DJTag.text = Strings.decode(tag1)
if !(celllist.contains {$0 == "\(indexPath.row)"}) {
celllist.append("\(indexPath.row)")
}
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row + 1 == arr2.count && !pages {
page += 1
downloadTask(page)
pages = true
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let segued:InfoDetail = segue.destination as! InfoDetail
let path = self.tableView.indexPathForSelectedRow
let title = (arr[(path?.row)!] as! String).components(separatedBy: ".html\">")[0].components(separatedBy: "<a href=\"")[1]
let djURL = "https://hitomi.la\(title).html"
segued.URL1 = djURL
}
func downloadTask(_ ind:UInt) {
var overlay:UIView
overlay = UIView(frame: (self.splitViewController?.view.frame)!)
overlay.backgroundColor = UIColor.black
overlay.alpha = 0.8
overlay.autoresizingMask = (self.splitViewController?.view.autoresizingMask)!
activityController.center = (self.splitViewController?.view.center)!
self.splitViewController?.view.addSubview(overlay)
overlay.addSubview(activityController)
activityController.isHidden = false
activityController.startAnimating()
let url = URL(string: "https://hitomi.la/index-all-\(ind).html")
UIApplication.shared.isNetworkActivityIndicatorVisible = true
let session = URLSession.shared
let request = URLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60.0)
let task = session.dataTask(with: request) { (data, response, error) in
if error == nil && (response as! HTTPURLResponse).statusCode == 200 {
var str = String(data:data!, encoding:.utf8)
str = Strings.replacingOccurrences(str)
let temp = str?.components(separatedBy: "<div class=\"dj\">")
for i in 1...(temp?.count)!-1 {
let list = temp?[i]
let img = list?.components(separatedBy: "\"> </div>")[0]
let imga = img?.components(separatedBy: "<img src=\"")[1]
let urlString = "https:\(imga!)"
self.arr.append(temp![i])
self.arr2.append(urlString)
self.arr3.append(NSNull())
}
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.tableView.reloadData()
self.activityController.isHidden = true
self.activityController.stopAnimating()
overlay.removeFromSuperview()
self.pages = false
}
}
else {
OperationQueue.main.addOperation {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
let alert = UIAlertController(title: NSLocalizedString("Error Occured.", comment: ""), message: error?.localizedDescription, preferredStyle: .alert)
let action = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
self.activityController.isHidden = true
self.activityController.stopAnimating()
overlay.removeFromSuperview()
}
}
}
task.resume()
self.tableView.reloadData()
}
@IBAction func Action(_ sender: Any) {
let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let activity = UIAlertAction(title: NSLocalizedString("Share URL", comment: ""), style: .default) { (_) in
let url = URL(string: "https://hitomi.la/")
let activitys = UIActivityViewController(activityItems: [url!], applicationActivities: nil)
activitys.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
self.present(activitys, animated: true, completion: nil)
}
let open = UIAlertAction(title: NSLocalizedString("Open in Safari", comment: ""), style: .default) { (_) in
let url = URL(string: "https://hitomi.la/")
let safari = SFSafariViewController(url: url!)
if #available(iOS 10.0, *) {
safari.preferredBarTintColor = UIColor(hue: 235.0/360.0, saturation: 0.77, brightness: 0.47, alpha: 1.0)
}
self.present(safari, animated: true, completion: nil)
}
let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil)
sheet.addAction(activity)
sheet.addAction(open)
sheet.addAction(cancel)
sheet.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
self.present(sheet, animated: true, completion: nil)
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
let cellPosition = self.tableView.convert(location, to: self.view)
let path = self.tableView.indexPathForRow(at: cellPosition)
if path != nil {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let segued:InfoDetail = storyboard.instantiateViewController(withIdentifier: "io.github.mario-kang.HClient.infodetail") as! InfoDetail
let title1 = arr[(path?.row)!]
let title2 = (title1 as! String).components(separatedBy: ".html\">")[0]
let title3 = title2.components(separatedBy: "<a href=\"")[1]
let djURL = "https://hitomi.la\(title3).html"
segued.URL1 = djURL
return segued
}
return nil
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
self.navigationController?.show(viewControllerToCommit, sender: nil)
}
}
| mit | e69c450f77a51dbde893565555beac66 | 43.854406 | 168 | 0.59016 | 4.760878 | false | false | false | false |
galacemiguel/bluehacks2017 | Project Civ-1/Project Civ/ProjectUpdateSectionController.swift | 1 | 3048 | //
// ProjectUpdateSectionController.swift
// Project Civ
//
// Created by Carlos Arcenas on 2/18/17.
// Copyright © 2017 Rogue Three. All rights reserved.
//
import Foundation
import IGListKit
class ProjectUpdateSectionController: IGListSectionController {
var projectUpdate: ProjectUpdate!
override init() {
super.init()
inset = UIEdgeInsets(top: 0, left: 0, bottom: 15, right: 0)
}
}
extension ProjectUpdateSectionController: IGListSectionType {
func numberOfItems() -> Int {
return projectUpdate.fetchUpdateComponents().count
}
func sizeForItem(at index: Int) -> CGSize {
guard let context = collectionContext, let update = projectUpdate else { return .zero }
let width = context.containerSize.width
// temp
let components = projectUpdate.fetchUpdateComponents()
if components[index] == .message {
return TextCell.cellSize(width: width, string: update.message!)
} else if components[index] == .userInfoAndTitle {
return ProjectUpdateTitleCell.cellSize(width: width, titleString: update.title, authorString: update.user.name)
} else if components[index] == .image {
return CGSize(width: width, height: 150)
}
return CGSize(width: width, height: 30)
}
func cellForItem(at index: Int) -> UICollectionViewCell {
let enumValue = projectUpdate.fetchUpdateComponents()[index]
var cellClass: AnyClass
switch enumValue {
case .userInfoAndTitle:
cellClass = ProjectUpdateTitleCell.self
case .image:
cellClass = ImageCell.self
case .message:
cellClass = TextCell.self
// case .date:
// cellClass = DateCell.self
default:
fatalError()
}
let cell = collectionContext!.dequeueReusableCell(of: cellClass, for: self, at: index)
if let cell = cell as? ProjectUpdateTitleCell {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
cell.titleLabel.text = projectUpdate.title
cell.authorLabel.text = projectUpdate.user.name.uppercased() + " ON " + dateFormatter.string(from: projectUpdate.date)
} else if let cell = cell as? ImageCell {
let image = UIImage(named: "hellohello.jpg")
cell.imageView.image = image
} else if let cell = cell as? TextCell {
cell.label.text = projectUpdate.message!
}
// else if let cell = cell as? DateCell {
// let dateFormatter = DateFormatter()
// dateFormatter.dateFormat = "MMMM dd, yyyy"
// cell.label.text = dateFormatter.string(from: projectUpdate.date)
// }
return cell
}
func didUpdate(to object: Any) {
projectUpdate = object as? ProjectUpdate
}
func didSelectItem(at index: Int) {
// fill this in
}
}
| mit | 99481ebd6b3187b476603ec82d59168b | 33.235955 | 130 | 0.61339 | 4.738725 | false | false | false | false |
phatblat/PushPopSplitView | PushPopSplitView/MasterViewController.swift | 1 | 3581 | //
// MasterViewController.swift
// PushPopSplitView
//
// Created by Ben Chatelain on 10/12/15.
// Copyright © 2015 Ben Chatelain. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insert(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! NSDate
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
| mit | a31a6246c3a0462c4dcdc28a867b16f3 | 37.085106 | 157 | 0.694413 | 5.764895 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/AviasalesSource/AirportPicker/ASAirportPickerPresenter.swift | 1 | 7732 | //
// ASAirportPickerPresenter.swift
// AviasalesSDKTemplate
//
// Created by Dim on 07.07.17.
// Copyright © 2017 Go Travel Un Limited. All rights reserved.
//
protocol ASAirportPickerViewProtocol: class {
func set(title: String)
func set(placeholder: String)
func set(sectionModels: [ASAirportPickerSectionViewModel])
func popOrDismiss()
}
class ASAirportPickerPresenter: NSObject {
fileprivate let type: ASAirportPickerType
fileprivate let selection: (JRSDKAirport) -> Void
fileprivate weak var view: ASAirportPickerViewProtocol?
fileprivate let searchedAirports = JRSearchedAirportsManager.searchedAirports()
fileprivate var searchText = String()
fileprivate var searching = false
fileprivate lazy var searchPerformer: AviasalesAirportsSearchPerformer = {
return AviasalesAirportsSearchPerformer.init(searchLocationType: [.airport, .city], delegate: self)
}()
init(type: ASAirportPickerType, selection: @escaping (JRSDKAirport) -> Void) {
self.type = type
self.selection = selection
super.init()
}
deinit {
stopObservingNotifications()
}
func attach(_ view: ASAirportPickerViewProtocol) {
self.view = view
view.set(title: type == .origin ? NSLS("JR_AIRPORT_PICKER_ORIGIN_MODE_TITLE") : NSLS("JR_AIRPORT_PICKER_DESTINATION_MODE_TITLE"))
view.set(placeholder: NSLS("JR_AIRPORT_PICKER_PLACEHOLDER_TEXT"))
view.set(sectionModels: buildDefaultSectionModels())
startObservingNotifications()
}
func set(searchText: String) {
searchPerformer.cancelSearch()
self.searchText = searchText
if searchText.isEmpty {
searching = false
view?.set(sectionModels: buildDefaultSectionModels())
} else {
searching = true
searchPerformer.searchAirports(with: searchText)
}
}
func select(cellModel: ASAirportPickerCellModelProtocol) {
if cellModel.type == .data {
let cellModel = cellModel as! ASAirportPickerDataCellModel
JRSearchedAirportsManager.markSearchedAirport(cellModel.model)
selection(cellModel.model)
view?.popOrDismiss()
}
}
}
private extension ASAirportPickerPresenter {
func startObservingNotifications() {
if type == .origin {
let name = Notification.Name(rawValue: kAviasalesNearestAirportsManagerDidUpdateNotificationName)
NotificationCenter.default.addObserver(self, selector: #selector(updateNearestAirports), name: name, object: nil)
}
}
func stopObservingNotifications() {
if type == .origin {
NotificationCenter.default.removeObserver(self)
}
}
@objc func updateNearestAirports() {
if self.searchText.isEmpty {
view?.set(sectionModels: buildDefaultSectionModels())
}
}
}
private extension ASAirportPickerPresenter {
func buildDefaultSectionModels() -> [ASAirportPickerSectionViewModel] {
var sectionModels = [ASAirportPickerSectionViewModel]()
if type == .origin {
sectionModels.append(buildNearestAirportsSectionModel())
}
if let searchedAirports = searchedAirports, searchedAirports.count > 0 {
sectionModels.append(buildSearchedAirportsSectionModel())
}
return sectionModels
}
func buildNearestAirportsSectionModel() -> ASAirportPickerSectionViewModel {
return ASAirportPickerSectionViewModel(name: NSLS("JR_AIRPORT_PICKER_NEAREST_AIRPORTS"), cellModels: buildNearestAirportsCellModels())
}
func buildNearestAirportsCellModels() -> [ASAirportPickerCellModelProtocol] {
let state = AviasalesSDK.sharedInstance().nearestAirportsManager.state
let airports = AviasalesSDK.sharedInstance().nearestAirportsManager.airports
let cellModels: [ASAirportPickerCellModelProtocol]
switch state {
case .readingAirportData:
cellModels = [ASAirportPickerInfoCellModel(loading: true, info: NSLS("JR_AIRPORT_PICKER_UPDATING_NEAREST_AIRPORTS"))]
case .readingError:
cellModels = [ASAirportPickerInfoCellModel(loading: false, info: NSLS("JR_AIRPORT_PICKER_NEAREST_AIRPORTS_READING_ERROR"))]
case .idle where airports?.count == 0:
cellModels = [ASAirportPickerInfoCellModel(loading: false, info: NSLS("JR_AIRPORT_PICKER_NO_NEAREST_AIRPORTS"))]
case .idle:
cellModels = buildCellModels(from: airports)
}
return cellModels
}
func buildSearchedAirportsSectionModel() -> ASAirportPickerSectionViewModel {
return ASAirportPickerSectionViewModel(name: NSLS("JR_AIRPORT_PICKER_SEARCHED_AIRPORTS"), cellModels: buildSearchedAirportsCellModels())
}
func buildSearchedAirportsCellModels() -> [ASAirportPickerDataCellModel] {
return buildCellModels(from: searchedAirports)
}
func buildCellModels(from airports: [JRSDKAirport]?) -> [ASAirportPickerDataCellModel] {
guard let airports = airports else {
return [ASAirportPickerDataCellModel]()
}
return airports.map {
ASAirportPickerDataCellModel(city: $0.city, airport: airportAndCountryString(for: $0), iata: $0.iata, model: $0)
}
}
func airportAndCountryString(for airport: JRSDKAirport) -> String {
return [airportString(for: airport), airport.countryName].compactMap({ $0 }).joined(separator: NSLS("COMMA_AND_WHITESPACE"))
}
func airportString(for airport: JRSDKAirport) -> String? {
var name: String?
if airport.isCity {
let airport = AviasalesSDK.sharedInstance().airportsStorage.findAirport(byIATA: airport.iata, city: false)
if let airport = airport, JRSDKModelUtils.isAirportSingle(inItsCity: airport) {
name = airport.airportName
} else {
name = NSLS("JR_ANY_AIRPORT")
}
} else {
name = airport.airportName
}
return name
}
}
private extension ASAirportPickerPresenter {
func buildSearchSectionModels(from locations: [JRSDKLocation]) -> [ASAirportPickerSectionViewModel] {
return [ASAirportPickerSectionViewModel(name: nil, cellModels: buildCellModels(from: locations))]
}
func buildCellModels(from locations: [JRSDKLocation]) -> [ASAirportPickerCellModelProtocol] {
var cellModels = [ASAirportPickerCellModelProtocol]()
for location in locations {
if let airport = location as? JRSDKAirport, airport.searchable == true {
cellModels.append(ASAirportPickerDataCellModel(city: airport.city, airport: airportAndCountryString(for: airport), iata: airport.iata, model: airport))
}
}
if cellModels.count == 0 && !searching {
cellModels.append(ASAirportPickerInfoCellModel(loading: false, info: NSLS("JR_AIRPORT_PICKER_NOT_FOUND")))
}
if searching {
cellModels.append(ASAirportPickerInfoCellModel(loading: true, info: NSLS("JR_AIRPORT_PICKER_SEARCHING_ON_SERVER_TEXT")))
}
return cellModels
}
}
extension ASAirportPickerPresenter: AviasalesSearchPerformerDelegate {
func airportsSearchPerformer(_ airportsSearchPerformer: AviasalesAirportsSearchPerformer!, didFound locations: [JRSDKLocation]!, final: Bool) {
searching = !final
view?.set(sectionModels: buildSearchSectionModels(from: locations))
}
func airportsSearchPerformer(_ airportsSearchPerformer: AviasalesAirportsSearchPerformer!, didFailSearchingWithError error: Error!) {
}
}
| mit | 6b26002ee6a3b279bb025291b8c3526f | 33.824324 | 167 | 0.685552 | 4.574556 | false | false | false | false |
younata/RSSClient | Tethys/Articles/Reading an article/ArticleViewController.swift | 1 | 7186 | import UIKit
import PureLayout
import TOBrowserActivityKit
import TethysKit
import WebKit
import SafariServices
public final class ArticleViewController: UIViewController {
public let article: Article
public private(set) lazy var shareButton: UIBarButtonItem = {
let button = UIBarButtonItem(barButtonSystemItem: .action, target: self,
action: #selector(ArticleViewController.share))
button.accessibilityIdentifier = "ArticleViewController_ShareArticle"
button.accessibilityLabel = String.localizedStringWithFormat(
NSLocalizedString("ArticleViewController_Action_Accessibility_ShareArticle", comment: ""),
self.article.title
)
button.isAccessibilityElement = true
button.accessibilityTraits = [.button]
return button
}()
public private(set) lazy var openInSafariButton: UIBarButtonItem = {
let button = UIBarButtonItem(
title: NSLocalizedString("ArticleViewController_TabBar_OpenURL", comment: ""),
style: .plain,
target: self,
action: #selector(ArticleViewController.openInSafari)
)
button.accessibilityLabel = NSLocalizedString("ArticleViewController_Accessibility_TabBar_OpenURL", comment: "")
button.isAccessibilityElement = true
button.accessibilityTraits = [.button]
return button
}()
fileprivate let articleUseCase: ArticleUseCase
fileprivate let htmlViewController: HTMLViewController
public init(article: Article,
articleUseCase: ArticleUseCase,
htmlViewController: @escaping () -> HTMLViewController) {
self.article = article
self.articleUseCase = articleUseCase
self.htmlViewController = htmlViewController()
super.init(nibName: nil, bundle: nil)
self.htmlViewController.delegate = self
self.addChild(self.htmlViewController)
}
public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
fileprivate func showArticle(_ article: Article) {
self.htmlViewController.configure(html: self.articleUseCase.readArticle(article))
}
private func spacer() -> UIBarButtonItem {
return UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
}
public override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.htmlViewController.view)
self.htmlViewController.view.autoPinEdgesToSuperviewEdges()
self.updateLeftBarButtonItem(self.traitCollection)
self.toolbarItems = [
self.spacer(), self.shareButton, self.spacer(), self.openInSafariButton, self.spacer()
]
self.title = self.article.title
self.view.backgroundColor = Theme.backgroundColor
self.showArticle(self.article)
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.navigationController?.setToolbarHidden(false, animated: false)
self.navigationController?.hidesBarsOnSwipe = true
self.navigationController?.hidesBarsOnTap = true
self.splitViewController?.setNeedsStatusBarAppearanceUpdate()
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.hidesBarsOnSwipe = false
self.navigationController?.hidesBarsOnTap = false
}
private func updateLeftBarButtonItem(_ traitCollection: UITraitCollection) {
if traitCollection.horizontalSizeClass == .regular {
self.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
self.navigationItem.leftItemsSupplementBackButton = true
} else {
self.navigationItem.leftBarButtonItem = nil
}
}
public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.updateLeftBarButtonItem(self.traitCollection)
}
public override var canBecomeFirstResponder: Bool { return true }
public override var keyCommands: [UIKeyCommand]? {
let addTitleToCmd: (UIKeyCommand, String) -> Void = {cmd, title in
cmd.discoverabilityTitle = title
}
var commands: [UIKeyCommand] = []
let markAsRead = UIKeyCommand(input: "r", modifierFlags: .shift,
action: #selector(ArticleViewController.toggleArticleRead))
addTitleToCmd(markAsRead, NSLocalizedString("ArticleViewController_Command_ToggleRead", comment: ""))
commands.append(markAsRead)
let cmd = UIKeyCommand(input: "l", modifierFlags: .command,
action: #selector(ArticleViewController.openInSafari))
addTitleToCmd(cmd, NSLocalizedString("ArticleViewController_Command_OpenInWebView", comment: ""))
commands.append(cmd)
let showShareSheet = UIKeyCommand(input: "s", modifierFlags: .command,
action: #selector(ArticleViewController.share))
addTitleToCmd(showShareSheet, NSLocalizedString("ArticleViewController_Command_OpenShareSheet", comment: ""))
commands.append(showShareSheet)
return commands
}
@objc fileprivate func toggleArticleRead() {
self.articleUseCase.toggleArticleRead(self.article)
}
@objc fileprivate func share() {
let safari = TOActivitySafari()
let chrome = TOActivityChrome()
let activity = UIActivityViewController(
activityItems: [self.article.link],
applicationActivities: [safari, chrome]
)
activity.popoverPresentationController?.barButtonItem = self.shareButton
self.present(activity, animated: true, completion: nil)
}
@objc private func openInSafari() {
self.openURL(self.article.link)
}
fileprivate func openURL(_ url: URL) {
self.loadUrlInSafari(url)
}
private func loadUrlInSafari(_ url: URL) {
let safari = SFSafariViewController(url: url)
self.present(safari, animated: true, completion: nil)
}
}
extension ArticleViewController: HTMLViewControllerDelegate {
public func openURL(url: URL) -> Bool {
guard ["http", "https"].contains(url.scheme ?? "") else {
return false
}
self.openURL(url)
return true
}
public func peekURL(url: URL) -> UIViewController? {
let vc = SFSafariViewController(url: url)
vc.preferredControlTintColor = Theme.highlightColor
return vc
}
public func commitViewController(viewController: UIViewController) {
if viewController is SFSafariViewController {
viewController.popoverPresentationController?.sourceView = self.htmlViewController.view
self.present(viewController, animated: true, completion: nil)
} else {
self.navigationController?.pushViewController(viewController, animated: true)
}
}
}
| mit | 2942d1ccd80a436e6bd20230fa78865c | 37.223404 | 120 | 0.680768 | 5.570543 | false | false | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro | Parse Dashboard for iOS/Models/ParseLiteObject.swift | 1 | 4350 | //
// ParseLiteObject.swift
// Parse Dashboard for iOS
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 8/31/17.
//
import Foundation
import SwiftyJSON
import IGListKit
class ParseLiteObject: ListDiffable {
// MARK: - Properties
var id: String
var json: JSON
var createdAt = "createdAt: "
var updatedAt = "updatedAt: "
var schema: PFSchema?
var displayKey: String = .objectId
var keys: [String] {
if let schemaKeys = schema?.fields?.keys {
// Local object will not contain keys for values that are undefined/null
var keys = Array(schemaKeys)
if let index = keys.index(of: "className") {
keys.remove(at: index)
}
if let index = keys.index(of: "type") {
keys.remove(at: index)
}
keys = keys.sorted()
if let index = keys.index(of: .objectId) {
keys.insert(keys.remove(at: index), at: 0)
}
if let index = keys.index(of: .createdAt) {
keys.insert(keys.remove(at: index), at: 1)
}
if let index = keys.index(of: .updatedAt) {
keys.insert(keys.remove(at: index), at: 2)
}
if let index = keys.index(of: .acl) {
keys.append(keys.remove(at: index))
}
return keys
}
return Array(json.dictionaryValue.keys).sorted() // Fallback on local keys
}
// MARK: - Initialization
init(_ dictionary: [String : AnyObject], schema: PFSchema? = nil) {
self.schema = schema
json = JSON(dictionary)
id = (dictionary[.objectId] as? String) ?? .undefined
let createdAtString = (dictionary[.createdAt] as? String) ?? .undefined
let updatedAtString = (dictionary[.updatedAt] as? String) ?? .undefined
// Date Data Type
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let date = dateFormatter.date(from: createdAtString) {
createdAt += date.string(dateStyle: .medium, timeStyle: .short)
}
if let date = dateFormatter.date(from: updatedAtString) {
updatedAt += date.string(dateStyle: .medium, timeStyle: .short)
}
}
// MARK: - Methods
func value(forKey key: String) -> Any? {
return json.dictionaryObject?[key]
}
func displayValue() -> Any? {
return value(forKey: displayKey)
}
func diffIdentifier() -> NSObjectProtocol {
return id as NSObject
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
guard let lteObject = object as? ParseLiteObject else { return false }
return lteObject.id == id && lteObject.updatedAt == updatedAt
}
}
extension Array where Element:Equatable {
func removeDuplicates() -> [Element] {
var result = [Element]()
for value in self {
if result.contains(value) == false {
result.append(value)
}
}
return result
}
}
| mit | b7342c96ace0efa595be346dd99c5204 | 33.515873 | 84 | 0.609795 | 4.419715 | false | false | false | false |
pmark/MartianRover | Playgrounds/MyPlayground4a.playground/Contents.swift | 1 | 3581 | import Cocoa // (or UIKit for iOS)
import SceneKit
import QuartzCore // for the basic animation
import XCPlayground // for the live preview
// create a scene view with an empty scene
let sceneSize = 700
var sceneView = SCNView(frame: CGRect(x: 0, y: 0, width: sceneSize, height: sceneSize))
var scene = SCNScene()
sceneView.scene = scene
sceneView.backgroundColor = NSColor.darkGrayColor()
sceneView.autoenablesDefaultLighting = true
// start a live preview of that view
XCPShowView("The Scene View", sceneView)
/*
// a geometry object
var torus = SCNTorus(ringRadius: 3, pipeRadius: 1)
var torusNode = SCNNode(geometry: torus)
scene.rootNode.addChildNode(torusNode)
// configure the geometry object
torus.firstMaterial?.diffuse.contents = NSColor.yellowColor() // (or UIColor on iOS)
torus.firstMaterial?.specular.contents = NSColor.yellowColor() // (or UIColor on iOS)
// set a rotation axis (no angle) to be able to
// use a nicer keypath below and avoid needing
// to wrap it in an NSValue
torusNode.rotation = SCNVector4(x: 1.0, y: 0.0, z: 0.0, w: 0.0)
// animate the rotation of the torus
var spin = CABasicAnimation(keyPath: "rotation.w") // only animate the angle
spin.toValue = 2.0*M_PI
spin.duration = 1.5
spin.repeatCount = HUGE // for infinity
torusNode.addAnimation(spin, forKey: "spin around")
*/
let tileSize:CGFloat = 1.0
let duration:CFTimeInterval = 5
var colorToggle = false
for x in -4...3 {
colorToggle = (x % 2 == 0) ? true : false
for y in -4...3 {
var extra = CGFloat((abs(x)+abs(y))/3)
var cube = SCNBox(
width: tileSize/4,
height: tileSize,
length: tileSize+extra,
chamferRadius: 1)
var cubeNode = SCNNode(geometry: cube)
cubeNode.position.x = CGFloat(x * Int(tileSize*2) + 1);
cubeNode.position.y = CGFloat(y * Int(tileSize*2) + 1);
cubeNode.position.z = CGFloat(-extra*2.0);
cube.firstMaterial?.diffuse.contents = (colorToggle ? NSColor.blackColor() : NSColor.redColor())
cube.firstMaterial?.specular.contents = (colorToggle ? NSColor.redColor() : NSColor.whiteColor())
colorToggle = !colorToggle
cubeNode.rotation = SCNVector4(x: 1, y: 1, z: 0.0, w: 0.0)
// var spin = CABasicAnimation(keyPath: "rotation.w") // only animate the angle
// spin.fromValue = -M_PI*2.0
// spin.toValue = M_PI*2.0
// spin.duration = duration + CFTimeInterval(abs(x)+abs(y))
// spin.autoreverses = false
// spin.repeatCount = HUGE // for infinity
// cubeNode.addAnimation(spin, forKey: "spin around")
scene.rootNode.addChildNode(cubeNode)
}
}
// a camera
var camera = SCNCamera()
var cameraNode = SCNNode()
cameraNode.camera = camera
cameraNode.position = SCNVector3(
x: 0, y: 0, z: 15)
camera.automaticallyAdjustsZRange = true
scene.rootNode.addChildNode(cameraNode)
cameraNode.rotation = SCNVector4(
x: 0,
y: 0, z: -1.0, w: 0.0)
//var camspin = CABasicAnimation(keyPath: "rotation.w")
//camspin.fromValue = 0
//camspin.toValue = 2 * M_PI
//camspin.duration = duration*2
//camspin.autoreverses = false
//camspin.repeatCount = HUGE // for infinity
//cameraNode.addAnimation(camspin, forKey: "group")
//var fly = CABasicAnimation(keyPath: "position.z")
//fly.fromValue = 10
//fly.toValue = 20
//fly.duration = duration
//fly.autoreverses = true
//fly.repeatCount = HUGE // for infinity
//var g = CAAnimationGroup()
//g.animations = [camspin]
//cameraNode.addAnimation(g, forKey: "group")
| mit | 46c47b0717c4a9d4165e63a00615ff3a | 30.13913 | 105 | 0.671321 | 3.581 | false | false | false | false |
gali8/G8MaterialKitTextField | MKTextField/MKButton.swift | 1 | 3896 | //
// MKButton.swift
// MaterialKit
//
// Created by LeVan Nghia on 11/14/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
@IBDesignable
class MKButton : UIButton
{
@IBInspectable var maskEnabled: Bool = true {
didSet {
mkLayer.enableMask(maskEnabled)
}
}
@IBInspectable var rippleLocation: MKRippleLocation = .TapLocation {
didSet {
mkLayer.rippleLocation = rippleLocation
}
}
@IBInspectable var circleGrowRatioMax: Float = 0.9 {
didSet {
mkLayer.circleGrowRatioMax = circleGrowRatioMax
}
}
@IBInspectable var backgroundLayerCornerRadius: CGFloat = 0.0 {
didSet {
mkLayer.setBackgroundLayerCornerRadius(backgroundLayerCornerRadius)
}
}
// animations
@IBInspectable var shadowAniEnabled: Bool = true
@IBInspectable var backgroundAniEnabled: Bool = true {
didSet {
if !backgroundAniEnabled {
mkLayer.enableOnlyCircleLayer()
}
}
}
@IBInspectable var aniDuration: Float = 0.65
@IBInspectable var circleAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable var backgroundAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable var shadowAniTimingFunction: MKTimingFunction = .EaseOut
@IBInspectable var cornerRadius: CGFloat = 2.5 {
didSet {
layer.cornerRadius = cornerRadius
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
}
// color
@IBInspectable var circleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) {
didSet {
mkLayer.setCircleLayerColor(circleLayerColor)
}
}
@IBInspectable var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) {
didSet {
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
}
}
override var bounds: CGRect {
didSet {
mkLayer.superLayerDidResize()
}
}
private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer)
// MARK - initilization
override init(frame: CGRect) {
super.init(frame: frame)
setupLayer()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayer()
}
// MARK - setup methods
private func setupLayer() {
adjustsImageWhenHighlighted = false
self.cornerRadius = 2.5
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
mkLayer.setCircleLayerColor(circleLayerColor)
}
// MARK - location tracking methods
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
if rippleLocation == .TapLocation {
mkLayer.didChangeTapLocation(touch.locationInView(self))
}
// circleLayer animation
mkLayer.animateScaleForCircleLayer(0.45, toScale: 1.0, timingFunction: circleAniTimingFunction, duration: CFTimeInterval(aniDuration))
// backgroundLayer animation
if backgroundAniEnabled {
mkLayer.animateAlphaForBackgroundLayer(backgroundAniTimingFunction, duration: CFTimeInterval(aniDuration))
}
// shadow animation for self
if shadowAniEnabled {
let shadowRadius = self.layer.shadowRadius
let shadowOpacity = self.layer.shadowOpacity
//if mkType == .Flat {
// mkLayer.animateMaskLayerShadow()
//} else {
mkLayer.animateSuperLayerShadow(10, toRadius: shadowRadius, fromOpacity: 0, toOpacity: shadowOpacity, timingFunction: shadowAniTimingFunction, duration: CFTimeInterval(aniDuration))
//}
}
return super.beginTrackingWithTouch(touch, withEvent: event)
}
}
| mit | 42ab57de25380f55c9b201e992a4f54c | 31.466667 | 197 | 0.63655 | 5.336986 | false | false | false | false |
hfutrell/SmoothedParticleHydrodynamics | SmoothedParticleHydrodynamics/SmoothedParticleHydrodynamics/RegularGrid.swift | 1 | 6850 | //
// RegularGrid.swift
// SmoothedParticleHydrodynamics
//
// Created by Holmes Futrell on 8/26/16.
// Copyright © 2016 Holmes Futrell. All rights reserved.
//
import Foundation
protocol CellObjectProtocol {
var x: CGPoint { get }
}
internal class Cell<ObjectType> {
var count: Int = 0
var debugCount: Int = 0
var firstIndex: Int = 0
var objects: UnsafeMutablePointer<ObjectType> = nil // todo: remove, it's not strictly necessary to have this pointer
func insert(object: ObjectType) {
objects[count] = object
count += 1
}
}
class RegularGrid<ObjectType: CellObjectProtocol> {
let width: Double
let height: Double
let objects: UnsafeMutablePointer<ObjectType>
let objectData: NSData
var numObjects: Int
let maxObjects: Int
let cells: UnsafeMutablePointer<Cell<ObjectType>>
let cellData: NSData
let horizontalCells: Int
let verticalCells: Int
var numCells: Int {
return horizontalCells * verticalCells
}
let cellSize: Double
let cellStride: Int // offset to add per row when indexing into cells
required init(withWidth width: Double, height: Double, cellSize: Double, maxObjects: Int) {
assert(cellSize > 0)
self.width = width
self.height = height
self.cellSize = cellSize
self.horizontalCells = Int(ceil(width / cellSize))
self.verticalCells = Int(ceil(height / cellSize))
let numCells = self.horizontalCells * self.verticalCells
self.cellStride = self.horizontalCells
self.objectData = NSMutableData(length: sizeof(ObjectType) * maxObjects )! // zero-filled per documentation
self.objects = UnsafeMutablePointer<ObjectType>(objectData.bytes)
self.cellData = NSMutableData(length: sizeof(Cell<ObjectType>) * numCells )! // zero-filled per documentation
self.cells = UnsafeMutablePointer<Cell<ObjectType>>(cellData.bytes)
self.numObjects = 0
self.maxObjects = maxObjects
}
func cell(atLocation location: CGPoint) -> Cell<ObjectType> {
assert((Double(location.x) >= 0) && (Double(location.x) <= self.width))
assert((Double(location.y) >= 0) && (Double(location.y) <= self.height))
let horizontalIndex: Int = Int(floor(Double(location.x) / cellSize))
let verticalIndex: Int = Int(floor(Double(location.y) / cellSize))
return self.cell(atHorizontalIndex: horizontalIndex, verticalIndex: verticalIndex)
}
func cell(atHorizontalIndex horizontalIndex: Int, verticalIndex: Int) -> Cell<ObjectType> {
assert(horizontalIndex >= 0 && horizontalIndex < self.horizontalCells)
assert(verticalIndex >= 0 && verticalIndex < self.verticalCells)
let index = verticalIndex * self.cellStride + horizontalIndex
return self.cells[index]
}
func setObjects(objects: UnsafePointer<ObjectType>, count: Int) {
assert(count < self.maxObjects && objects != nil)
// step 0: reset cells completely
for i in 0..<self.numCells {
cells[i] = Cell<ObjectType>()
}
// step 1: update counts for all cells
for i in 0..<count {
let object = objects[i]
let cell = self.cell(atLocation: object.x)
cell.count += 1
cell.debugCount += 1
}
// step 2: use counts to allocate memory for cells and reset counts
var numObjectsSoFar: Int = 0
for i in 0..<self.numCells {
cells[i].objects = self.objects + numObjectsSoFar // pointer arithmetic
cells[i].firstIndex = numObjectsSoFar
numObjectsSoFar += cells[i].count
cells[i].count = 0 // we have to reset this because cell.insert uses it to determine what index to use when inserting
}
// step 3: insert objects
for i in 0..<count {
let object = objects[i]
let cell = self.cell(atLocation: object.x)
cell.insert(object)
}
// step 4: update object count
self.numObjects = numObjectsSoFar
}
// todo: copy object list function
func runFunction(callback: (index: Int, object: ObjectType) ->Void) {
for i in 0..<self.numObjects {
callback(index: i, object: self.objects[i])
}
}
func runPairwiseSpatialFunction(callback: (index1: Int, index2: Int, inout object1: ObjectType, inout object2: ObjectType ) -> Void, maxDistance: Double) {
let cellsToCheck: Int = Int(ceil(maxDistance / self.cellSize))
for objectIndex1 in 0..<self.numObjects {
var object1: ObjectType = self.objects[objectIndex1]
let horizontalCellIndex: Int = Int(floor(Double(object1.x.x) / cellSize))
let verticalCellIndex: Int = Int(floor(Double(object1.x.y) / cellSize))
let minL = (horizontalCellIndex - cellsToCheck) < 0 ? 0 : (horizontalCellIndex - cellsToCheck)
let maxL = (horizontalCellIndex + cellsToCheck) > (self.horizontalCells - 1) ? (self.horizontalCells - 1) : (horizontalCellIndex + cellsToCheck)
// check the cells above (and equal row)
// these have object indices that are less than or equal to object1 cell's object indices
// when we compare the two objects may actually be in the same cell
// in this case we take care to ensure that object2's index is less than object1's
let minK = (verticalCellIndex - cellsToCheck) < 0 ? 0 : (verticalCellIndex - cellsToCheck)
let maxK = verticalCellIndex
for k in minK ..< maxK {
let firstCell = self.cell(atHorizontalIndex: minL, verticalIndex: k)
let lastCell = self.cell(atHorizontalIndex: maxL, verticalIndex: k)
for objectIndex2 in firstCell.firstIndex..<(lastCell.firstIndex+lastCell.count) {
var object2 : ObjectType = self.objects[objectIndex2]
callback(index1: objectIndex1, index2: objectIndex2, object1: &object1, object2: &object2)
}
}
// special handling of row with k = maxK = verticalCellIndex, where early exit of loop is required to ensure objectIndex2 < objectIndex1
let firstCell = self.cell(atHorizontalIndex: minL, verticalIndex: verticalCellIndex)
for objectIndex2 in firstCell.firstIndex..<objectIndex1 {
var object2 : ObjectType = self.objects[objectIndex2]
callback(index1: objectIndex1, index2: objectIndex2, object1: &object1, object2: &object2)
}
} // end objectIndex1
}
} | mit | c0babef7d27a16575b17846fbf81af6f | 39.294118 | 159 | 0.625931 | 4.464798 | false | false | false | false |
exsortis/PnutKit | Sources/PnutKit/Models/Channel.swift | 1 | 2891 | import Foundation
private let dateFormatter = ISO8601DateFormatter()
public struct Channel {
public var createdAt : Date
public var id : String
public var isActive : Bool
public var type : String
public var owner : User
public var recentMessageId : String?
public var recentMessage : Message?
public var acl : ACL
public var counts : Counts
public var youSubscribed : Bool
public var youMuted : Bool
public var hasUnread : Bool
public struct Counts {
public var messages : Int
public var subscribers : Int
}
}
extension Channel : Serializable {
public init?(from dict : JSONDictionary) {
guard let createdAtStr = dict["created_at"] as? String,
let createdAt = dateFormatter.date(from: createdAtStr),
let id = dict["id"] as? String,
let type = dict["type"] as? String,
let aclDict = dict["acl"] as? [String : Any],
let acl = ACL(from: aclDict),
let counts = dict["counts"] as? [String : Int],
let messagesCount = counts["messages"],
let subscribersCount = counts["subscribers"],
let youSubscribed = dict["you_subscribed"] as? Bool,
let youMuted = dict["you_muted"] as? Bool,
let hasUnread = dict["has_unread"] as? Bool
else { return nil }
self.createdAt = createdAt
self.id = id
self.isActive = dict["is_active"] as? Bool ?? false
self.type = type
self.owner = User(from: dict["owner"] as? [String: Any] ?? [:]) ?? .deleted
self.recentMessageId = dict["recent_message_id"] as? String
self.recentMessage = Message(from: dict["recent_message"] as? [String : Any] ?? [:])
self.acl = acl
self.counts = Counts(messages: messagesCount,
subscribers: subscribersCount)
self.youSubscribed = youSubscribed
self.youMuted = youMuted
self.hasUnread = hasUnread
}
public func toDictionary() -> JSONDictionary {
var dict : JSONDictionary = [
"created_at" : dateFormatter.string(from: createdAt),
"id" : id,
"is_active" : isActive,
"type" : type,
"owner" : owner.toDictionary(),
"acl" : acl.toDictionary(),
"counts" : [
"messages" : counts.messages,
"subscribers" : counts.subscribers,
],
"you_subscribed" : youSubscribed,
"you_muted" : youMuted,
"has_unread" : hasUnread,
]
if let recentMessageId = recentMessageId {
dict["recent_message_id"] = recentMessageId
}
if let recentMessage = recentMessage {
dict["recent_message"] = recentMessage.toDictionary()
}
return dict
}
}
| mit | e8d58a02101d95c1dd92816bcca51820 | 32.616279 | 92 | 0.569699 | 4.588889 | false | false | false | false |
liuchuo/LeetCode-practice | Swift/206. Reverse Linked List.swift | 1 | 315 | // 206. Reverse Linked List
// 20 ms, 63.85%
func reverseList(_ head: ListNode?) -> ListNode? {
var stack = [Int](), p = head
while let t = p {
stack.append(t.val)
p = t.next
}
p = head
while let t = p {
t.val = stack.popLast()!
p = t.next
}
return head
} | gpl-3.0 | bb2995761e878851a49d55c07098f166 | 20.066667 | 50 | 0.498413 | 3.315789 | false | false | false | false |
calkinssean/TIY-Assignments | Day 39/matchbox20FanClub/matchbox20FanClub/MenuController.swift | 1 | 3283 | //
// MenuController.swift
// matchbox20FanClub
//
// Created by Sean Calkins on 3/25/16.
// Copyright © 2016 Sean Calkins. All rights reserved.
//
import UIKit
import Firebase
class MenuController: UITableViewController {
let ref = Firebase(url: "https://matchbox20fanclub.firebaseio.com")
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 3 {
ref.unauth()
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
// MARK: - Table view data source
// override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// // #warning Incomplete implementation, return the number of rows
// return 0
// }
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| cc0-1.0 | 887dc02660f89c83e5be87c3d37ab8f6 | 32.489796 | 157 | 0.678245 | 5.442786 | false | false | false | false |
kinyong/KYWeiboDemo-Swfit | AYWeibo/AYWeibo/classes/Tools/progress/KYProgressImgView.swift | 1 | 967 | //
// KYProgressImgView.swift
// demo
//
// Created by Kinyong on 16/7/12.
// Copyright © 2016年 Ayong. All rights reserved.
//
import UIKit
class KYProgressImgView: UIImageView {
private lazy var progressView: KYProgressView = KYProgressView()
/// 下载进度值,0.0 ~ 1.0
var progress: CGFloat = 0 {
didSet{
progressView.progress = progress
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
override func layoutSubviews() {
progressView.frame = self.bounds
}
private func setupUI() {
self.addSubview(progressView)
progressView.frame = self.bounds
progressView.backgroundColor = UIColor.clearColor()
}
func setProgressHidden(bool: Bool){
progressView.hidden = bool
}
}
| apache-2.0 | 1af7d58fd7aec71fb34e91e6098db36c | 20.636364 | 68 | 0.602941 | 4.327273 | false | false | false | false |
Great-Li-Xin/Xcode | Concentration/Concentration/ViewController.swift | 1 | 1547 | //
// ViewController.swift
// Concentration
//
// Created by Justin Dell Adam on 1/15/18.
// Copyright © 2018 Li Xin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var flipCount = 0 {
didSet {
flipCountLabel.text = "Flips: \(flipCount)"
}
}
@IBOutlet weak var flipCountLabel: UILabel!
@IBOutlet var cardButtons: [UIButton]!
var emojiChoices = ["🎃","👻","🎃","👻"]
@IBAction func touchCard(_ sender: UIButton) {
flipCount += 1
if let cardNumber = cardButtons.index(of: sender) {
flipCard(withEmoji: emojiChoices[cardNumber], on: sender)
} else {
print("Chosen card was not in cardButtons")
}
}
func flipCard(withEmoji emoji:String, on button:UIButton) {
if button.currentTitle == emoji {
button.setTitle("", for: UIControlState.normal)
button.backgroundColor = #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1)
} else {
button.setTitle(emoji, for: UIControlState.normal)
button.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
}
}
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.
}
}
| mit | 098cb082ebc8ab11997ae13377894b64 | 26.392857 | 98 | 0.599087 | 4.225895 | false | false | false | false |
lorentey/GlueKit | Sources/UpdatableValue.swift | 1 | 5986 | //
// Updatable.swift
// GlueKit
//
// Created by Károly Lőrentey on 2015-12-07.
// Copyright © 2015–2017 Károly Lőrentey.
//
/// An observable thing that also includes support for updating its value.
public protocol UpdatableValueType: ObservableValueType, UpdatableType {
/// Returns the type-erased version of this UpdatableValueType.
var anyUpdatableValue: AnyUpdatableValue<Value> { get }
}
extension UpdatableValueType {
/// Returns the type-erased version of this UpdatableValueType.
public var anyUpdatableValue: AnyUpdatableValue<Value> {
return AnyUpdatableValue(self)
}
}
/// The type erased representation of an UpdatableValueType.
public struct AnyUpdatableValue<Value>: UpdatableValueType {
public typealias Change = ValueChange<Value>
private let box: _AbstractUpdatableValue<Value>
init(box: _AbstractUpdatableValue<Value>) {
self.box = box
}
public init<Updates: SourceType>(getter: @escaping () -> Value,
apply: @escaping (Update<ValueChange<Value>>) -> Void,
updates: Updates)
where Updates.Value == Update<Change> {
self.box = UpdatableClosureBox(getter: getter,
apply: apply,
updates: updates)
}
public init<Base: UpdatableValueType>(_ base: Base) where Base.Value == Value {
self.box = UpdatableBox(base)
}
public var value: Value {
get { return box.value }
nonmutating set { box.value = newValue }
}
public func apply(_ update: Update<Change>) {
box.apply(update)
}
public func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Update<Change> {
box.add(sink)
}
@discardableResult
public func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Update<Change> {
return box.remove(sink)
}
public var anyObservableValue: AnyObservableValue<Value> {
return box.anyObservableValue
}
public var anyUpdatableValue: AnyUpdatableValue<Value> {
return self
}
}
open class _AbstractUpdatableValue<Value>: _AbstractObservableValue<Value>, UpdatableValueType {
public typealias Change = ValueChange<Value>
open override var value: Value {
get { abstract() }
set { abstract() }
}
open func apply(_ update: Update<Change>) { abstract() }
public final var anyUpdatableValue: AnyUpdatableValue<Value> { return AnyUpdatableValue(box: self) }
}
open class _BaseUpdatableValue<Value>: _AbstractUpdatableValue<Value>, TransactionalThing {
var _signal: TransactionalSignal<ValueChange<Value>>? = nil
var _transactionCount = 0
func rawGetValue() -> Value { abstract() }
func rawSetValue(_ value: Value) { abstract() }
public final override func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Update<Change> {
signal.add(sink)
}
@discardableResult
public final override func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Update<Change> {
return signal.remove(sink)
}
public final override var value: Value {
get {
return rawGetValue()
}
set {
beginTransaction()
let old = rawGetValue()
rawSetValue(newValue)
sendChange(ValueChange(from: old, to: newValue))
endTransaction()
}
}
public final override func apply(_ update: Update<Change>) {
switch update {
case .beginTransaction:
beginTransaction()
case .change(let change):
rawSetValue(change.new)
sendChange(change)
case .endTransaction:
endTransaction()
}
}
open func activate() {
// Do nothing
}
open func deactivate() {
// Do nothing
}
}
internal final class UpdatableBox<Base: UpdatableValueType>: _AbstractUpdatableValue<Base.Value> {
typealias Value = Base.Value
private let base: Base
init(_ base: Base) {
self.base = base
}
override var value: Value {
get { return base.value }
set { base.value = newValue }
}
override func apply(_ update: Update<ValueChange<Value>>) {
base.apply(update)
}
override func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Update<Change> {
base.add(sink)
}
@discardableResult
override func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Update<Change> {
return base.remove(sink)
}
}
private final class UpdatableClosureBox<Value, Updates: SourceType>: _AbstractUpdatableValue<Value>
where Updates.Value == Update<ValueChange<Value>> {
/// The getter closure for the current value of this updatable.
private let _getter: () -> Value
private let _apply: (Update<ValueChange<Value>>) -> Void
/// A closure returning a source providing the values of future updates to this updatable.
private let _updates: Updates
public init(getter: @escaping () -> Value,
apply: @escaping (Update<ValueChange<Value>>) -> Void,
updates: Updates) {
self._getter = getter
self._apply = apply
self._updates = updates
}
override var value: Value {
get { return _getter() }
set {
_apply(.beginTransaction)
_apply(.change(ValueChange(from: _getter(), to: newValue)))
_apply(.endTransaction)
}
}
override func apply(_ update: Update<ValueChange<Value>>) {
_apply(update)
}
override func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Update<Change> {
_updates.add(sink)
}
@discardableResult
override func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Update<Change> {
return _updates.remove(sink)
}
}
| mit | 4e84c2e1e81c4b403fb1a974a0e07c01 | 29.19697 | 112 | 0.622679 | 4.553694 | false | false | false | false |
symentis/Corridor | CorridorDemo.playground/Pages/Test.xcplaygroundpage/Sources/Context.swift | 1 | 1505 | import Foundation
import UIKit
import Corridor
// ------------------------------------------------------
// MARK: - Protocol for Context
// ------------------------------------------------------
public protocol AppContext {
var now: Date { get }
}
// ------------------------------------------------------
// MARK: - Default implementation for Context
// ------------------------------------------------------
struct DefaultContext: AppContext {
var now: Date { return Date() }
}
// ------------------------------------------------------
// MARK: - General Resolver for base protocol HasContext
// ------------------------------------------------------
public extension HasContext {
typealias Context = AppContext
static var `default`: Resolver<Self, AppContext> {
return Resolver(context: DefaultContext())
}
}
// ------------------------------------------------------
// MARK: - Actual resolving
// ------------------------------------------------------
protocol ContextAware: HasInstanceContext where Self.Context == AppContext {}
extension ContextAware {
var now: Date {
return resolve[\.now]
}
}
// ------------------------------------------------------
// MARK: - App Usage
// ------------------------------------------------------
public final class Controller: LabelController, ContextAware {
public var resolve = `default`
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
label.text = "Now is \(now)"
}
}
| mit | 31fdb82538df71bca24ee2f45c011a46 | 24.083333 | 77 | 0.437874 | 5.657895 | false | false | false | false |
TrustWallet/trust-wallet-ios | Trust/Lock/Lock.swift | 1 | 4426 | // Copyright DApps Platform Inc. All rights reserved.
import UIKit
import SAMKeychain
import KeychainSwift
protocol LockInterface {
func isPasscodeSet() -> Bool
func shouldShowProtection() -> Bool
}
final class Lock: LockInterface {
private struct Keys {
static let service = "trust.lock"
static let account = "trust.account"
}
private let passcodeAttempts = "passcodeAttempts"
private let maxAttemptTime = "maxAttemptTime"
private let autoLockType = "autoLockType"
private let autoLockTime = "autoLockTime"
private let keychain: KeychainSwift
init(keychain: KeychainSwift = KeychainSwift(keyPrefix: Constants.keychainKeyPrefix)) {
self.keychain = keychain
}
func shouldShowProtection() -> Bool {
return isPasscodeSet() && autoLockTriggered()
}
func isPasscodeSet() -> Bool {
return currentPasscode() != nil
}
func currentPasscode() -> String? {
return SAMKeychain.password(forService: Keys.service, account: Keys.account)
}
func isPasscodeValid(passcode: String) -> Bool {
return passcode == currentPasscode()
}
func setAutoLockType(type: AutoLock) {
keychain.set(String(type.rawValue), forKey: autoLockType)
}
func getAutoLockType() -> AutoLock {
let id = keychain.get(autoLockType)
guard let type = id, let intType = Int(type), let autoLock = AutoLock(rawValue: intType) else {
return .immediate
}
return autoLock
}
func setAutoLockTime() {
guard isPasscodeSet(), keychain.get(autoLockTime) == nil else { return }
let timeString = dateFormatter().string(from: Date())
keychain.set(timeString, forKey: autoLockTime)
}
func getAutoLockTime() -> Date {
guard let timeString = keychain.get(autoLockTime), let time = dateFormatter().date(from: timeString) else {
return Date()
}
return time
}
func setPasscode(passcode: String) {
SAMKeychain.setPassword(passcode, forService: Keys.service, account: Keys.account)
}
func deletePasscode() {
SAMKeychain.deletePassword(forService: Keys.service, account: Keys.account)
resetPasscodeAttemptHistory()
setAutoLockType(type: AutoLock.immediate)
}
func numberOfAttempts() -> Int {
guard let attempts = keychain.get(passcodeAttempts) else {
return 0
}
return Int(attempts)!
}
func resetPasscodeAttemptHistory() {
keychain.delete(passcodeAttempts)
}
func recordIncorrectPasscodeAttempt() {
var numberOfAttemptsSoFar = numberOfAttempts()
numberOfAttemptsSoFar += 1
keychain.set(String(numberOfAttemptsSoFar), forKey: passcodeAttempts)
}
func recordedMaxAttemptTime() -> Date? {
guard let timeString = keychain.get(maxAttemptTime) else {
return nil
}
return dateFormatter().date(from: timeString)
}
func incorrectMaxAttemptTimeIsSet() -> Bool {
guard let timeString = keychain.get(maxAttemptTime), !timeString.isEmpty else {
return false
}
return true
}
func recordIncorrectMaxAttemptTime() {
let timeString = dateFormatter().string(from: Date())
keychain.set(timeString, forKey: maxAttemptTime)
}
func removeIncorrectMaxAttemptTime() {
keychain.delete(maxAttemptTime)
}
func removeAutoLockTime() {
keychain.delete(autoLockTime)
}
private func dateFormatter() -> DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = DateFormatter.Style.short
dateFormatter.timeStyle = DateFormatter.Style.medium
return dateFormatter
}
private func autoLockTriggered() -> Bool {
let type = getAutoLockType()
switch type {
case .immediate:
return true
default:
return timeOutInterval(for: type)
}
}
private func timeOutInterval(for type: AutoLock) -> Bool {
let elapsed = Date().timeIntervalSince(getAutoLockTime())
let intervalPassed = Int(elapsed) >= type.interval
return intervalPassed
}
func clear() {
deletePasscode()
resetPasscodeAttemptHistory()
removeIncorrectMaxAttemptTime()
removeAutoLockTime()
}
}
| gpl-3.0 | e59957c0c0e6d18342d4dd88fbfe883b | 27.928105 | 115 | 0.647763 | 4.748927 | false | false | false | false |
BitGo/keytool-ios | KeyTool/KeyTool/ConfirmViewController.swift | 1 | 5511 | //
// ConfirmViewController.swift
// KeyTool
//
// Created by Huang Yu on 7/29/15.
// Copyright (c) 2015 BitGo, Inc. All rights reserved.
//
import UIKit
class ConfirmViewController: KeyToolViewController, UITextViewDelegate, UIAlertViewDelegate {
@IBOutlet var mnemonicView: BitGoTextView!
@IBOutlet var bottomLayoutConstraint: NSLayoutConstraint!
var words: [String]!
override func viewDidLoad() {
super.viewDidLoad()
self.mnemonicView.delegate = self
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "keyboardWillShowNotification:",
name: UIKeyboardWillShowNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "keyboardWillHideNotification:",
name: UIKeyboardWillHideNotification,
object: nil)
self.mnemonicView.becomeFirstResponder()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self,
name: UIKeyboardWillShowNotification,
object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self,
name: UIKeyboardWillHideNotification,
object: nil)
}
@IBAction func pressStartOver(sender: AnyObject) {
UIAlertView(type: .StartOver, delegate: self).show()
self.mnemonicView.becomeFirstResponder()
}
@IBAction func confirmKey(sender: AnyObject) {
if self.mnemonicView.text.lowercaseString != KeyInfoManager.sharedManager.keyInfo.mnemonicString() {
self.mnemonicView.borderColor = UIColor.redColor()
UIAlertView(type: .IncorrectPhrase, delegate: self).show()
return
}
self.performSegueWithIdentifier("showSuccessViewControllerSegue", sender: self)
}
@IBOutlet var confirmButton: UIButton!
// MARK: - TextViewDelegate
func textViewDidChange(textView: UITextView) {
var mnString = KeyInfoManager.sharedManager.keyInfo.mnemonicString()
if mnString.hasPrefix(textView.text.lowercaseString) {
self.mnemonicView.borderColor = BitGoGreenColor
} else {
textView.layer.borderColor = UIColor.redColor().CGColor
}
}
func textView(
textView: UITextView,
shouldChangeTextInRange range: NSRange,
replacementText text: String) -> Bool
{
if text == "\n" {
if textView.text == KeyInfoManager.sharedManager.keyInfo.mnemonicString() {
self.performSegueWithIdentifier("showSuccessViewControllerSegue", sender: self)
} else {
textView.resignFirstResponder()
}
return false
}
return true
}
// MARK: - UIAlertViewDelegate
override func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if alertView.title == AlertTitle.StartOver.rawValue {
if buttonIndex == 1 {
// a hack to prevent keyboard glitch, which happens after this VC is dismissed
var delay = dispatch_time(DISPATCH_TIME_NOW, Int64(500 * Double(NSEC_PER_MSEC)))
dispatch_after(delay, dispatch_get_main_queue(), { () -> Void in
self.performSegueWithIdentifier(
"backToRootViewControllerFromConfirmSegue",
sender: self
)
})
} else {
self.mnemonicView.becomeFirstResponder()
}
} else if alertView.title == AlertTitle.IncorrectPhrase.rawValue {
self.mnemonicView.becomeFirstResponder()
} else {
super.alertView(alertView, clickedButtonAtIndex: buttonIndex)
}
}
// MARK: - Notifications
func keyboardWillShowNotification(notification: NSNotification) {
updateBottomLayoutConstraintWithNotification(notification)
}
func keyboardWillHideNotification(notification: NSNotification) {
updateBottomLayoutConstraintWithNotification(notification)
}
// MARK: - Private
func updateBottomLayoutConstraintWithNotification(notification: NSNotification) {
let userInfo = notification.userInfo!
let animationDuration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let keyboardEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let convertedKeyboardEndFrame = view.convertRect(keyboardEndFrame, fromView: view.window)
let rawAnimationCurve = (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).unsignedIntValue << 16
let animationCurve = UIViewAnimationOptions(rawValue: UInt(rawAnimationCurve))
bottomLayoutConstraint.constant = CGRectGetMaxY(view.bounds) - CGRectGetMinY(convertedKeyboardEndFrame) + 20
UIView.animateWithDuration(animationDuration, delay: 0.0, options: .BeginFromCurrentState | animationCurve, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
}
| apache-2.0 | 857ed601e9dc32c9d456981b98baf2b9 | 36.746575 | 129 | 0.65342 | 5.770681 | false | false | false | false |
enze0923/SwiftHYH | SwiftHaiyinhui/AppDelegate.swift | 1 | 2858 | //
// AppDelegate.swift
// SwiftHaiyinhui
//
// Created by HaiyinEnze on 2016/10/25.
// Copyright © 2016年 ENZE. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UITabBarControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
if !UserDefaults.standard.bool(forKey: EZFirstLaunch) {
window?.rootViewController = EZGuidePageViewController()
UserDefaults.standard.set(true, forKey: EZFirstLaunch)
} else {
let tabbar = EZTabBarViewController()
tabbar.delegate = self
window?.rootViewController = tabbar
}
window?.makeKeyAndVisible()
return true
}
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | a956dda8e8d83c7166f00eaefe64ff18 | 42.257576 | 285 | 0.714186 | 5.598039 | false | false | false | false |
eocleo/AlbumCore | AlbumDemo/AlbumDemo/AlbumViews/views/NoDataOverlayerView.swift | 1 | 1088 | //
// NoDataOverlayerView.swift
// FileMail
//
// Created by leo on 2017/5/27.
// Copyright © 2017年 leo. All rights reserved.
//
import UIKit
class NoDataOverlayerView: OverlayerView {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var descriptionLabel: UILabel!
static func createWith(image: UIImage?, message: String?) -> NoDataOverlayerView? {
let overlayerView: NoDataOverlayerView? = Bundle.main.loadNibNamed("NoDataOverlayerView", owner: nil , options: nil)?.first as? NoDataOverlayerView
overlayerView?.setup(image: image, message: message)
if (overlayerView == nil) {
AlbumDebug("NoDataOverlayerView 创建失败")
}
return overlayerView
}
func setup(image: UIImage?, message: String?) -> Void {
self.imageView.image = image
self.descriptionLabel.text = message
}
override func awakeFromNib() {
super.awakeFromNib()
AlbumDebug("\(String(describing: imageView.image)),\(String(describing: descriptionLabel.text))")
}
}
| mit | af95b85db50f548d4b7bdbccea876e9c | 28.916667 | 155 | 0.662024 | 4.378049 | false | false | false | false |
remlostime/one | one/one/ViewControllers/CommentViewController.swift | 1 | 13696 | //
// CommentViewController.swift
// one
//
// Created by Kai Chen on 1/9/17.
// Copyright © 2017 Kai Chen. All rights reserved.
//
import UIKit
import Parse
import MJRefresh
import ActiveLabel
class CommentViewController: UIViewController {
@IBOutlet var commentTextField: UITextField!
@IBOutlet var postButton: UIButton!
@IBOutlet var commentsTableView: UITableView!
@IBOutlet var commentsView: UIView!
var postUsername: String?
var postUUID: String?
let countOfCommentsPerPage: Int32 = 15
var refreher: UIRefreshControl?
var commentModels: [CommentViewCellModel] = [CommentViewCellModel]()
@IBAction func usernameButtonTapped(_ sender: UIButton) {
let username = sender.title(for: .normal)
let homeVC = self.storyboard?.instantiateViewController(withIdentifier: Identifier.profileViewController.rawValue) as? ProfileViewController
homeVC?.userid = username
self.navigationController?.pushViewController(homeVC!, animated: true)
}
@IBAction func postButtonTapped(_ sender: UIButton) {
sendComment()
}
func sendComment() {
let comment = PFObject(className: Comments.modelName.rawValue)
let commentModel = CommentViewCellModel()
commentModel.comments = commentTextField.text
commentModel.username = PFUser.current()?.username
commentModel.createdTime = Date()
commentModel.uuid = UUID().uuidString
self.commentModels.append(commentModel)
commentsTableView.reloadData()
comment[Comments.comment.rawValue] = commentTextField.text
comment[Comments.username.rawValue] = PFUser.current()?.username
comment[Comments.post_uuid.rawValue] = postUUID
comment[Comments.uuid.rawValue] = commentModel.uuid
comment.saveEventually()
let notification = PFObject(className: Notifications.modelName.rawValue)
notification[Notifications.sender.rawValue] = PFUser.current()?.username!
notification[Notifications.receiver.rawValue] = postUsername!
notification[Notifications.action.rawValue] = NotificationsAction.comment.rawValue
notification.saveEventually()
let text: [String] = (commentTextField.text?.components(separatedBy: CharacterSet.whitespacesAndNewlines))!
for word in text {
if word.hasPrefix("#") {
let object = PFObject(className: Hashtag.modelName.rawValue)
let startIndex = word.index(word.startIndex, offsetBy: 1)
object[Hashtag.hashtag.rawValue] = word.substring(from: startIndex)
object[Hashtag.username.rawValue] = PFUser.current()?.username!
object[Hashtag.postid.rawValue] = postUUID!
object[Hashtag.commentid.rawValue] = commentModel.uuid
object.saveEventually()
}
if word.hasPrefix("@") {
let notification = PFObject(className: Notifications.modelName.rawValue)
notification[Notifications.sender.rawValue] = PFUser.current()?.username!
let index = word.index(word.startIndex, offsetBy: 1)
notification[Notifications.receiver.rawValue] = word.substring(from: index)
notification[Notifications.action.rawValue] = NotificationsAction.mention.rawValue
notification.saveEventually()
}
}
commentTextField.text = nil
}
override func viewDidLoad() {
super.viewDidLoad()
commentTextField.delegate = self
commentsTableView.delegate = self
commentsTableView.dataSource = self
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(endEditing))
commentsTableView.addGestureRecognizer(tapGesture)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name:.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDismiss(notification:)), name: .UIKeyboardWillHide, object: nil)
loadComments()
}
func endEditing() {
commentTextField.endEditing(true)
}
func keyboardWillShow(notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
UIView.animate(withDuration: 0.4, animations: { [weak self]() -> Void in
guard let strongSelf = self else {
return
}
var frame = strongSelf.commentsTableView.frame
frame.size.height = frame.size.height - keyboardSize.height
strongSelf.commentsTableView.frame = frame
var commentViewFrame = strongSelf.commentsView.frame
commentViewFrame.origin.y = frame.height
strongSelf.commentsView.frame = commentViewFrame
})
}
}
func keyboardWillDismiss(notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
UIView.animate(withDuration: 0.4, animations: { [weak self]() -> Void in
guard let strongSelf = self else {
return
}
var frame = strongSelf.commentsTableView.frame
frame.size.height = frame.size.height + keyboardSize.height
strongSelf.commentsTableView.frame = frame
})
}
}
func loadComments() {
let countQuery = PFQuery(className: Comments.modelName.rawValue)
countQuery.whereKey(Comments.post_uuid.rawValue, equalTo: postUUID!)
countQuery.countObjectsInBackground { [weak self](count: Int32, error: Error?) in
guard let strongSelf = self else {
return
}
// if strongSelf.countOfCommentsPerPage < count {
// strongSelf.refreher?.addTarget(self, action: #selector(loadMoreComments), for: .valueChanged)
// strongSelf.commentsTableView.addSubview(strongSelf.refreher!)
// }
let query = PFQuery(className: Comments.modelName.rawValue)
query.whereKey(Comments.post_uuid.rawValue, equalTo: strongSelf.postUUID!)
// query.skip = count - strongSelf.countOfCommentsPerPage
query.addAscendingOrder("createdAt")
query.findObjectsInBackground(block: { [weak self](objects: [PFObject]?, error: Error?) in
guard let strongSelf = self else {
return
}
if error == nil {
for object in objects! {
let model = CommentViewCellModel()
model.username = object.object(forKey: Comments.username.rawValue) as! String?
model.comments = object.object(forKey: Comments.comment.rawValue) as! String?
model.createdTime = object.createdAt
strongSelf.commentModels.append(model)
}
strongSelf.commentsTableView.reloadData()
}
})
}
}
}
extension CommentViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
var actions = [UITableViewRowAction]()
let username = commentModels[indexPath.row].username
// TODO: Add If the the post belong to current user, user can delete comment
if username == PFUser.current()?.username {
actions.append(delete())
}
if username != PFUser.current()?.username {
actions.append(reply())
actions.append(complain())
}
return actions
}
func complain() -> UITableViewRowAction {
let complainAction = UITableViewRowAction(style: .normal, title: "Complain", handler: {(action: UITableViewRowAction, indexPath: IndexPath) in })
// TODO: Add complain logic
return complainAction
}
func reply() -> UITableViewRowAction {
let replyAction = UITableViewRowAction(style: .normal, title: "Reply", handler: { [weak self](action: UITableViewRowAction, indexPath: IndexPath) in
guard let strongSelf = self else {
return
}
let model = strongSelf.commentModels[indexPath.row]
strongSelf.commentTextField.text = strongSelf.commentTextField.text! + "@" + model.username!
})
return replyAction
}
func delete() -> UITableViewRowAction {
let deleteAction = UITableViewRowAction(style: .normal, title: "Delete", handler: { [weak self](action: UITableViewRowAction, indexPath: IndexPath) in
guard let strongSelf = self else {
return
}
let model = strongSelf.commentModels[indexPath.row]
let query = PFQuery(className: Comments.modelName.rawValue)
query.whereKey(Comments.post_uuid.rawValue, equalTo: strongSelf.postUUID!)
query.whereKey(Comments.username.rawValue, equalTo: model.username!)
query.whereKey(Comments.comment.rawValue, equalTo: model.comments!)
query.whereKey(Comments.uuid.rawValue, equalTo: model.uuid!)
query.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in
guard let object = objects?.first else {
return
}
object.deleteEventually()
})
strongSelf.commentModels.remove(at: indexPath.row)
strongSelf.commentsTableView.deleteRows(at: [indexPath], with: .automatic)
let hashtagQuery = PFQuery(className: Hashtag.modelName.rawValue)
hashtagQuery.whereKey(Hashtag.commentid.rawValue, equalTo: model.uuid!)
hashtagQuery.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in
for object in objects! {
object.deleteEventually()
}
})
})
deleteAction.backgroundColor = .red
return deleteAction
}
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return false
}
}
extension CommentViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return commentModels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Identifier.commentViewCell.rawValue, for: indexPath) as? CommentViewCell
let model = commentModels[indexPath.row]
cell?.usernameButton.setTitle(model.username, for: .normal)
// cell?.commentTimeLabel.text = model.createdTime?.description
cell?.delegate = self
cell?.commentLabel.text = model.comments
cell?.commentLabel.enabledTypes = [.mention, .hashtag, .url]
cell?.commentLabel.hashtagColor = .cyan
cell?.commentLabel.mentionColor = .cyan
cell?.commentLabel.handleHashtagTap({ (hashtag: String) in
let hashtagVC = self.storyboard?.instantiateViewController(withIdentifier: Identifier.hashtagViewController.rawValue) as? HashtagCollectionViewController
hashtagVC?.hashtag = hashtag
self.navigationController?.pushViewController(hashtagVC!, animated: true)
})
cell?.commentLabel.handleMentionTap({ (username: String) in
self.navigateToUser(username)
})
let user = PFUser.query()
user?.whereKey(User.id.rawValue, equalTo: model.username!)
user?.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in
guard let objects = objects else {
return
}
let object = objects.first as? PFUser
let imageFile = object?.object(forKey: User.profileImage.rawValue) as? PFFile
imageFile?.getDataInBackground(block: { [weak cell](data: Data?, error: Error?) in
guard let strongCell = cell, let data = data else {
return
}
DispatchQueue.main.async {
strongCell.profileImageView.image = UIImage.init(data: data)
}
})
})
return cell!
}
}
extension CommentViewController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
let spacing = NSCharacterSet.whitespacesAndNewlines
if (textField.text?.trimmingCharacters(in: spacing).isEmpty)! {
postButton.isEnabled = false
} else {
postButton.isEnabled = true
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
sendComment()
return true
}
}
extension CommentViewController: CommentViewCellDelegate {
func navigateToUser(_ username: String?) {
let profileVC = self.storyboard?.instantiateViewController(withIdentifier: Identifier.profileViewController.rawValue) as? ProfileViewController
profileVC?.userid = username
self.navigationController?.pushViewController(profileVC!, animated: true)
}
}
| gpl-3.0 | d4f86e7c1dc3b2a54a92fa8ace2a98fc | 37.147632 | 165 | 0.639138 | 5.376914 | false | false | false | false |
exchangegroup/paged-scroll-view-with-images | paged-scroll-view-with-images/TegErrors.swift | 2 | 606 | //
// List of custom error codes for this app.
//
import Foundation
enum TegError: Int {
case HttpCouldNotParseUrlString = 1
// There is a response from server, but it is not 200
case HttpNot200FromServer = 2
case HttpFailedToConvertResponseToText = 3
// Response is received and is 200 but the iOS app can not accept it for some other reasons,
// like a parsing error.
case HttpUnexpectedResponse = 4
var nsError: NSError {
let domain = NSBundle.mainBundle().bundleIdentifier ?? "teg.unknown.domain"
return NSError(domain: domain, code: rawValue, userInfo: nil)
}
}
| mit | d22a517fb0c109920768c631eeeef8de | 25.347826 | 94 | 0.717822 | 4.150685 | false | false | false | false |
erinshihshih/ETripTogether | Pods/LiquidFloatingActionButton/Pod/Classes/LiquidUtil.swift | 51 | 1401 | //
// LiquidUtil.swift
// LiquidLoading
//
// Created by Takuma Yoshida on 2015/08/17.
// Copyright (c) 2015年 yoavlt. All rights reserved.
//
import Foundation
import UIKit
func withBezier(f: (UIBezierPath) -> ()) -> UIBezierPath {
let bezierPath = UIBezierPath()
f(bezierPath)
bezierPath.closePath()
return bezierPath
}
extension CALayer {
func appendShadow() {
shadowColor = UIColor.blackColor().CGColor
shadowRadius = 2.0
shadowOpacity = 0.1
shadowOffset = CGSize(width: 4, height: 4)
masksToBounds = false
}
func eraseShadow() {
shadowRadius = 0.0
shadowColor = UIColor.clearColor().CGColor
}
}
class CGMath {
static func radToDeg(rad: CGFloat) -> CGFloat {
return rad * 180 / CGFloat(M_PI)
}
static func degToRad(deg: CGFloat) -> CGFloat {
return deg * CGFloat(M_PI) / 180
}
static func circlePoint(center: CGPoint, radius: CGFloat, rad: CGFloat) -> CGPoint {
let x = center.x + radius * cos(rad)
let y = center.y + radius * sin(rad)
return CGPoint(x: x, y: y)
}
static func linSpace(from: CGFloat, to: CGFloat, n: Int) -> [CGFloat] {
var values: [CGFloat] = []
for i in 0..<n {
values.append((to - from) * CGFloat(i) / CGFloat(n - 1) + from)
}
return values
}
} | mit | 6e941a6742bfb4e18805253c42fc6a43 | 24 | 88 | 0.586133 | 3.875346 | false | false | false | false |
externl/ice | swift/test/Ice/operations/BatchOneways.swift | 4 | 3632 | //
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import Darwin
import Ice
import TestCommon
func batchOneways(_ helper: TestHelper, _ p: MyClassPrx) throws {
func test(_ value: Bool, file: String = #file, line: Int = #line) throws {
try helper.test(value, file: file, line: line)
}
let bs1 = ByteSeq(repeating: 0, count: 10 * 1024)
let batch = p.ice_batchOneway()
try batch.ice_flushBatchRequests() // Empty flush
_ = try p.opByteSOnewayCallCount() // Reset the call count
for _ in 0 ..< 30 {
do {
try batch.opByteSOneway(bs1)
} catch is Ice.MemoryLimitException {
try test(false)
}
}
var count: Int32 = 0
while count < 27 { // 3 * 9 requests auto-flushed.
count += try p.opByteSOnewayCallCount()
usleep(100)
}
var conn = try batch.ice_getConnection()
if conn != nil {
let batch1 = p.ice_batchOneway()
let batch2 = p.ice_batchOneway()
try batch1.ice_ping()
try batch2.ice_ping()
try batch1.ice_flushBatchRequests()
try batch1.ice_getConnection()!.close(Ice.ConnectionClose.GracefullyWithWait)
try batch1.ice_ping()
try batch2.ice_ping()
_ = try batch1.ice_getConnection()
_ = try batch2.ice_getConnection()
try batch1.ice_ping()
try batch1.ice_getConnection()!.close(Ice.ConnectionClose.GracefullyWithWait)
try batch1.ice_ping()
try batch2.ice_ping()
}
var identity = Ice.Identity()
identity.name = "invalid"
let batch3 = batch.ice_identity(identity)
try batch3.ice_ping()
try batch3.ice_flushBatchRequests()
// Make sure that a bogus batch request doesn't cause troubles to other ones.
try batch3.ice_ping()
try batch.ice_ping()
try batch.ice_flushBatchRequests()
try batch.ice_ping()
try p.ice_ping()
var supportsCompress = true
do {
supportsCompress = try p.supportsCompress()
} catch is Ice.OperationNotExistException {}
conn = try p.ice_getConnection()
if supportsCompress,
conn != nil,
p.ice_getCommunicator().getProperties().getProperty("Ice.Override.Compress") == "" {
let prx = try p.ice_getConnection()!.createProxy(p.ice_getIdentity()).ice_batchOneway()
let batchC1 = uncheckedCast(prx: prx.ice_compress(false), type: MyClassPrx.self)
let batchC2 = uncheckedCast(prx: prx.ice_compress(true), type: MyClassPrx.self)
let batchC3 = uncheckedCast(prx: prx.ice_identity(identity), type: MyClassPrx.self)
try batchC1.opByteSOneway(bs1)
try batchC1.opByteSOneway(bs1)
try batchC1.opByteSOneway(bs1)
try batchC1.ice_getConnection()!.flushBatchRequests(Ice.CompressBatch.Yes)
try batchC2.opByteSOneway(bs1)
try batchC2.opByteSOneway(bs1)
try batchC2.opByteSOneway(bs1)
try batchC1.ice_getConnection()!.flushBatchRequests(Ice.CompressBatch.No)
try batchC1.opByteSOneway(bs1)
try batchC1.opByteSOneway(bs1)
try batchC1.opByteSOneway(bs1)
try batchC1.ice_getConnection()!.flushBatchRequests(Ice.CompressBatch.BasedOnProxy)
try batchC1.opByteSOneway(bs1)
try batchC2.opByteSOneway(bs1)
try batchC1.opByteSOneway(bs1)
try batchC1.ice_getConnection()!.flushBatchRequests(Ice.CompressBatch.BasedOnProxy)
try batchC1.opByteSOneway(bs1)
try batchC3.opByteSOneway(bs1)
try batchC1.opByteSOneway(bs1)
try batchC1.ice_getConnection()!.flushBatchRequests(Ice.CompressBatch.BasedOnProxy)
}
}
| gpl-2.0 | eaf99993aee16a6cd44ebb181e3d44a8 | 32.321101 | 95 | 0.655011 | 3.560784 | false | false | false | false |
lstn-ltd/lstn-sdk-ios | Lstn/Classes/Article/RemoteArticleResolver.swift | 1 | 5539 | //
// RemoteArticleResolver.swift
// Pods
//
// Created by Dan Halliday on 09/11/2016.
//
//
import Foundation
class RemoteArticleResolver: ArticleResolver {
weak var delegate: ArticleResolverDelegate? = nil
private let endpoint: URL
private let session: URLSessionType
private var tasks: [URLSessionDataTaskType] = []
private var cache: [ArticleKey:Article] = [:]
private let image = URL(string: "https://s18.postimg.org/h3701xrex/lstn_article_image_placeholder_2.png")!
private enum AudioFormat: String {
case wav = "audio/wav"
case hls = "application/x-mpegurl"
case mp3 = "audio/mpeg"
}
// TODO: Inject authentication token as well as endpoint; test
init(endpoint: URL = Lstn.endpoint, session: URLSessionType = URLSession.shared) {
self.endpoint = endpoint
self.session = session
}
func resolve(key: ArticleKey) {
self.delegate?.resolutionDidStart(key: key)
let request = self.request(for: key)
let task = self.session.dataTask(with: request) { data, response, error in
if let _ = error as? NSError {
self.delegate?.resolutionDidFail(key: key)
return
}
guard let response = response as? HTTPURLResponse else {
self.delegate?.resolutionDidFail(key: key)
return
}
if response.statusCode != 200 {
self.delegate?.resolutionDidFail(key: key);
return
}
guard let data = data else {
self.delegate?.resolutionDidFail(key: key)
return
}
if data.count == 0 {
self.delegate?.resolutionDidFail(key: key)
return
}
let json: Any
do { json = try JSONSerialization.jsonObject(with: data) } catch {
self.delegate?.resolutionDidFail(key: key)
return
}
guard let article = self.articleFromJson(json: json) else {
self.delegate?.resolutionDidFail(key: key)
return
}
self.delegate?.resolutionDidFinish(key: key, article: article)
self.tasks = self.tasks.filter({ $0.state != .completed })
// .enumerated()
// .filter({ $0.element.state == .completed })
// .map({ $0.offset })
// .forEach({ self.tasks.remove(at: $0) })
}
self.tasks.append(task)
task.resume()
}
private func articleFromJson(json: Any) -> Article? {
guard let dictionary = json as? [String:Any] else {
return nil
}
guard let state = dictionary["state"] as? String, state == "processed" else {
return nil
}
guard let id = dictionary["id"] as? String else {
return nil
}
// guard let publisher = dictionary["publisher"] as? [String:Any] else {
// return nil
// }
// guard let publisherId = publisher["id"] as? String else {
// return nil
// }
// guard let publisherName = publisher["name"] as? String else {
// return nil
// }
guard let source = URL(string: dictionary["url"] as? String) else {
return nil
}
guard let media = dictionary["media"] as? [[String:Any]] else {
return nil
}
guard let audio = self.audio(for: media) else {
return nil
}
// let image = URL(string: dictionary["image"] as? String) ?? self.image
guard let title = dictionary["title"] as? String else {
return nil
}
// guard let author = dictionary["author"] as? String else {
// return nil
// }
// Temporary hard-coded values
// TODO: Swap out once API implementation is complete
let publisher = "Lstn"
let author = dictionary["author"] as? String ?? "Lstn"
let key = ArticleKey(id: id, source: "unknown", publisher: "unknown")
let article = Article(key: key, source: source, audio: audio, image: self.image,
title: title, author: author, publisher: publisher)
return article
}
func url(for key: ArticleKey) -> URL {
return self.endpoint.appendingPathComponent("/news_sites/\(key.source)/articles/\(key.id)")
}
func request(for key: ArticleKey) -> URLRequest {
var request = URLRequest(url: self.url(for: key))
let token = Lstn.token ?? ""
request.setValue("Token token=\(token)", forHTTPHeaderField: "Authorization")
return request
}
func audio(for media: [[String:Any]]) -> URL? {
let candidates = media.filter { ($0["role"] as? String)?.lowercased() == "summary" }
let wav = candidates.filter { ($0["content_type"] as? String)?.lowercased() == AudioFormat.wav.rawValue }
let hls = candidates.filter { ($0["content_type"] as? String)?.lowercased() == AudioFormat.hls.rawValue }
let mp3 = candidates.filter { ($0["content_type"] as? String)?.lowercased() == AudioFormat.mp3.rawValue }
guard let item = hls.first ?? mp3.first ?? wav.first else {
return nil
}
guard let url = item["url"] as? String else {
return nil
}
return URL(string: url)
}
}
| mit | abcb555255243a383c9a04568e48a507 | 27.405128 | 113 | 0.551363 | 4.406523 | false | false | false | false |
CoderST/DYZB | DYZB/DYZB/Class/Profile/View/ProfileCell.swift | 1 | 1816 | //
// ProfileCell.swift
// DYZB
//
// Created by xiudou on 2017/6/20.
// Copyright © 2017年 xiudo. All rights reserved.
//
import UIKit
fileprivate let margin : CGFloat = 20
fileprivate let iconImageViewHW : CGFloat = 20
class ProfileCell: UICollectionViewCell {
fileprivate let lineView : UIView = {
let lineView = UIView()
lineView.backgroundColor = UIColor(r: 239, g: 239, b: 239)
return lineView
}()
fileprivate let iconImageView : UIImageView = {
let iconImageView = UIImageView()
iconImageView.contentMode = .center
return iconImageView
}()
fileprivate let titleLabel : UILabel = {
let titleLabel = UILabel()
return titleLabel
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
contentView.addSubview(iconImageView)
contentView.addSubview(titleLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var profileModel : ProfileModel?{
didSet{
guard let profileModel = profileModel else { return }
iconImageView.image = UIImage(named: profileModel.imageName)
titleLabel.text = profileModel.titleName
}
}
override func layoutSubviews() {
super.layoutSubviews()
iconImageView.frame = CGRect(x: margin, y: 0, width: iconImageViewHW, height: frame.height)
titleLabel.frame = CGRect(x: iconImageView.frame.maxX + 10, y: 0, width: 100, height: frame.height)
lineView.frame = CGRect(x: margin, y: frame.height - 1, width: sScreenW - margin, height: 1)
}
}
| mit | d04d50fb60863aa97ed3cb1717f0e2ef | 26.059701 | 107 | 0.600662 | 4.940054 | false | false | false | false |
mflint/ios-tldr-viewer | tldr-viewer/SearchingDataSourceDecorator.swift | 1 | 1897 | //
// SearchingDataSourceDecorator.swift
// tldr-viewer
//
// Created by Matthew Flint on 04/08/2019.
// Copyright © 2019 Green Light. All rights reserved.
//
import Foundation
class SearchingDataSourceDecorator: DataSourcing, SwitchableDataSourceDecorator {
private var delegates = WeakCollection<DataSourceDelegate>()
private(set) var commands = [Command]() {
didSet {
delegates.forEach { (delegate) in
delegate.dataSourceDidUpdate(dataSource: self)
}
}
}
var searchText: String = "" {
didSet {
update()
}
}
let isSearchable = true
var isRefreshable: Bool {
return underlyingDataSource.isRefreshable
}
private var underlyingDataSource: DataSourcing
let name = Localizations.CommandList.DataSources.All
let type = DataSourceType.all
init(underlyingDataSource: DataSourcing) {
self.underlyingDataSource = underlyingDataSource
underlyingDataSource.add(delegate: self)
}
func add(delegate: DataSourceDelegate) {
delegates.add(delegate)
}
private func update() {
let allCommands = underlyingDataSource.commands
// if the search string is empty, return everything
if searchText.isEmpty {
commands = allCommands
} else {
let lowercasedSearchText = searchText.lowercased()
commands = allCommands.filter({ (command) -> Bool in
// TODO: can improve search performance by adding `lowercasedName`
// property to Command
command.name.lowercased().contains(lowercasedSearchText)
})
}
}
}
extension SearchingDataSourceDecorator: DataSourceDelegate {
func dataSourceDidUpdate(dataSource: DataSourcing) {
update()
}
}
| mit | 4e9ff8f4cddba058dd2941b3b5244d87 | 26.478261 | 82 | 0.628165 | 5.266667 | false | false | false | false |
takeo-asai/math-puzzle | problems/04.swift | 1 | 732 | struct Stick {
let length: Int
init(_ l: Int) {
length = l
}
func cut() -> [Stick] {
if isCutable() {
return [Stick(length/2), Stick(length/2 + length%2)]
}
return [self]
}
func isCutable() -> Bool {
return length != 1
}
}
let n = 100
let m = 5
var sticks: [Stick] = [Stick(n)]
var t = 0
while true {
// terminate if cut is done
let cutable: Bool = sticks.map() { $0.isCutable() }.reduce(false) { $0 || $1 }
if !cutable {
break
}
// cut
var tmps: [Stick] = []
for _ in 0 ..< m {
if sticks.count > 0 {
let stick = sticks.removeAtIndex(0)
tmps += stick.cut()
}
}
sticks += tmps
sticks = sticks.sort { (s0: Stick, s1: Stick) -> Bool in s0.length > s1.length }
t++
}
print("times: \(t)")
| mit | 5eb8e6b13203b68efffc57b2fa03f47a | 16.023256 | 81 | 0.565574 | 2.407895 | false | false | false | false |
kuruvilla6970/Zoot | Source/JS API/DialogOptions.swift | 1 | 2650 | //
// DialogOptions.swift
// THGHybridWeb
//
// Created by Angelo Di Paolo on 7/7/15.
// Copyright (c) 2015 TheHolyGrail. All rights reserved.
//
import JavaScriptCore
import UIKit
struct DialogOptions {
var title: String?
var message: String?
let actions: [DialogAction]
init(title: String?, message: String?, actions: [DialogAction]) {
self.title = title
self.message = message
self.actions = actions
}
// TODO: Refactor after migrating to Swift 2 with real initializer that throws an ErrorType
static func resultOrErrorWithOptions(options: [String: AnyObject]) -> HybridAPIResult<DialogOptions> {
let title = options["title"] as? String
let message = options["message"] as? String
if message == nil && title == nil {
return .Failure(DialogOptionsError.EmptyTitleAndMessage)
}
if let actions = options["actions"] as? [[String: AnyObject]] where count(actions) > 0 {
var dialogActions = [DialogAction]()
for actionOptions in actions {
switch DialogAction.resultOrError(actionOptions) {
case .Success(let boxedDialogAction):
dialogActions.append(boxedDialogAction.value)
case .Failure(let error):
return .Failure(error)
}
}
return .Success(Box(DialogOptions(title: title, message: message, actions: dialogActions)))
} else {
return .Failure(DialogOptionsError.MissingAction)
}
}
func actionAtIndex(index: Int) -> String? {
return actions[index].actionID
}
}
enum DialogOptionsError: String, HybridAPIErrorType {
case MissingAction = "Must have at least one action defined in `actions` array of the options parameter."
case EmptyTitleAndMessage = "Must have at least title or message defined in options parameter."
case MissingActionParameters = "Action objects must have `id` and `label` parameters."
var message: String { return self.rawValue }
}
struct DialogAction {
let actionID: String
let label: String
static func resultOrError(options: [String: AnyObject]) -> HybridAPIResult<DialogAction> {
if let actionID = options["id"] as? String,
let label = options["label"] as? String {
return .Success(Box(DialogAction(actionID: actionID, label: label)))
} else {
return .Failure(DialogOptionsError.MissingActionParameters)
}
}
}
| mit | 4d344992edb03d15b12793fa7bc25cff | 33.415584 | 109 | 0.616604 | 4.698582 | false | false | false | false |
L550312242/SinaWeiBo-Switf | weibo 1/AppDelegate.swift | 1 | 2428 | //
// AppDelegate.swift
// weibo 1
//
// Created by sa on 15/10/27.
// Copyright © 2015年 sa. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//创造Window
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.orangeColor()
let tabbar = CZMainViewController()
//?: 如果?前面的变量有值才执行后面的代码
window?.rootViewController = defaultController()
// window?.rootViewController = CZOauthViewController()
//成为主窗口并显示
window?.makeKeyAndVisible()
return true
}
private func defaultController() -> UIViewController {
//判断是否登录
// 每次判断都需要 == nil
if !CZUserAccount.userLogin() {
return CZMainViewController()
}
// 判断是否是新版本
return isNewVersion() ? CZNewFeatureViewController() : CZWelcomeViewController()
}
//判断是否是新版本
private func isNewVersion() -> Bool{
//获取当前版本号
let versionString = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
let currentVersion = Double(versionString)!
// print("currentVersion: \(currentVersion)")
//获取到之前的版本号
let sandboxVersionKey = "sandboxVersionKey"
let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
// print("sandboxVersion: \(sandboxVersion)")
//保存当前版本号
NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey)
//对比
return currentVersion > sandboxVersion
}
// MARK: - 切换根控制器
/**
切换根控制器
- parameter isMain: true: 表示切换到MainViewController, false: welcome
*/
func switchRootController(isMain: Bool) {
window?.rootViewController = isMain ? CZMainViewController() : CZWelcomeViewController()
}
private func setupAppearance() {
// 尽早设置
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
}
}
| apache-2.0 | 2cb0c4de39ddc06cafb65a0fea472037 | 30.253521 | 127 | 0.653898 | 5.160465 | false | false | false | false |
loudnate/LoopKit | LoopKitUI/ServiceCredential.swift | 2 | 1178 | //
// ServiceCredential.swift
// Loop
//
// Created by Nate Racklyeft on 7/2/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
/// Represents the input method for a service credential
public struct ServiceCredential {
/// The localized title of the credential (e.g. "Username")
public let title: String
/// The localized placeholder text to assist text input
public let placeholder: String?
/// Whether the credential is considered secret. Correponds to the `secureTextEntry` trait.
public let isSecret: Bool
/// The type of keyboard to use to enter the credential
public let keyboardType: UIKeyboardType
/// A set of valid values for presenting a selection. The first item is the default.
public let options: [(title: String, value: String)]?
public init(title: String, placeholder: String? = nil, isSecret: Bool, keyboardType: UIKeyboardType = .asciiCapable, options: [(title: String, value: String)]? = nil) {
self.title = title
self.placeholder = placeholder
self.isSecret = isSecret
self.keyboardType = keyboardType
self.options = options
}
}
| mit | d952420565fb96a5460693f8cd43813c | 31.694444 | 172 | 0.694987 | 4.615686 | false | false | false | false |
witochandra/CalendarView | Source/Classes/CalendarDayCell.swift | 1 | 3041 | //
// CalendarDayCell.swift
// CalendarView
//
// Created by Wito Chandra on 05/04/16.
// Copyright © 2016 Wito Chandra. All rights reserved.
//
import UIKit
public enum CalendarDayCellState {
case normal
case disabled
case start(hasNext: Bool)
case range
case end
}
open class CalendarDayCell: UICollectionViewCell {
@IBOutlet fileprivate var viewBackground: UIView!
@IBOutlet fileprivate var viewSelectedCircle: UIView!
@IBOutlet fileprivate var viewNextRange: UIView!
@IBOutlet fileprivate var viewPreviousRange: UIView!
@IBOutlet fileprivate var labelDay: UILabel!
fileprivate(set) var state = CalendarDayCellState.normal
fileprivate(set) var date = Date()
open override func awakeFromNib() {
super.awakeFromNib()
viewSelectedCircle.layer.cornerRadius = viewSelectedCircle.frame.width / 2
viewSelectedCircle.layer.masksToBounds = true
}
open func update(theme: CalendarViewTheme, date: Date, state: CalendarDayCellState, isCurrentMonth: Bool) {
self.date = date
self.state = state
let calendar = CalendarViewUtils.instance.calendar
let components = (calendar as NSCalendar).components(.day, from: date)
labelDay.text = String(components.day ?? 0)
viewPreviousRange.backgroundColor = theme.colorForDatesRange
viewNextRange.backgroundColor = theme.colorForDatesRange
viewSelectedCircle.backgroundColor = theme.colorForSelectedDate
if isCurrentMonth {
viewBackground.backgroundColor = theme.bgColorForCurrentMonth
} else {
viewBackground.backgroundColor = theme.bgColorForOtherMonth
}
switch state {
case .normal:
if isCurrentMonth {
labelDay.textColor = theme.textColorForNormalDay
} else {
labelDay.textColor = theme.textColorForDisabledDay
}
viewSelectedCircle.isHidden = true
viewNextRange.isHidden = true
viewPreviousRange.isHidden = true
case .disabled:
labelDay.textColor = theme.textColorForDisabledDay
viewSelectedCircle.isHidden = true
viewNextRange.isHidden = true
viewPreviousRange.isHidden = true
case let .start(hasNext):
labelDay.textColor = theme.textColorForSelectedDay
viewSelectedCircle.isHidden = false
viewNextRange.isHidden = !hasNext
viewPreviousRange.isHidden = true
case .range:
labelDay.textColor = theme.textColorForNormalDay
viewSelectedCircle.isHidden = true
viewNextRange.isHidden = false
viewPreviousRange.isHidden = false
case .end:
labelDay.textColor = theme.textColorForSelectedDay
viewSelectedCircle.isHidden = false
viewNextRange.isHidden = true
viewPreviousRange.isHidden = false
}
}
}
| mit | 66550ac2efd4b0a3b022d7608b199a68 | 33.942529 | 111 | 0.656579 | 5.092127 | false | false | false | false |
hq7781/MoneyBook | Pods/JTAppleCalendar/Sources/JTAppleCalendarView.swift | 2 | 48531 | //
// JTAppleCalendarView.swift
//
// Copyright (c) 2016-2017 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.
//
let maxNumberOfDaysInWeek = 7 // Should not be changed
let maxNumberOfRowsPerMonth = 6 // Should not be changed
let developerErrorMessage = "There was an error in this code section. Please contact the developer on GitHub"
let decorationViewID = "Are you ready for the life after this one?"
/// An instance of JTAppleCalendarView (or simply, a calendar view) is a
/// means for displaying and interacting with a gridstyle layout of date-cells
open class JTAppleCalendarView: UICollectionView {
/// Configures the size of your date cells
@IBInspectable open var cellSize: CGFloat = 0 {
didSet {
if oldValue == cellSize { return }
if scrollDirection == .horizontal {
calendarViewLayout.cellSize.width = cellSize
} else {
calendarViewLayout.cellSize.height = cellSize
}
calendarViewLayout.invalidateLayout()
calendarViewLayout.itemSizeWasSet = cellSize == 0 ? false: true
}
}
/// The scroll direction of the sections in JTAppleCalendar.
open var scrollDirection: UICollectionViewScrollDirection!
/// Enables/Disables the stretching of date cells. When enabled cells will stretch to fit the width of a month in case of a <= 5 row month.
open var allowsDateCellStretching = true
/// Alerts the calendar that range selection will be checked. If you are
/// not using rangeSelection and you enable this,
/// then whenever you click on a datecell, you may notice a very fast
/// refreshing of the date-cells both left and right of the cell you
/// just selected.
open var isRangeSelectionUsed: Bool = false
/// The object that acts as the delegate of the calendar view.
weak open var calendarDelegate: JTAppleCalendarViewDelegate? {
didSet { lastMonthSize = sizesForMonthSection() }
}
/// The object that acts as the data source of the calendar view.
weak open var calendarDataSource: JTAppleCalendarViewDataSource? {
didSet {
setupMonthInfoAndMap() // Refetch the data source for a data source change
}
}
var lastSavedContentOffset: CGFloat = 0.0
var triggerScrollToDateDelegate: Bool? = true
var isScrollInProgress = false
var isReloadDataInProgress = false
var delayedExecutionClosure: [(() -> Void)] = []
let dateGenerator = JTAppleDateConfigGenerator()
/// Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.
public init() {
super.init(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
setupNewLayout(from: collectionViewLayout as! JTAppleCalendarLayoutProtocol)
}
/// Initializes and returns a newly allocated collection view object with the specified frame and layout.
@available(*, unavailable, message: "Please use JTAppleCalendarView() instead. It manages its own layout.")
public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
setupNewLayout(from: collectionViewLayout as! JTAppleCalendarLayoutProtocol)
}
/// Initializes using decoder object
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupNewLayout(from: collectionViewLayout as! JTAppleCalendarLayoutProtocol)
}
/// Notifies the container that the size of its view is about to change.
public func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator, focusDateIndexPathAfterRotate: IndexPath? = nil) {
calendarViewLayout.focusIndexPath = focusDateIndexPathAfterRotate
coordinator.animate(alongsideTransition: { (context) -> Void in
self.performBatchUpdates(nil, completion: nil)
},completion: { (context) -> Void in
self.calendarViewLayout.focusIndexPath = nil
})
}
/// Lays out subviews.
override open func layoutSubviews() {
super.layoutSubviews()
if !delayedExecutionClosure.isEmpty, isCalendarLayoutLoaded {
executeDelayedTasks()
}
}
func setupMonthInfoAndMap(with data: ConfigurationParameters? = nil) {
theData = setupMonthInfoDataForStartAndEndDate(with: data)
}
// Configuration parameters from the dataSource
var cachedConfiguration: ConfigurationParameters!
// Set the start of the month
var startOfMonthCache: Date!
// Set the end of month
var endOfMonthCache: Date!
var theSelectedIndexPaths: [IndexPath] = []
var theSelectedDates: [Date] = []
var initialScrollDate: Date?
func firstContentOffset() -> CGPoint {
var retval: CGPoint = .zero
guard let date = initialScrollDate else { return retval }
// Ensure date is within valid boundary
let components = calendar.dateComponents([.year, .month, .day], from: date)
let firstDayOfDate = calendar.date(from: components)!
if !((firstDayOfDate >= self.startOfMonthCache!) && (firstDayOfDate <= self.endOfMonthCache!)) { return retval }
// Get valid indexPath of date to scroll to
let retrievedPathsFromDates = self.pathsFromDates([date])
if retrievedPathsFromDates.isEmpty { return retval }
let sectionIndexPath = self.pathsFromDates([date])[0]
if calendarViewLayout.thereAreHeaders && scrollDirection == .vertical {
let indexPath = IndexPath(item: 0, section: sectionIndexPath.section)
guard let attributes = calendarViewLayout.layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionHeader, at: indexPath) else { return retval }
let maxYCalendarOffset = max(0, self.contentSize.height - self.frame.size.height)
retval = CGPoint(x: attributes.frame.origin.x,y: min(maxYCalendarOffset, attributes.frame.origin.y))
// if self.scrollDirection == .horizontal { topOfHeader.x += extraAddedOffset} else { topOfHeader.y += extraAddedOffset }
} else {
switch self.scrollingMode {
case .stopAtEach, .stopAtEachSection, .stopAtEachCalendarFrameWidth:
if self.scrollDirection == .horizontal || (scrollDirection == .vertical && !calendarViewLayout.thereAreHeaders) {
retval = self.targetPointForItemAt(indexPath: sectionIndexPath) ?? .zero
}
default:
break
}
}
return retval
}
open var sectionInset: UIEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)
open var minimumInteritemSpacing: CGFloat = 0
open var minimumLineSpacing: CGFloat = 0
lazy var theData: CalendarData = {
return self.setupMonthInfoDataForStartAndEndDate()
}()
var lastMonthSize: [AnyHashable:CGFloat] = [:]
var monthMap: [Int: Int] {
get { return theData.sectionToMonthMap }
set { theData.sectionToMonthMap = monthMap }
}
/// Configure the scrolling behavior
open var scrollingMode: ScrollingMode = .stopAtEachCalendarFrameWidth {
didSet {
switch scrollingMode {
case .stopAtEachCalendarFrameWidth: decelerationRate = UIScrollViewDecelerationRateFast
case .stopAtEach, .stopAtEachSection: decelerationRate = UIScrollViewDecelerationRateFast
case .nonStopToSection, .nonStopToCell, .nonStopTo, .none: decelerationRate = UIScrollViewDecelerationRateNormal
}
#if os(iOS)
switch scrollingMode {
case .stopAtEachCalendarFrameWidth:
isPagingEnabled = true
default:
isPagingEnabled = false
}
#endif
}
}
/// A semantic description of the view’s contents, used to determine whether the view should be flipped when switching between left-to-right and right-to-left layouts.
open override var semanticContentAttribute: UISemanticContentAttribute {
didSet {
transform.a = semanticContentAttribute == .forceRightToLeft ? -1 : 1
}
}
func developerError(string: String) {
print(string)
print(developerErrorMessage)
assert(false)
}
func setupNewLayout(from oldLayout: JTAppleCalendarLayoutProtocol) {
let newLayout = JTAppleCalendarLayout(withDelegate: self)
newLayout.scrollDirection = oldLayout.scrollDirection
newLayout.sectionInset = oldLayout.sectionInset
newLayout.minimumInteritemSpacing = oldLayout.minimumInteritemSpacing
newLayout.minimumLineSpacing = oldLayout.minimumLineSpacing
collectionViewLayout = newLayout
scrollDirection = newLayout.scrollDirection
sectionInset = newLayout.sectionInset
minimumLineSpacing = newLayout.minimumLineSpacing
minimumInteritemSpacing = newLayout.minimumInteritemSpacing
transform.a = semanticContentAttribute == .forceRightToLeft ? -1 : 1
super.dataSource = self
super.delegate = self
decelerationRate = UIScrollViewDecelerationRateFast
#if os(iOS)
if isPagingEnabled {
scrollingMode = .stopAtEachCalendarFrameWidth
} else {
scrollingMode = .none
}
#endif
}
func validForwardAndBackwordSelectedIndexes(forIndexPath indexPath: IndexPath) -> [IndexPath] {
var retval: [IndexPath] = []
if let validForwardIndex = calendarViewLayout.indexPath(direction: .next, of: indexPath.section, item: indexPath.item),
theSelectedIndexPaths.contains(validForwardIndex) {
retval.append(validForwardIndex)
}
if
let validBackwardIndex = calendarViewLayout.indexPath(direction: .previous, of: indexPath.section, item: indexPath.item),
theSelectedIndexPaths.contains(validBackwardIndex) {
retval.append(validBackwardIndex)
}
return retval
}
func scrollTo(indexPath: IndexPath, triggerScrollToDateDelegate: Bool, isAnimationEnabled: Bool, position: UICollectionViewScrollPosition, extraAddedOffset: CGFloat, completionHandler: (() -> Void)?) {
isScrollInProgress = true
if let validCompletionHandler = completionHandler {
self.delayedExecutionClosure.append(validCompletionHandler)
}
self.triggerScrollToDateDelegate = triggerScrollToDateDelegate
DispatchQueue.main.async {
self.scrollToItem(at: indexPath, at: position, animated: isAnimationEnabled)
if (isAnimationEnabled && self.calendarOffsetIsAlreadyAtScrollPosition(forIndexPath: indexPath)) ||
!isAnimationEnabled {
self.scrollViewDidEndScrollingAnimation(self)
}
self.isScrollInProgress = false
}
}
func targetPointForItemAt(indexPath: IndexPath) -> CGPoint? {
guard let targetCellFrame = calendarViewLayout.layoutAttributesForItem(at: indexPath)?.frame else { // Jt101 This was changed !!
return nil
}
let theTargetContentOffset: CGFloat = scrollDirection == .horizontal ? targetCellFrame.origin.x : targetCellFrame.origin.y
var fixedScrollSize: CGFloat = 0
switch scrollingMode {
case .stopAtEachSection, .stopAtEachCalendarFrameWidth, .nonStopToSection:
if self.scrollDirection == .horizontal || (scrollDirection == .vertical && !calendarViewLayout.thereAreHeaders) {
// Horizontal has a fixed width.
// Vertical with no header has fixed height
fixedScrollSize = calendarViewLayout.sizeOfContentForSection(0)
} else {
// JT101 will remodel this code. Just a quick fix
fixedScrollSize = calendarViewLayout.sizeOfContentForSection(0)
}
case .stopAtEach(customInterval: let customVal):
fixedScrollSize = customVal
default:
break
}
let section = CGFloat(Int(theTargetContentOffset / fixedScrollSize))
let destinationRectOffset = (fixedScrollSize * section)
var x: CGFloat = 0
var y: CGFloat = 0
if scrollDirection == .horizontal {
x = destinationRectOffset
} else {
y = destinationRectOffset
}
return CGPoint(x: x, y: y)
}
func calendarOffsetIsAlreadyAtScrollPosition(forOffset offset: CGPoint) -> Bool {
var retval = false
// If the scroll is set to animate, and the target content
// offset is already on the screen, then the
// didFinishScrollingAnimation
// delegate will not get called. Once animation is on let's
// force a scroll so the delegate MUST get caalled
let theOffset = scrollDirection == .horizontal ? offset.x : offset.y
let divValue = scrollDirection == .horizontal ? frame.width : frame.height
let sectionForOffset = Int(theOffset / divValue)
let calendarCurrentOffset = scrollDirection == .horizontal ? contentOffset.x : contentOffset.y
if calendarCurrentOffset == theOffset || (scrollingMode.pagingIsEnabled() && (sectionForOffset == currentSection())) {
retval = true
}
return retval
}
func calendarOffsetIsAlreadyAtScrollPosition(forIndexPath indexPath: IndexPath) -> Bool {
var retval = false
// If the scroll is set to animate, and the target content offset
// is already on the screen, then the didFinishScrollingAnimation
// delegate will not get called. Once animation is on let's force
// a scroll so the delegate MUST get caalled
if let attributes = calendarViewLayout.layoutAttributesForItem(at: indexPath) { // JT101 this was changed!!!!
let layoutOffset: CGFloat
let calendarOffset: CGFloat
if scrollDirection == .horizontal {
layoutOffset = attributes.frame.origin.x
calendarOffset = contentOffset.x
} else {
layoutOffset = attributes.frame.origin.y
calendarOffset = contentOffset.y
}
if calendarOffset == layoutOffset {
retval = true
}
}
return retval
}
func scrollToHeaderInSection(_ section: Int,
triggerScrollToDateDelegate: Bool = false,
withAnimation animation: Bool = true,
extraAddedOffset: CGFloat,
completionHandler: (() -> Void)? = nil) {
if !calendarViewLayout.thereAreHeaders { return }
let indexPath = IndexPath(item: 0, section: section)
guard let attributes = calendarViewLayout.layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionHeader, at: indexPath) else { return }
isScrollInProgress = true
if let validHandler = completionHandler { self.delayedExecutionClosure.append(validHandler) }
self.triggerScrollToDateDelegate = triggerScrollToDateDelegate
let maxYCalendarOffset = max(0, self.contentSize.height - self.frame.size.height)
var topOfHeader = CGPoint(x: attributes.frame.origin.x,y: min(maxYCalendarOffset, attributes.frame.origin.y))
if self.scrollDirection == .horizontal { topOfHeader.x += extraAddedOffset} else { topOfHeader.y += extraAddedOffset }
DispatchQueue.main.async {
self.setContentOffset(topOfHeader, animated: animation)
if (animation && self.calendarOffsetIsAlreadyAtScrollPosition(forOffset: topOfHeader)) ||
!animation {
self.scrollViewDidEndScrollingAnimation(self)
}
self.isScrollInProgress = false
}
}
// Subclasses cannot use this function
@available(*, unavailable)
open override func reloadData() {
super.reloadData()
}
func executeDelayedTasks() {
let tasksToExecute = delayedExecutionClosure
delayedExecutionClosure.removeAll()
for aTaskToExecute in tasksToExecute {
aTaskToExecute()
}
}
// Only reload the dates if the datasource information has changed
func reloadDelegateDataSource() -> (shouldReload: Bool, configParameters: ConfigurationParameters?) {
var retval: (Bool, ConfigurationParameters?) = (false, nil)
if let
newDateBoundary = calendarDataSource?.configureCalendar(self) {
// Jt101 do a check in each var to see if
// user has bad star/end dates
let newStartOfMonth = calendar.startOfMonth(for: newDateBoundary.startDate)
let newEndOfMonth = calendar.endOfMonth(for: newDateBoundary.endDate)
let oldStartOfMonth = calendar.startOfMonth(for: startDateCache)
let oldEndOfMonth = calendar.endOfMonth(for: endDateCache)
let newLastMonth = sizesForMonthSection()
let calendarLayout = calendarViewLayout
if
// ConfigParameters were changed
newStartOfMonth != oldStartOfMonth ||
newEndOfMonth != oldEndOfMonth ||
newDateBoundary.calendar != cachedConfiguration.calendar ||
newDateBoundary.numberOfRows != cachedConfiguration.numberOfRows ||
newDateBoundary.generateInDates != cachedConfiguration.generateInDates ||
newDateBoundary.generateOutDates != cachedConfiguration.generateOutDates ||
newDateBoundary.firstDayOfWeek != cachedConfiguration.firstDayOfWeek ||
newDateBoundary.hasStrictBoundaries != cachedConfiguration.hasStrictBoundaries ||
// Other layout information were changed
minimumInteritemSpacing != calendarLayout.minimumInteritemSpacing ||
minimumLineSpacing != calendarLayout.minimumLineSpacing ||
sectionInset != calendarLayout.sectionInset ||
lastMonthSize != newLastMonth ||
allowsDateCellStretching != calendarLayout.allowsDateCellStretching ||
scrollDirection != calendarLayout.scrollDirection ||
calendarLayout.cellSizeWasUpdated {
lastMonthSize = newLastMonth
retval = (true, newDateBoundary)
}
}
return retval
}
func remapSelectedDatesWithCurrentLayout() -> (selected:(indexPaths:[IndexPath], counterPaths:[IndexPath]), selectedDates: [Date]) {
var retval = (selected:(indexPaths:[IndexPath](), counterPaths:[IndexPath]()), selectedDates: [Date]())
if !selectedDates.isEmpty {
let selectedDates = self.selectedDates
// Get the new paths
let newPaths = self.pathsFromDates(selectedDates)
// Get the new counter Paths
var newCounterPaths: [IndexPath] = []
for date in selectedDates {
if let counterPath = self.indexPathOfdateCellCounterPath(date, dateOwner: .thisMonth) {
newCounterPaths.append(counterPath)
}
}
// Append paths
retval.selected.indexPaths.append(contentsOf: newPaths)
retval.selected.counterPaths.append(contentsOf: newCounterPaths)
// Append dates to retval
for allPaths in [newPaths, newCounterPaths] {
for path in allPaths {
guard let dateFromPath = dateOwnerInfoFromPath(path)?.date else { continue }
retval.selectedDates.append(dateFromPath)
}
}
}
return retval
}
func restoreSelectionStateForCellAtIndexPath(_ indexPath: IndexPath) {
if theSelectedIndexPaths.contains(indexPath) {
selectItem(at: indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition() )
}
}
}
extension JTAppleCalendarView {
func handleScroll(point: CGPoint? = nil,
indexPath: IndexPath? = nil,
triggerScrollToDateDelegate: Bool = true,
isAnimationEnabled: Bool,
position: UICollectionViewScrollPosition? = .left,
extraAddedOffset: CGFloat = 0,
completionHandler: (() -> Void)?) {
if isScrollInProgress { return }
// point takes preference
if let validPoint = point {
scrollTo(point: validPoint,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
isAnimationEnabled: isAnimationEnabled,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
} else {
guard let validIndexPath = indexPath else { return }
var isNonConinuousScroll = true
switch scrollingMode {
case .none, .nonStopToCell: isNonConinuousScroll = false
default: break
}
if calendarViewLayout.thereAreHeaders,
scrollDirection == .vertical,
isNonConinuousScroll {
scrollToHeaderInSection(validIndexPath.section,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
withAnimation: isAnimationEnabled,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
} else {
scrollTo(indexPath:validIndexPath,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
isAnimationEnabled: isAnimationEnabled,
position: position ?? .left,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
}
}
}
func scrollTo(point: CGPoint, triggerScrollToDateDelegate: Bool? = nil, isAnimationEnabled: Bool, extraAddedOffset: CGFloat, completionHandler: (() -> Void)?) {
isScrollInProgress = true
if let validCompletionHandler = completionHandler {
self.delayedExecutionClosure.append(validCompletionHandler)
}
self.triggerScrollToDateDelegate = triggerScrollToDateDelegate
var point = point
if scrollDirection == .horizontal { point.x += extraAddedOffset } else { point.y += extraAddedOffset }
DispatchQueue.main.async() {
self.setContentOffset(point, animated: isAnimationEnabled)
if (isAnimationEnabled && self.calendarOffsetIsAlreadyAtScrollPosition(forOffset: point)) ||
!isAnimationEnabled {
self.scrollViewDidEndScrollingAnimation(self)
}
self.isScrollInProgress = false
}
}
func indexPathOfdateCellCounterPath(_ date: Date,
dateOwner: DateOwner) -> IndexPath? {
if (cachedConfiguration.generateInDates == .off ||
cachedConfiguration.generateInDates == .forFirstMonthOnly) &&
cachedConfiguration.generateOutDates == .off {
return nil
}
var retval: IndexPath?
if dateOwner != .thisMonth {
// If the cell is anything but this month, then the cell belongs
// to either a previous of following month
// Get the indexPath of the counterpartCell
let counterPathIndex = pathsFromDates([date])
if !counterPathIndex.isEmpty {
retval = counterPathIndex[0]
}
} else {
// If the date does belong to this month,
// then lets find out if it has a counterpart date
if date < startOfMonthCache || date > endOfMonthCache {
return retval
}
guard let dayIndex = calendar.dateComponents([.day], from: date).day else {
print("Invalid Index")
return nil
}
if case 1...13 = dayIndex {
// then check the previous month
// get the index path of the last day of the previous month
let periodApart = calendar.dateComponents([.month], from: startOfMonthCache, to: date)
guard
let monthSectionIndex = periodApart.month, monthSectionIndex - 1 >= 0 else {
// If there is no previous months,
// there are no counterpart dates
return retval
}
let previousMonthInfo = monthInfo[monthSectionIndex - 1]
// If there are no postdates for the previous month,
// then there are no counterpart dates
if previousMonthInfo.outDates < 1 || dayIndex > previousMonthInfo.outDates {
return retval
}
guard
let prevMonth = calendar.date(byAdding: .month, value: -1, to: date),
let lastDayOfPrevMonth = calendar.endOfMonth(for: prevMonth) else {
assert(false, "Error generating date in indexPathOfdateCellCounterPath(). Contact the developer on github")
return retval
}
let indexPathOfLastDayOfPreviousMonth = pathsFromDates([lastDayOfPrevMonth])
if indexPathOfLastDayOfPreviousMonth.isEmpty {
print("out of range error in indexPathOfdateCellCounterPath() upper. This should not happen. Contact developer on github")
return retval
}
let lastDayIndexPath = indexPathOfLastDayOfPreviousMonth[0]
var section = lastDayIndexPath.section
var itemIndex = lastDayIndexPath.item + dayIndex
// Determine if the sections/item needs to be adjusted
let extraSection = itemIndex / collectionView(self, numberOfItemsInSection: section)
let extraIndex = itemIndex % collectionView(self, numberOfItemsInSection: section)
section += extraSection
itemIndex = extraIndex
let reCalcRapth = IndexPath(item: itemIndex, section: section)
retval = reCalcRapth
} else if case 25...31 = dayIndex { // check the following month
let periodApart = calendar.dateComponents([.month], from: startOfMonthCache, to: date)
let monthSectionIndex = periodApart.month!
if monthSectionIndex + 1 >= monthInfo.count {
return retval
}
// If there is no following months, there are no counterpart dates
let followingMonthInfo = monthInfo[monthSectionIndex + 1]
if followingMonthInfo.inDates < 1 {
return retval
}
// If there are no predates for the following month then there are no counterpart dates
let lastDateOfCurrentMonth = calendar.endOfMonth(for: date)!
let lastDay = calendar.component(.day, from: lastDateOfCurrentMonth)
let section = followingMonthInfo.startSection
let index = dayIndex - lastDay + (followingMonthInfo.inDates - 1)
if index < 0 {
return retval
}
retval = IndexPath(item: index, section: section)
}
}
return retval
}
func setupMonthInfoDataForStartAndEndDate(with config: ConfigurationParameters? = nil) -> CalendarData {
var months = [Month]()
var monthMap = [Int: Int]()
var totalSections = 0
var totalDays = 0
var validConfig = config
if validConfig == nil { validConfig = calendarDataSource?.configureCalendar(self) }
if let validConfig = validConfig {
let comparison = validConfig.calendar.compare(validConfig.startDate, to: validConfig.endDate, toGranularity: .nanosecond)
if comparison == ComparisonResult.orderedDescending {
assert(false, "Error, your start date cannot be greater than your end date\n")
return (CalendarData(months: [], totalSections: 0, sectionToMonthMap: [:], totalDays: 0))
}
// Set the new cache
cachedConfiguration = validConfig
if let
startMonth = calendar.startOfMonth(for: validConfig.startDate),
let endMonth = calendar.endOfMonth(for: validConfig.endDate) {
startOfMonthCache = startMonth
endOfMonthCache = endMonth
// Create the parameters for the date format generator
let parameters = ConfigurationParameters(startDate: startOfMonthCache,
endDate: endOfMonthCache,
numberOfRows: validConfig.numberOfRows,
calendar: calendar,
generateInDates: validConfig.generateInDates,
generateOutDates: validConfig.generateOutDates,
firstDayOfWeek: validConfig.firstDayOfWeek,
hasStrictBoundaries: validConfig.hasStrictBoundaries)
let generatedData = dateGenerator.setupMonthInfoDataForStartAndEndDate(parameters)
months = generatedData.months
monthMap = generatedData.monthMap
totalSections = generatedData.totalSections
totalDays = generatedData.totalDays
}
}
let data = CalendarData(months: months, totalSections: totalSections, sectionToMonthMap: monthMap, totalDays: totalDays)
return data
}
func sizesForMonthSection() -> [AnyHashable:CGFloat] {
var retval: [AnyHashable:CGFloat] = [:]
guard
let headerSizes = calendarDelegate?.calendarSizeForMonths(self),
headerSizes.defaultSize > 0 else {
return retval
}
// Build the default
retval["default"] = headerSizes.defaultSize
// Build the every-month data
if let allMonths = headerSizes.months {
for (size, months) in allMonths {
for month in months {
assert(retval[month] == nil, "You have duplicated months. Please revise your month size data.")
retval[month] = size
}
}
}
// Build the specific month data
if let specificSections = headerSizes.dates {
for (size, dateArray) in specificSections {
let paths = pathsFromDates(dateArray)
for path in paths {
retval[path.section] = size
}
}
}
return retval
}
func pathsFromDates(_ dates: [Date]) -> [IndexPath] {
var returnPaths: [IndexPath] = []
for date in dates {
if calendar.startOfDay(for: date) >= startOfMonthCache! && calendar.startOfDay(for: date) <= endOfMonthCache! {
let periodApart = calendar.dateComponents([.month], from: startOfMonthCache, to: date)
let day = calendar.dateComponents([.day], from: date).day!
guard let monthSectionIndex = periodApart.month else { continue }
let currentMonthInfo = monthInfo[monthSectionIndex]
if let indexPath = currentMonthInfo.indexPath(forDay: day) {
returnPaths.append(indexPath)
}
}
}
return returnPaths
}
func cellStateFromIndexPath(_ indexPath: IndexPath, withDateInfo info: (date: Date, owner: DateOwner)? = nil, cell: JTAppleCell? = nil) -> CellState {
let validDateInfo: (date: Date, owner: DateOwner)
if let nonNilDateInfo = info {
validDateInfo = nonNilDateInfo
} else {
guard let newDateInfo = dateOwnerInfoFromPath(indexPath) else {
developerError(string: "Error this should not be nil. Contact developer Jay on github by opening a request")
return CellState(isSelected: false,
text: "",
dateBelongsTo: .thisMonth,
date: Date(),
day: .sunday,
row: { return 0 },
column: { return 0 },
dateSection: {
return (range: (Date(), Date()), month: 0, rowCount: 0)
},
selectedPosition: {return .left},
cell: {return nil})
}
validDateInfo = newDateInfo
}
let date = validDateInfo.date
let dateBelongsTo = validDateInfo.owner
let currentDay = calendar.component(.day, from: date)
let componentWeekDay = calendar.component(.weekday, from: date)
let cellText = String(describing: currentDay)
let dayOfWeek = DaysOfWeek(rawValue: componentWeekDay)!
let rangePosition = { () -> SelectionRangePosition in
if !self.theSelectedIndexPaths.contains(indexPath) { return .none }
if self.selectedDates.count == 1 { return .full }
guard
let nextIndexPath = self.calendarViewLayout.indexPath(direction: .next, of: indexPath.section, item: indexPath.item),
let previousIndexPath = self.calendarViewLayout.indexPath(direction: .previous, of: indexPath.section, item: indexPath.item) else {
return .full
}
let selectedIndicesContainsPreviousPath = self.theSelectedIndexPaths.contains(previousIndexPath)
let selectedIndicesContainsFollowingPath = self.theSelectedIndexPaths.contains(nextIndexPath)
var position: SelectionRangePosition
if selectedIndicesContainsPreviousPath == selectedIndicesContainsFollowingPath {
position = selectedIndicesContainsPreviousPath == false ? .full : .middle
} else {
position = selectedIndicesContainsPreviousPath == false ? .left : .right
}
return position
}
let cellState = CellState(
isSelected: theSelectedIndexPaths.contains(indexPath),
text: cellText,
dateBelongsTo: dateBelongsTo,
date: date,
day: dayOfWeek,
row: { return indexPath.item / maxNumberOfDaysInWeek },
column: { return indexPath.item % maxNumberOfDaysInWeek },
dateSection: {
return self.monthInfoFromSection(indexPath.section)!
},
selectedPosition: rangePosition,
cell: { return cell }
)
return cellState
}
func batchReloadIndexPaths(_ indexPaths: [IndexPath]) {
let visiblePaths = indexPathsForVisibleItems
var visiblePathsToReload: [IndexPath] = []
var invisiblePathsToRelad: [IndexPath] = []
for path in indexPaths {
if calendarViewLayout.cachedValue(for: path.item, section: path.section) == nil { continue }
if visiblePaths.contains(path) {
visiblePathsToReload.append(path)
} else {
invisiblePathsToRelad.append(path)
}
}
// Reload the invisible paths first.
// Why reload invisible paths? because they have already been prefetched
if !invisiblePathsToRelad.isEmpty {
calendarViewLayout.shouldClearCacheOnInvalidate = false
reloadItems(at: invisiblePathsToRelad)
}
// Reload the visible paths
if !visiblePathsToReload.isEmpty {
UICollectionView.performWithoutAnimation {
self.calendarViewLayout.shouldClearCacheOnInvalidate = false
performBatchUpdates({[unowned self] in
self.reloadItems(at: visiblePathsToReload)
})
}
}
}
func selectDate(indexPath: IndexPath, date: Date, shouldTriggerSelecteionDelegate: Bool) -> Set<IndexPath> {
var allIndexPathsToReload: Set<IndexPath> = []
selectItem(at: indexPath, animated: false, scrollPosition: [])
allIndexPathsToReload.insert(indexPath)
// If triggereing is enabled, then let their delegate
// handle the reloading of view, else we will reload the data
if shouldTriggerSelecteionDelegate {
self.collectionView(self, didSelectItemAt: indexPath)
} else {
// Although we do not want the delegate triggered,
// we still want counterpart cells to be selected
addCellToSelectedSetIfUnselected(indexPath, date: date)
let cellState = self.cellStateFromIndexPath(indexPath)
if isRangeSelectionUsed {
allIndexPathsToReload.formUnion(Set(validForwardAndBackwordSelectedIndexes(forIndexPath: indexPath)))
}
if let aSelectedCounterPartIndexPath = self.selectCounterPartCellIndexPathIfExists(indexPath, date: date, dateOwner: cellState.dateBelongsTo) {
// If there was a counterpart cell then
// it will also need to be reloaded
allIndexPathsToReload.insert(aSelectedCounterPartIndexPath)
if isRangeSelectionUsed {
allIndexPathsToReload.formUnion(Set(validForwardAndBackwordSelectedIndexes(forIndexPath: aSelectedCounterPartIndexPath)))
}
}
}
return allIndexPathsToReload
}
func deselectDate(oldIndexPath: IndexPath, shouldTriggerSelecteionDelegate: Bool) -> Set<IndexPath> {
var allIndexPathsToReload: Set<IndexPath> = []
if let index = self.theSelectedIndexPaths.index(of: oldIndexPath) {
let oldDate = self.theSelectedDates[index]
self.deselectItem(at: oldIndexPath, animated: false)
self.theSelectedIndexPaths.remove(at: index)
self.theSelectedDates.remove(at: index)
// If delegate triggering is enabled, let the
// delegate function handle the cell
if shouldTriggerSelecteionDelegate {
self.collectionView(self, didDeselectItemAt: oldIndexPath)
} else {
// Although we do not want the delegate triggered,
// we still want counterpart cells to be deselected
allIndexPathsToReload.insert(oldIndexPath)
let cellState = self.cellStateFromIndexPath(oldIndexPath)
if isRangeSelectionUsed {
allIndexPathsToReload.formUnion(Set(validForwardAndBackwordSelectedIndexes(forIndexPath: oldIndexPath)))
}
if let anUnselectedCounterPartIndexPath = self.deselectCounterPartCellIndexPath(oldIndexPath, date: oldDate, dateOwner: cellState.dateBelongsTo) {
// If there was a counterpart cell then
// it will also need to be reloaded
allIndexPathsToReload.insert(anUnselectedCounterPartIndexPath)
if isRangeSelectionUsed {
allIndexPathsToReload.formUnion(Set(validForwardAndBackwordSelectedIndexes(forIndexPath: anUnselectedCounterPartIndexPath)))
}
}
}
}
return allIndexPathsToReload
}
func addCellToSelectedSetIfUnselected(_ indexPath: IndexPath, date: Date) {
if self.theSelectedIndexPaths.contains(indexPath) == false {
self.theSelectedIndexPaths.append(indexPath)
self.theSelectedDates.append(date)
}
}
func deleteCellFromSelectedSetIfSelected(_ indexPath: IndexPath) {
if let index = self.theSelectedIndexPaths.index(of: indexPath) {
self.theSelectedIndexPaths.remove(at: index)
self.theSelectedDates.remove(at: index)
}
}
func deselectCounterPartCellIndexPath(_ indexPath: IndexPath, date: Date, dateOwner: DateOwner) -> IndexPath? {
if let counterPartCellIndexPath = indexPathOfdateCellCounterPath(date, dateOwner: dateOwner) {
deleteCellFromSelectedSetIfSelected(counterPartCellIndexPath)
return counterPartCellIndexPath
}
return nil
}
func selectCounterPartCellIndexPathIfExists(_ indexPath: IndexPath, date: Date, dateOwner: DateOwner) -> IndexPath? {
if let counterPartCellIndexPath = indexPathOfdateCellCounterPath(date, dateOwner: dateOwner) {
let dateComps = calendar.dateComponents([.month, .day, .year], from: date)
guard let counterpartDate = calendar.date(from: dateComps) else {
return nil
}
addCellToSelectedSetIfUnselected(counterPartCellIndexPath, date: counterpartDate)
return counterPartCellIndexPath
}
return nil
}
func monthInfoFromSection(_ section: Int) -> (range: (start: Date, end: Date), month: Int, rowCount: Int)? {
guard let monthIndex = monthMap[section] else {
return nil
}
let monthData = monthInfo[monthIndex]
guard
let monthDataMapSection = monthData.sectionIndexMaps[section],
let indices = monthData.boundaryIndicesFor(section: monthDataMapSection) else {
return nil
}
let startIndexPath = IndexPath(item: indices.startIndex, section: section)
let endIndexPath = IndexPath(item: indices.endIndex, section: section)
guard
let startDate = dateOwnerInfoFromPath(startIndexPath)?.date,
let endDate = dateOwnerInfoFromPath(endIndexPath)?.date else {
return nil
}
if let monthDate = calendar.date(byAdding: .month, value: monthIndex, to: startDateCache) {
let monthNumber = calendar.dateComponents([.month], from: monthDate)
let numberOfRowsForSection = monthData.numberOfRows(for: section, developerSetRows: cachedConfiguration.numberOfRows)
return ((startDate, endDate), monthNumber.month!, numberOfRowsForSection)
}
return nil
}
/// Retrieves the current section
public func currentSection() -> Int? {
let minVisiblePaths = calendarViewLayout.minimumVisibleIndexPaths()
return minVisiblePaths.cellIndex?.section
}
func dateSegmentInfoFrom(visible indexPaths: [IndexPath]) -> DateSegmentInfo {
var inDates = [(Date, IndexPath)]()
var monthDates = [(Date, IndexPath)]()
var outDates = [(Date, IndexPath)]()
for indexPath in indexPaths {
let info = dateOwnerInfoFromPath(indexPath)
if let validInfo = info {
switch validInfo.owner {
case .thisMonth:
monthDates.append((validInfo.date, indexPath))
case .previousMonthWithinBoundary, .previousMonthOutsideBoundary:
inDates.append((validInfo.date, indexPath))
default:
outDates.append((validInfo.date, indexPath))
}
}
}
let retval = DateSegmentInfo(indates: inDates, monthDates: monthDates, outdates: outDates)
return retval
}
func dateOwnerInfoFromPath(_ indexPath: IndexPath) -> (date: Date, owner: DateOwner)? { // Returns nil if date is out of scope
guard let monthIndex = monthMap[indexPath.section] else {
return nil
}
let monthData = monthInfo[monthIndex]
// Calculate the offset
let offSet: Int
var numberOfDaysToAddToOffset: Int = 0
switch monthData.sectionIndexMaps[indexPath.section]! {
case 0:
offSet = monthData.inDates
default:
offSet = 0
let currentSectionIndexMap = monthData.sectionIndexMaps[indexPath.section]!
numberOfDaysToAddToOffset = monthData.sections[0..<currentSectionIndexMap].reduce(0, +)
numberOfDaysToAddToOffset -= monthData.inDates
}
var dayIndex = 0
var dateOwner: DateOwner = .thisMonth
let date: Date?
if indexPath.item >= offSet && indexPath.item + numberOfDaysToAddToOffset < monthData.numberOfDaysInMonth + offSet {
// This is a month date
dayIndex = monthData.startDayIndex + indexPath.item - offSet + numberOfDaysToAddToOffset
date = calendar.date(byAdding: .day, value: dayIndex, to: startOfMonthCache)
} else if indexPath.item < offSet {
// This is a preDate
dayIndex = indexPath.item - offSet + monthData.startDayIndex
date = calendar.date(byAdding: .day, value: dayIndex, to: startOfMonthCache)
if date! < startOfMonthCache {
dateOwner = .previousMonthOutsideBoundary
} else {
dateOwner = .previousMonthWithinBoundary
}
} else {
// This is a postDate
dayIndex = monthData.startDayIndex - offSet + indexPath.item + numberOfDaysToAddToOffset
date = calendar.date(byAdding: .day, value: dayIndex, to: startOfMonthCache)
if date! > endOfMonthCache {
dateOwner = .followingMonthOutsideBoundary
} else {
dateOwner = .followingMonthWithinBoundary
}
}
guard let validDate = date else { return nil }
return (validDate, dateOwner)
}
}
| mit | 30116e2bc91c54c468ece11919d3b8b1 | 46.253165 | 205 | 0.613056 | 5.857453 | false | false | false | false |
carabina/AlecrimAsyncKit | Source/AlecrimAsyncKit/Core/Task.swift | 1 | 7601 | //
// Task.swift
// AlecrimAsyncKit
//
// Created by Vanderlei Martinelli on 2015-05-10.
// Copyright (c) 2015 Alecrim. All rights reserved.
//
import Foundation
internal let taskCancelledError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil)
// MARK: - protocols needed to support task observers in this version
public protocol TaskType: class {
}
public protocol FailableTaskType: TaskType {
func cancel()
}
public protocol NonFailableTaskType: TaskType {
}
// MARK: -
public class BaseTask<V>: TaskType {
public private(set) var value: V!
public private(set) var error: ErrorType?
private let dispatchGroup: dispatch_group_t = dispatch_group_create()
private var waiting = true
private var spinlock = OS_SPINLOCK_INIT
private var deferredClosures: Array<() -> Void>?
private init() {
dispatch_group_enter(self.dispatchGroup)
}
deinit {
withUnsafeMutablePointer(&self.spinlock, OSSpinLockLock)
assert(!self.waiting, "Either value or error were never assigned or task was never cancelled.")
withUnsafeMutablePointer(&self.spinlock, OSSpinLockUnlock)
}
private final func waitForCompletion() {
assert(!NSThread.isMainThread(), "Cannot wait task on main thread.")
dispatch_group_wait(self.dispatchGroup, DISPATCH_TIME_FOREVER)
}
private final func setValue(value: V?, error: ErrorType?) {
withUnsafeMutablePointer(&self.spinlock, OSSpinLockLock)
defer {
withUnsafeMutablePointer(&self.spinlock, OSSpinLockUnlock)
//
self.deferredClosures?.forEach { $0() }
self.deferredClosures = nil
}
// assert(self.value == nil && self.error == nil, "value or error can be assigned only once.")
// we do not assert anymore, but the value or error can be assigned only once anyway
guard self.value == nil && self.error == nil else { return }
assert(value != nil || error != nil, "Invalid combination of value/error.")
if let error = error {
self.value = nil
self.error = error
}
else {
self.value = value
self.error = nil
}
self.waiting = false
//
dispatch_group_leave(self.dispatchGroup)
}
// MARK: -
public final func finish() {
if V.self is Void.Type {
self.setValue((() as! V), error: nil)
}
else {
fatalError("`Self.ValueType` is not `Void`.")
}
}
public final func finishWithValue(value: V) {
self.setValue(value, error: nil)
}
// MARK: -
private func addDeferredClosure(deferredClosure: () -> Void) {
if self.deferredClosures == nil {
self.deferredClosures = [deferredClosure]
}
else {
self.deferredClosures!.append(deferredClosure)
}
}
}
public final class Task<V>: BaseTask<V>, FailableTaskType {
public var cancelled: Bool {
var c = false
withUnsafeMutablePointer(&self.spinlock, OSSpinLockLock)
if let error = self.error as? NSError where error.code == NSUserCancelledError {
c = true
}
withUnsafeMutablePointer(&self.spinlock, OSSpinLockUnlock)
return c
}
internal init(queue: NSOperationQueue, observers: [TaskObserver]?, conditions: [TaskCondition]?, closure: (Task<V>) -> Void) {
assert(queue.maxConcurrentOperationCount == NSOperationQueueDefaultMaxConcurrentOperationCount || queue.maxConcurrentOperationCount > 1, "Task `queue` cannot be the main queue nor a serial queue.")
super.init()
queue.addOperationWithBlock {
do {
//
if let conditions = conditions where !conditions.isEmpty {
//
guard !self.cancelled else { return }
//
let mutuallyExclusiveConditions = conditions.flatMap { $0 as? MutuallyExclusiveTaskCondition }
if !mutuallyExclusiveConditions.isEmpty {
mutuallyExclusiveConditions.forEach { mutuallyExclusiveCondition in
MutuallyExclusiveTaskCondition.increment(mutuallyExclusiveCondition.categoryName)
}
self.addDeferredClosure {
mutuallyExclusiveConditions.forEach { mutuallyExclusiveCondition in
MutuallyExclusiveTaskCondition.decrement(mutuallyExclusiveCondition.categoryName)
}
}
}
//
try await(TaskCondition.asyncEvaluateConditions(conditions))
}
//
guard !self.cancelled else { return }
//
if let observers = observers where !observers.isEmpty {
observers.forEach { $0.taskDidStart(self) }
self.addDeferredClosure { [unowned self] in
observers.forEach { $0.taskDidFinish(self) }
}
}
//
closure(self)
}
catch let error {
self.finishWithError(error)
}
}
}
@warn_unused_result
internal func waitForCompletionAndReturnValue() throws -> V {
self.waitForCompletion()
if let error = self.error {
throw error
}
else {
return self.value
}
}
public func finishWithError(error: ErrorType) {
self.setValue(nil, error: error)
}
public func finishWithValue(value: V?, error: ErrorType?) {
self.setValue(value, error: error)
}
// MARK: -
public func cancel() {
self.setValue(nil, error: taskCancelledError)
}
// MARK: -
public func continueWithTask(task: Task<V>) {
do {
let value = try task.waitForCompletionAndReturnValue()
self.finishWithValue(value)
}
catch let error {
self.finishWithError(error)
}
}
}
public final class NonFailableTask<V>: BaseTask<V>, NonFailableTaskType {
internal init(queue: NSOperationQueue, observers: [TaskObserver]?, closure: (NonFailableTask<V>) -> Void) {
assert(queue.maxConcurrentOperationCount == NSOperationQueueDefaultMaxConcurrentOperationCount || queue.maxConcurrentOperationCount > 1, "Task `queue` cannot be the main queue nor a serial queue.")
super.init()
queue.addOperationWithBlock {
if let observers = observers where !observers.isEmpty {
observers.forEach { $0.taskDidStart(self) }
self.addDeferredClosure { [unowned self] in
observers.forEach { $0.taskDidFinish(self) }
}
}
closure(self)
}
}
@warn_unused_result
internal func waitForCompletionAndReturnValue() -> V {
self.waitForCompletion()
return self.value
}
// MARK: -
public func continueWithTask(task: NonFailableTask<V>) {
let value = task.waitForCompletionAndReturnValue()
self.finishWithValue(value)
}
}
| mit | 298f75520e5edadbdd428ef3c160ba2b | 29.773279 | 205 | 0.571898 | 5.167233 | false | false | false | false |
tvolkert/plugins | packages/url_launcher/url_launcher_macos/macos/Classes/UrlLauncherPlugin.swift | 1 | 1639 | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import FlutterMacOS
import Foundation
public class UrlLauncherPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(
name: "plugins.flutter.io/url_launcher",
binaryMessenger: registrar.messenger)
let instance = UrlLauncherPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let urlString: String? = (call.arguments as? [String: Any])?["url"] as? String
switch call.method {
case "canLaunch":
guard let unwrappedURLString = urlString,
let url = URL.init(string: unwrappedURLString)
else {
result(invalidURLError(urlString))
return
}
result(NSWorkspace.shared.urlForApplication(toOpen: url) != nil)
case "launch":
guard let unwrappedURLString = urlString,
let url = URL.init(string: unwrappedURLString)
else {
result(invalidURLError(urlString))
return
}
result(NSWorkspace.shared.open(url))
default:
result(FlutterMethodNotImplemented)
}
}
}
/// Returns an error for the case where a URL string can't be parsed as a URL.
private func invalidURLError(_ url: String?) -> FlutterError {
return FlutterError(
code: "argument_error",
message: "Unable to parse URL",
details: "Provided URL: \(String(describing: url))")
}
| bsd-3-clause | cc94947b5761f9b5027ff9e932033862 | 33.145833 | 82 | 0.696156 | 4.453804 | false | false | false | false |
JayGajjar/JGTransitionCollectionView | JGTransitionCollectionView/classes/JGTransitionCollectionView.swift | 1 | 5167 | //
// JGTransitionCollectionView.swift
// JGTransitionCollectionView
//
// Created by Jay on 23/03/15.
// Copyright (c) 2015 Jay. All rights reserved.
//
import Foundation
import UIKit
protocol JGTransitionCollectionViewDatasource: UICollectionViewDataSource {
func collectionView(_ JGcollectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
func collectionView(_ JGCollectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
}
class JGTransitionCollectionView: UICollectionView,UICollectionViewDataSource {
var jgDatasource : JGTransitionCollectionViewDatasource?
var dataArray : NSMutableArray = NSMutableArray() {
didSet {
self.secondaryDataArray.add(dataArray.firstObject!)
self.animate = true
}
}
var secondaryDataArray : NSMutableArray = NSMutableArray()
fileprivate var animate : Bool = true
// MARK: Initialisation
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
//self.delegate = self
self.dataSource = self
}
// MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.secondaryDataArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : UICollectionViewCell = jgDatasource!.collectionView(self, cellForItemAt: indexPath)
cell.backgroundColor = UIColor.clear
if (indexPath.row == secondaryDataArray.count-1 && indexPath.row < 8 && animate == true) {
self.animate = false
let progress = 0.0
var transform = CATransform3DIdentity
transform.m34 = -1.0/500.0
let angle = (1 - progress) * Double.pi/2
if ((indexPath.row) % 4 == 3) {
//left (perfect)
self.setAnchorPoint(CGPoint(x: 1, y: 0.5), view: cell.contentView)
transform = CATransform3DRotate(transform, CGFloat(-angle), 0, 1, 0 )
}else if ((indexPath.row) % 4 == 2){
//bottom followed by right
self.setAnchorPoint(CGPoint(x: 0.5, y: 0), view: cell.contentView)
transform = CATransform3DRotate(transform, CGFloat(-angle), 1, 0, 0 )
}else if ((indexPath.row) % 4 == 1){
//right (prtfect)
self.setAnchorPoint(CGPoint(x: 0, y: 0.5), view: cell.contentView)
transform = CATransform3DRotate(transform, CGFloat(angle), 0, 1, 0 )
}else if ((indexPath.row) % 4 == 0){
//bottm
self.setAnchorPoint(CGPoint(x: 0.5, y: 0), view: cell.contentView)
transform = CATransform3DRotate(transform, CGFloat(-angle), 1, 0, 0 )
}
cell.contentView.layer.transform = transform
UIView.animate(withDuration: 0.5, animations: {
cell.contentView.layer.transform = CATransform3DIdentity
}, completion: { (finished) in
cell.contentView.layer.transform = CATransform3DIdentity
self.animate = true
self.reloadDataWithTransition(indexPath)
})
}
return cell
}
func reloadDataWithTransition(_ indexPath : IndexPath) {
if (indexPath.row < self.dataArray.count-1 && indexPath.row < 8 && self.animate == true) {
self.secondaryDataArray.add(self.dataArray[(indexPath.row+1)])
// self.insertItemsAtIndexPaths([NSIndexPath(forItem: indexPath.row+1, inSection: indexPath.section)])
self.reloadData()
if indexPath.row == 6 {
self.animate = false
self.secondaryDataArray = self.dataArray
self.reloadData()
}else{
self.animate = true
}
}else{
self.animate = false
self.dataArray = self.secondaryDataArray
}
}
// MARK: HelperMethods
func setAnchorPoint(_ anchorPoint : CGPoint, view : UIView) {
var newPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y);
var oldPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y);
newPoint = newPoint.applying(view.transform);
oldPoint = oldPoint.applying(view.transform);
var position = view.layer.position;
position.x -= oldPoint.x;
position.x += newPoint.x;
position.y -= oldPoint.y;
position.y += newPoint.y;
view.layer.position = position;
view.layer.anchorPoint = anchorPoint;
}
}
| mit | 9234b0061ec0824501d516cfc3e81234 | 39.367188 | 140 | 0.611573 | 4.828972 | false | false | false | false |
maurovc/MyMarvel | MyMarvel/DataDownloader.swift | 1 | 21668 | //
// DataDownloader.swift
// MyMarvel
//
// Created by Mauro Vime Castillo on 25/10/16.
// Copyright © 2016 Mauro Vime Castillo. All rights reserved.
//
import Foundation
import AFNetworking
typealias DefaultBlock = (succeeded: Bool, error:NSError?) -> Void
typealias HeroBlock = (succeeded: Bool, hero: Hero?, error:NSError?) -> Void
typealias ElementsBlock = (succeeded: Bool, elements: [Element]?, error:NSError?) -> Void
/**
LoadingState is an enumeration used to handle the state of the API calls.
- Loading: When the API hasn't sent a response.
- Idle: When we aren't loading anything from the API.
- Error: If the API has thrown an error.
*/
enum LoadingState: Int {
case Loading
case Idle
case Error
}
/// DataDownloader is the class that manages all the calls to the API.
class DataDownloader {
/// Singleton for shared instance.
static let sharedDownloader = DataDownloader()
/// Host of the API.
static let host = "https://gateway.marvel.com"
/// Path for the characters list API call.
let charactersPath = "/v1/public/characters"
/// Public key.
var apiKey = ""
/// Private key.
var privateApiKey = ""
/// Variable used to define if we need to parse the characters by name.
var searchName: String?
/// Variable used to define an offset and skip a certain number of results in the characters list method call.
var offset = 0
/// Variable used to define a limit of response elements in the characters list method call.
let limit = 50
/// Variable used to store the total number of elements that the API has stored to response to the characters list method call.
var total = -1
/// List of heroes returned by the API.
var heroes: [Hero]?
/// Manager used to create the API requests.
let manager: AFHTTPRequestOperationManager = {
let manager = AFHTTPRequestOperationManager(baseURL: NSURL(string: host))
manager.responseSerializer = AFJSONResponseSerializer()
return manager
}()
/// Variable used to manage the loading calls to the characters list method.
var state = LoadingState.Idle
/// Variable used to store the block from last characters list method call.
var myBlock: DefaultBlock?
}
//MARK: Helper functions.
extension DataDownloader {
/**
This method instantiates the class with the provided keys.
- Parameter publicKey: The public key as a `String`.
- Parameter privateKey: The private key as a `String`.
*/
func configureKeys(publicKey publicKey: String, privateKey: String) {
apiKey = publicKey
privateApiKey = privateKey
}
/**
This method resets all the properties of the class.
*/
func reset() {
searchName = nil
refreshForPool()
}
/**
This method resets some properties of the class after a "pull to refresh".
*/
func refreshForPool() {
heroes = nil
offset = 0
total = -1
state = .Idle
manager.operationQueue.cancelAllOperations()
}
/**
Helper method that indicates if there are more heroes to load from the API.
*/
func hasMore() -> Bool {
return (offset < total) || ((offset == 0) && (total == -1))
}
}
//MARK: Download heroes
extension DataDownloader {
/**
This method creates a Dictionary with the Headers for getting a list of heroes ordered by name.
- Returns: A Dictionary of type `[String: String]`.
*/
func heroesParameters() -> [String: String] {
let timestamp = NSDate().timestamp() ?? ""
let hash = (timestamp + privateApiKey + apiKey).md5Hash() ?? ""
var parameters = ["orderBy": "name",
"apikey": apiKey,
"ts": timestamp,
"limit": "\(limit)",
"offset": "\(offset)",
"hash": hash]
if let searchName = searchName {
parameters["nameStartsWith"] = searchName
}
return parameters
}
/**
This method downloads the next page of heroes.
- Parameter block: Response handler of type `DefaultBlock`.
*/
func downloadNextPage(block: DefaultBlock?) {
myBlock = block
if state != .Idle {
return
}
state = .Loading
let parameters = heroesParameters()
if let urlString = NSURL(string: charactersPath, relativeToURL: NSURL(string: DataDownloader.host))?.absoluteString.urlWithParameters(parameters) {
var error: NSError?
let request = manager.requestSerializer.requestWithMethod("GET", URLString: urlString, parameters: [], error: &error)
let operation = manager.HTTPRequestOperationWithRequest(request, success: { (operation, response) in
if let response = response as? JSON, let code = response["code"] as? NSNumber, let data = response["data"] as? [String: AnyObject] {
let succeeded = self.parseData(data)
self.state = .Idle
self.myBlock?(succeeded: (succeeded && (code.intValue == 200)), error: nil)
} else {
self.state = .Error
self.myBlock?(succeeded: false, error: nil)
}
}, failure: { (operation, error) in
self.state = .Error
self.myBlock?(succeeded: false, error: error)
})
manager.operationQueue.addOperation(operation)
} else {
myBlock?(succeeded: false, error: nil)
}
}
/**
This method parses the response from `downloadNextPage(block:)`.
- Parameter data: The response from the server in `JSON` format.
- Returns: This method resturns a `Bool` indicating if the parse has finished successfully.
*/
func parseData(data: JSON) -> Bool {
if total == -1 {
heroes = [Hero]()
}
guard let newOffset = data["count"] as? NSNumber, let newTotal = data["total"] as? NSNumber, let results = data["results"] as? [[String: AnyObject]] else {
return false
}
offset += newOffset.integerValue
total = newTotal.integerValue
heroes?.appendContentsOf(results.map { Hero(json: $0) })
return true
}
}
//MARK: Download a certain hero
extension DataDownloader {
/**
This method creates a Dictionary with the Headers for getting a certain hero.
- Returns: A Dictionary of type `[String: String]`.
*/
func heroParameters() -> [String: String] {
let timestamp = NSDate().timestamp() ?? ""
let hash = (timestamp + privateApiKey + apiKey).md5Hash() ?? ""
var parameters = ["apikey": apiKey,
"ts": timestamp,"hash": hash]
if let searchName = searchName {
parameters["nameStartsWith"] = searchName
}
return parameters
}
/**
This method loads a certain hero.
- Parameter characterId: The identifier of a hero object represented in `String` type.
- Parameter block: Response handler of type `HeroBlock`.
*/
func loadHero(characterId: String, block: HeroBlock?) {
let comicPath = "/v1/public/characters/\(characterId)"
let parameters = heroParameters()
if let urlString = NSURL(string: comicPath, relativeToURL: NSURL(string: DataDownloader.host))?.absoluteString.urlWithParameters(parameters) {
var error: NSError?
let request = manager.requestSerializer.requestWithMethod("GET", URLString: urlString, parameters: [], error: &error)
let operation = manager.HTTPRequestOperationWithRequest(request, success: { (operation, response) in
if let response = response as? JSON, let code = response["code"] as? NSNumber, let data = response["data"] as? [String: AnyObject], let results = data["results"] as? [[String: AnyObject]] where results.count > 0 {
let hero = Hero(json: results[0])
block?(succeeded: (code.intValue == 200), hero: hero, error: nil)
} else {
block?(succeeded: false, hero: nil, error: nil)
}
}, failure: { (operation, error) in
block?(succeeded: false, hero: nil, error: error)
})
manager.operationQueue.addOperation(operation)
} else {
block?(succeeded: false, hero: nil, error: nil)
}
}
}
//MARK: Download comics
extension DataDownloader {
/**
This method creates a Dictionary with the Headers for getting a list of comics, from a certain hero, ordered by title.
- Parameter offset: `Int` variable used to skip the N first elements of the API.
- Returns: A Dictionary of type `[String: String]`.
*/
func comicParameters(offset: Int) -> [String: String] {
let timestamp = NSDate().timestamp() ?? ""
let hash = (timestamp + privateApiKey + apiKey).md5Hash() ?? ""
let parameters = ["orderBy": "title",
"apikey": apiKey,
"ts": timestamp,
"limit": "\(limit)",
"offset": "\(offset)",
"hash": hash]
return parameters
}
/**
This method loads all the comics from a certain hero.
- Parameter characterId: The identifier of a hero object represented in `String` type.
- Parameter offset: `Int` variable used to skip the N first elements of the API.
- Parameter block: Response handler of type `ElementsBlock`.
*/
func getComicsForCharacter(characterId: String?, offset: Int, block: ElementsBlock?) {
guard let characterId = characterId else {
block?(succeeded: false, elements: nil, error: nil)
return
}
let comicPath = "/v1/public/characters/\(characterId)/comics"
let parameters = comicParameters(offset)
if let urlString = NSURL(string: comicPath, relativeToURL: NSURL(string: DataDownloader.host))?.absoluteString.urlWithParameters(parameters) {
var error: NSError?
let request = manager.requestSerializer.requestWithMethod("GET", URLString: urlString, parameters: [], error: &error)
let operation = manager.HTTPRequestOperationWithRequest(request, success: { (operation, response) in
if let response = response as? JSON, let code = response["code"] as? NSNumber, let data = response["data"] as? [String: AnyObject] {
let comics = self.parseComicsData(data)
block?(succeeded: (code.intValue == 200), elements: comics, error: nil)
} else {
block?(succeeded: false, elements: nil, error: nil)
}
}, failure: { (operation, error) in
block?(succeeded: false, elements: nil, error: error)
})
manager.operationQueue.addOperation(operation)
} else {
block?(succeeded: false, elements: nil, error: nil)
}
}
/**
Method that parses the response from `getComicsForCharacter(characterId:, offset:, block:)`.
- Parameter data: The response from the server in `JSON` format.
- Returns: A `Bool` indicating if the parse has finished successfully.
*/
func parseComicsData(data: JSON) -> [Comic]? {
guard let results = data["results"] as? [[String: AnyObject]] else {
return nil
}
return results.map { Comic(json: $0) }
}
}
//MARK: Download series
extension DataDownloader {
/**
This method creates a Dictionary with the Headers for getting a list of series, from a certain hero, ordered by title.
- Parameter offset: `Int` variable used to skip the N first elements of the API.
- Returns: A Dictionary of type `[String: String]`.
*/
func serieParameters(offset: Int) -> [String: String] {
let timestamp = NSDate().timestamp() ?? ""
let hash = (timestamp + privateApiKey + apiKey).md5Hash() ?? ""
let parameters = ["orderBy": "title",
"apikey": apiKey,
"ts": timestamp,
"limit": "\(limit)",
"offset": "\(offset)",
"hash": hash]
return parameters
}
/**
This method loads all the series from a certain hero.
- Parameter characterId: The identifier of a hero object represented in `String` type.
- Parameter offset: `Int` variable used to skip the N first elements of the API.
- Parameter block: Response handler of type `ElementsBlock`.
*/
func getSeriesForCharacter(characterId: String?, offset: Int, block: ElementsBlock?) {
guard let characterId = characterId else {
block?(succeeded: false, elements: nil, error: nil)
return
}
let seriePath = "/v1/public/characters/\(characterId)/series"
let parameters = serieParameters(offset)
if let urlString = NSURL(string: seriePath, relativeToURL: NSURL(string: DataDownloader.host))?.absoluteString.urlWithParameters(parameters) {
var error: NSError?
let request = manager.requestSerializer.requestWithMethod("GET", URLString: urlString, parameters: [], error: &error)
let operation = manager.HTTPRequestOperationWithRequest(request, success: { (operation, response) in
if let response = response as? JSON, let code = response["code"] as? NSNumber, let data = response["data"] as? [String: AnyObject] {
let series = self.parseSeriesData(data)
block?(succeeded: (code.intValue == 200), elements: series, error: nil)
} else {
block?(succeeded: false, elements: nil, error: nil)
}
}, failure: { (operation, error) in
block?(succeeded: false, elements: nil, error: error)
})
manager.operationQueue.addOperation(operation)
} else {
block?(succeeded: false, elements: nil, error: nil)
}
}
/**
Method that parses the response from `getSeriesForCharacter(characterId:, offset:, block:)`.
- Parameter data: The response from the server in `JSON` format.
- Returns: A `Bool` indicating if the parse has finished successfully.
*/
func parseSeriesData(data: JSON) -> [Serie]? {
guard let results = data["results"] as? [[String: AnyObject]] else {
return nil
}
return results.map { Serie(json: $0) }
}
}
//MARK: Download events
extension DataDownloader {
/**
This method creates a Dictionary with the Headers for getting a list of events, from a certain hero, ordered by title.
- Parameter offset: `Int` variable used to skip the N first elements of the API.
- Returns: A Dictionary of type `[String: String]`.
*/
func eventParameters(offset: Int) -> [String: String] {
let timestamp = NSDate().timestamp() ?? ""
let hash = (timestamp + privateApiKey + apiKey).md5Hash() ?? ""
let parameters = ["orderBy": "name",
"apikey": apiKey,
"ts": timestamp,
"limit": "\(limit)",
"offset": "\(offset)",
"hash": hash]
return parameters
}
/**
This method loads all the events from a certain hero.
- Parameter characterId: The identifier of a hero object represented in `String` type.
- Parameter offset: `Int` variable used to skip the N first elements of the API.
- Parameter block: Response handler of type `ElementsBlock`.
*/
func getEventsForCharacter(characterId: String?, offset: Int, block: ElementsBlock?) {
guard let characterId = characterId else {
block?(succeeded: false, elements: nil, error: nil)
return
}
let eventPath = "/v1/public/characters/\(characterId)/events"
let parameters = eventParameters(offset)
if let urlString = NSURL(string: eventPath, relativeToURL: NSURL(string: DataDownloader.host))?.absoluteString.urlWithParameters(parameters) {
var error: NSError?
let request = manager.requestSerializer.requestWithMethod("GET", URLString: urlString, parameters: [], error: &error)
let operation = manager.HTTPRequestOperationWithRequest(request, success: { (operation, response) in
if let response = response as? JSON, let code = response["code"] as? NSNumber, let data = response["data"] as? [String: AnyObject] {
let events = self.parseEventsData(data)
block?(succeeded: (code.intValue == 200), elements: events, error: nil)
} else {
block?(succeeded: false, elements: nil, error: nil)
}
}, failure: { (operation, error) in
block?(succeeded: false, elements: nil, error: error)
})
manager.operationQueue.addOperation(operation)
} else {
block?(succeeded: false, elements: nil, error: nil)
}
}
/**
Method that parses the response from `getEventsForCharacter(characterId:, offset:, block:)`.
- Parameter data: The response from the server in *JSON* format.
- Returns: A *Bool* indicating if the parse has finished successfully.
*/
func parseEventsData(data: JSON) -> [Event]? {
guard let results = data["results"] as? [[String: AnyObject]] else {
return nil
}
return results.map { Event(json: $0) }
}
}
//MARK: Download stories
extension DataDownloader {
/**
This method creates a Dictionary with the Headers for getting a list of stories, from a certain hero, ordered by title.
- Parameter offset: `Int` variable used to skip the N first elements of the API.
- Returns: A Dictionary of type `[String: String]`.
*/
func storyParameters(offset: Int) -> [String: String] {
let timestamp = NSDate().timestamp() ?? ""
let hash = (timestamp + privateApiKey + apiKey).md5Hash() ?? ""
let parameters = ["orderBy": "id",
"apikey": apiKey,
"ts": timestamp,
"limit": "\(limit)",
"offset": "\(offset)",
"hash": hash]
return parameters
}
/**
This method loads all the stories from a certain hero.
- Parameter characterId: The identifier of a hero object represented in `String` type.
- Parameter offset: `Int` variable used to skip the N first elements of the API.
- Parameter block: Response handler of type `ElementsBlock`.
*/
func getStoriesForCharacter(characterId: String?, offset: Int, block: ElementsBlock?) {
guard let characterId = characterId else {
block?(succeeded: false, elements: nil, error: nil)
return
}
let storyPath = "/v1/public/characters/\(characterId)/stories"
let parameters = storyParameters(offset)
if let urlString = NSURL(string: storyPath, relativeToURL: NSURL(string: DataDownloader.host))?.absoluteString.urlWithParameters(parameters) {
var error: NSError?
let request = manager.requestSerializer.requestWithMethod("GET", URLString: urlString, parameters: [], error: &error)
let operation = manager.HTTPRequestOperationWithRequest(request, success: { (operation, response) in
if let response = response as? JSON, let code = response["code"] as? NSNumber, let data = response["data"] as? [String: AnyObject] {
let stories = self.parseStoriesData(data)
block?(succeeded: (code.intValue == 200), elements: stories, error: nil)
} else {
block?(succeeded: false, elements: nil, error: nil)
}
}, failure: { (operation, error) in
block?(succeeded: false, elements: nil, error: error)
})
manager.operationQueue.addOperation(operation)
} else {
myBlock?(succeeded: false, error: nil)
}
}
/**
Method that parses the response from `getStoriesForCharacter(characterId:, offset:, block:)`.
- Parameter data: The response from the server in `JSON` format.
- Returns: A `Bool` indicating if the parse has finished successfully.
*/
func parseStoriesData(data: JSON) -> [Story]? {
guard let results = data["results"] as? [[String: AnyObject]] else {
return nil
}
return results.map { Story(json: $0) }
}
} | mit | 426f86abce2728bd6291c7954d05fffe | 37.215168 | 229 | 0.582453 | 4.899819 | false | false | false | false |
dooch/mySwiftStarterApp | SwiftWeather/WeatherViewController.swift | 1 | 5105 | //
// Created by Jake Lin on 8/18/15.
// Copyright © 2015 Jake Lin. All rights reserved.
//
import UIKit
class WeatherViewController: UIViewController, UIPageViewControllerDataSource {
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var iconLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet var forecastViews: [ForecastView]!
@IBOutlet weak var mSwitch: UISwitch!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "push")
{
var state:String
if (mSwitch.on)
{
state = "ON"
}
else
{
state = "OFF"
}
(segue.destinationViewController as! SecondViewController).data = state
}
}
//Adding in code to add a UIPageviewController
var pageViewController: UIPageViewController!
var pageTitles: NSArray!
var pageImages: NSArray!
override func viewDidLoad() {
super.viewDidLoad()
viewModel = WeatherViewModel()
viewModel?.startLocationService()
self.pageTitles = NSArray(objects: "Explore", "Today Widget")
self.pageImages = NSArray(objects: "page1","page2")
self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
self.pageViewController.dataSource = self
var startVC = self.viewControllerAtIndex(0) as ContentViewController
var viewControllers = NSArray(object: startVC)
self.pageViewController.setViewControllers(viewControllers as! [UIViewController], direction: .Forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRectMake(0, 30, self.view.frame.width, self.view.frame.size.height - 60)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
}
@IBAction func restartAction(sender: AnyObject) {
var startVC = self.viewControllerAtIndex(0) as ContentViewController
var viewControllers = NSArray(object: startVC)
self.pageViewController.setViewControllers(viewControllers as! [UIViewController], direction: .Forward, animated: true, completion: nil)
}
func viewControllerAtIndex(index: Int) -> ContentViewController
{
if ((self.pageTitles.count == 0) || (index >= self.pageTitles.count))
{
return ContentViewController()
}
var vc: ContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController
vc.imageFile = self.pageImages[index] as! String
vc.titleText = self.pageTitles[index] as! String
vc.pageIndex = index
return vc
}
//MARK : Page View Controller Data Source
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if (index == 0 || index == NSNotFound)
{
return nil
}
index--
return self.viewControllerAtIndex(index)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if (index == NSNotFound)
{
return nil
}
index++
if (index == self.pageTitles.count)
{
return nil
}
return self.viewControllerAtIndex(index)
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return self.pageTitles.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
// MARK: ViewModel
var viewModel: WeatherViewModel? {
didSet {
viewModel?.location.observe {
[unowned self] in
self.locationLabel.text = $0
}
viewModel?.iconText.observe {
[unowned self] in
self.iconLabel.text = $0
}
viewModel?.temperature.observe {
[unowned self] in
self.temperatureLabel.text = $0
}
viewModel?.forecasts.observe {
[unowned self] (let forecastViewModels) in
if forecastViewModels.count >= 4 {
for (index, forecastView) in self.forecastViews.enumerate() {
forecastView.loadViewModel(forecastViewModels[index])
}
}
}
}
}
}
| mit | 337bfa98f6ed188fa036951724d9395a | 28.674419 | 161 | 0.630682 | 5.590361 | false | false | false | false |
rambler-digital-solutions/rambler-it-ios | Carthage/Checkouts/rides-ios-sdk/source/UberRides/Model/TimeEstimate.swift | 1 | 2452 | //
// TimeEstimate.swift
// UberRides
//
// Copyright © 2015 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// MARK: TimeEstimates
/**
* Internal object that contains a list of ETAs for Uber products.
*/
struct TimeEstimates: Codable {
var list: [TimeEstimate]?
enum CodingKeys: String, CodingKey {
case list = "times"
}
}
// MARK: TimeEstimate
/**
* Contains information regarding the ETA of an Uber product.
*/
@objc(UBSDKTimeEstimate) public class TimeEstimate: NSObject, Codable {
/// Unique identifier representing a specific product for a given latitude & longitude.
@objc public private(set) var productID: String
/// Display name of product. Ex: "UberBLACK".
@objc public private(set) var name: String
/// ETA for the product (in seconds).
@objc public private(set) var estimate: Int
enum CodingKeys: String, CodingKey {
case productID = "product_id"
case name = "display_name"
case estimate = "estimate"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
productID = try container.decode(String.self, forKey: .productID)
name = try container.decode(String.self, forKey: .name)
estimate = try container.decode(Int.self, forKey: .estimate)
}
}
| mit | c58227345d624acd9a94775ee7591c2e | 36.707692 | 91 | 0.70869 | 4.277487 | false | false | false | false |
ahoppen/swift | test/Concurrency/Runtime/async_task_locals_copy_to_sync.swift | 5 | 2239 | // RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library %import-libdispatch) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// rdar://76038845
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
// Disable on cooperative executor because it can't dispatch jobs before the end of main function
// UNSUPPORTED: single_threaded_runtime
// REQUIRES: rdar80824152
import Dispatch
// For sleep
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#endif
enum TL {
@TaskLocal
static var number: Int = 0
@TaskLocal
static var other: Int = 0
}
@discardableResult
func printTaskLocal<V>(
_ key: TaskLocal<V>,
_ expected: V? = nil,
file: String = #file, line: UInt = #line
) -> V? {
let value = key.get()
print("\(key) (\(value)) at \(file):\(line)")
if let expected = expected {
assert("\(expected)" == "\(value)",
"Expected [\(expected)] but found: \(value), at \(file):\(line)")
}
return expected
}
// ==== ------------------------------------------------------------------------
func copyTo_sync_noWait() {
print(#function)
let sem = DispatchSemaphore(value: 0)
TL.$number.withValue(1111) {
TL.$number.withValue(2222) {
TL.$other.withValue(9999) {
Task {
printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2222)
printTaskLocal(TL.$other) // CHECK: TaskLocal<Int>(defaultValue: 0) (9999)
TL.$number.withValue(3333) {
printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (3333)
printTaskLocal(TL.$other) // CHECK: TaskLocal<Int>(defaultValue: 0) (9999)
sem.signal()
}
}
}
}
}
sem.wait()
}
func copyTo_sync_noValues() {
print(#function)
let sem = DispatchSemaphore(value: 0)
Task {
printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0)
sem.signal()
}
sem.wait()
}
/// Similar to tests in `async_task_locals_copy_to_async_ but without any task involved at the top level.
@main struct Main {
static func main() {
copyTo_sync_noWait()
copyTo_sync_noValues()
}
}
| apache-2.0 | d5b8099363d5e95206513dd0c14b3e8c | 24.443182 | 130 | 0.622153 | 3.794915 | false | false | false | false |
yoxisem544/NetworkRequestKit | NetworkRequestExample/NetworkRequestExample/CodableExample.swift | 1 | 1895 | //
// CodableExample.swift
// NetworkRequestExample
//
// Created by David on 2017/10/17.
//
import Foundation
import NetworkRequestKit
import Alamofire
import PromiseKit
struct Employee {
var name: String
var id: String
var favoriteToy: Toy
enum JSONKeys: String, CodingKey {
case json
}
enum CodingKeys: String, CodingKey {
case id = "employee_id"
case name
case gift
}
}
extension Employee : Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(name, forKey: .name)
try container.encode(favoriteToy, forKey: .gift)
}
}
extension Employee : Decodable {
init(from decoder: Decoder) throws {
let jsonContainer = try decoder.container(keyedBy: JSONKeys.self)
let values = try jsonContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .json)
// let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decode(String.self, forKey: .id)
name = try values.decode(String.self, forKey: .name)
favoriteToy = try values.decode(Toy.self, forKey: Employee.CodingKeys.gift)
}
}
struct Toy: Codable {
var name: String
}
class FetchEmployee : NetworkRequest {
typealias ResponseType = Employee
// I use httpbin here, check httpbin for futher information
// For normal usage, this is the endpoint that your request is going.
public var endpoint: String { return "/post" }
public var method: HTTPMethod { return .post }
// parameter here is passed to httpbin, then will be return by httpbin.
public var parameters: [String : Any]? {
return ["employee_id": "1", "name": "johnny appleseed", "gift": ["name": "Lego"]]
}
public func perform() -> Promise<ResponseType> {
return networkClient.performRequest(self).then(responseHandler)
}
}
| mit | 70986418abac64c125bc8045a3c63df2 | 26.463768 | 91 | 0.704485 | 3.939709 | false | false | false | false |
lyft/SwiftLint | Source/SwiftLintFramework/Rules/UnneededParenthesesInClosureArgumentRule.swift | 1 | 5041 | import Foundation
import SourceKittenFramework
public struct UnneededParenthesesInClosureArgumentRule: ConfigurationProviderRule, CorrectableRule, OptInRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "unneeded_parentheses_in_closure_argument",
name: "Unneeded Parentheses in Closure Argument",
description: "Parentheses are not needed when declaring closure arguments.",
kind: .style,
nonTriggeringExamples: [
"let foo = { (bar: Int) in }\n",
"let foo = { bar, _ in }\n",
"let foo = { bar in }\n",
"let foo = { bar -> Bool in return true }\n"
],
triggeringExamples: [
"call(arg: { ↓(bar) in })\n",
"call(arg: { ↓(bar, _) in })\n",
"let foo = { ↓(bar) -> Bool in return true }\n",
"foo.map { ($0, $0) }.forEach { ↓(x, y) in }",
"foo.bar { [weak self] ↓(x, y) in }"
],
corrections: [
"call(arg: { ↓(bar) in })\n": "call(arg: { bar in })\n",
"call(arg: { ↓(bar, _) in })\n": "call(arg: { bar, _ in })\n",
"let foo = { ↓(bar) -> Bool in return true }\n": "let foo = { bar -> Bool in return true }\n",
"method { ↓(foo, bar) in }\n": "method { foo, bar in }\n",
"foo.map { ($0, $0) }.forEach { ↓(x, y) in }": "foo.map { ($0, $0) }.forEach { x, y in }",
"foo.bar { [weak self] ↓(x, y) in }": "foo.bar { [weak self] x, y in }"
]
)
public func validate(file: File) -> [StyleViolation] {
return violationRanges(file: file).map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
private func violationRanges(file: File) -> [NSRange] {
let capturesPattern = "(?:\\[[^\\]]+\\])?"
let pattern = "\\{\\s*\(capturesPattern)\\s*(\\([^:}]+\\))\\s*(in|->)"
let contents = file.contents.bridge()
let range = NSRange(location: 0, length: contents.length)
return regex(pattern).matches(in: file.contents, options: [], range: range).compactMap { match -> NSRange? in
let parametersRange = match.range(at: 1)
let inRange = match.range(at: 2)
guard let parametersByteRange = contents.NSRangeToByteRange(start: parametersRange.location,
length: parametersRange.length),
let inByteRange = contents.NSRangeToByteRange(start: inRange.location,
length: inRange.length) else {
return nil
}
let parametersTokens = file.syntaxMap.tokens(inByteRange: parametersByteRange)
let parametersAreValid = parametersTokens.reduce(true) { isValid, token in
guard isValid else {
return false
}
let kind = SyntaxKind(rawValue: token.type)
if kind == .identifier {
return true
}
return kind == .keyword &&
file.contents.bridge().substringWithByteRange(start: token.offset, length: token.length) == "_"
}
let inKinds = Set(file.syntaxMap.kinds(inByteRange: inByteRange))
guard parametersAreValid,
inKinds.isEmpty || inKinds == [.keyword] else {
return nil
}
return parametersRange
}
}
public func correct(file: File) -> [Correction] {
let violatingRanges = file.ruleEnabled(violatingRanges: violationRanges(file: file), for: self)
var correctedContents = file.contents
var adjustedLocations = [Int]()
for violatingRange in violatingRanges.reversed() {
let correctingRange = NSRange(location: violatingRange.location + 1,
length: violatingRange.length - 2)
if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange),
let updatedRange = correctedContents.nsrangeToIndexRange(correctingRange) {
let updatedArguments = correctedContents[updatedRange]
correctedContents = correctedContents.replacingCharacters(in: indexRange,
with: String(updatedArguments))
adjustedLocations.insert(violatingRange.location, at: 0)
}
}
file.write(correctedContents)
return adjustedLocations.map {
Correction(ruleDescription: type(of: self).description,
location: Location(file: file, characterOffset: $0))
}
}
}
| mit | 84b17b8314fb92a4da7634318de1171e | 44.627273 | 117 | 0.538553 | 4.651529 | false | false | false | false |
ainopara/Stage1st-Reader | Stage1st/Scene/User/UserViewController.swift | 1 | 6157 | //
// UserViewController.swift
// Stage1st
//
// Created by Zheng Li on 3/3/16.
// Copyright © 2016 Renaissance. All rights reserved.
//
import Combine
import SnapKit
import Kingfisher
final class UserViewController: UIViewController {
private let viewModel: UserViewModel
private let scrollView = UIScrollView(frame: .zero)
private let containerView = UIView(frame: .zero)
private let avatarView = UIImageView(image: nil) // TODO: Add placeholder image.
private let usernameLabel = UILabel(frame: .zero)
private let blockButton = UIButton(type: .system)
private let customStatusLabel = UILabel(frame: .zero)
private let infoLabel = UILabel(frame: .zero)
private var bag = Set<AnyCancellable>()
// MARK: - Life Cycle
init(viewModel: UserViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
avatarView.contentMode = .scaleAspectFill
avatarView.layer.borderWidth = 1.0
avatarView.layer.cornerRadius = 4.0
avatarView.clipsToBounds = true
customStatusLabel.numberOfLines = 0
infoLabel.numberOfLines = 0
bindViewModel()
NotificationCenter.default.publisher(for: .APPaletteDidChange)
.sink { [weak self] notification in
guard let strongSelf = self else { return }
strongSelf.didReceivePaletteChangeNotification(notification)
}
.store(in: &bag)
// viewModel.updateCurrentUserProfile { [weak self] result in
// guard let strongSelf = self else { return }
// switch result {
// case let .success(user):
// break
// case let .failure(error):
// S1LogDebug("Failed to update user profile. error: \(error)")
// strongSelf.s1_presentAlertView("Error", message: "\(error)")
// }
// }
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bindViewModel() {
viewModel.user
.sink { [weak self] (user) in
guard let strongSelf = self else { return }
if let avatarURL = user.avatarURL {
strongSelf.avatarView.kf.setImage(with: avatarURL)
}
}
.store(in: &bag)
viewModel.username
.sink { [weak self] in self?.usernameLabel.text = $0 }
.store(in: &bag)
viewModel.isBlocked
.map { $0 ? "解除屏蔽" : "屏蔽" }
.sink { [weak self] in self?.blockButton.setTitle($0, for: .normal) }
.store(in: &bag)
blockButton.publisher(for: .touchUpInside)
.sink { [weak self] _ in
guard let strongSelf = self else { return }
strongSelf.viewModel.toggleBlockStatus()
}
.store(in: &bag)
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
scrollView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
scrollView.addSubview(containerView)
containerView.snp.makeConstraints { make in
make.edges.equalTo(scrollView) // To decide scrollView's content size
make.width.equalTo(scrollView.snp.width) // To decide containerView's width
}
containerView.addSubview(avatarView)
avatarView.snp.makeConstraints { make in
make.leading.equalTo(containerView.snp.leading).offset(10.0)
make.top.equalTo(containerView.snp.top).offset(10.0)
make.width.height.equalTo(80.0)
}
containerView.addSubview(usernameLabel)
usernameLabel.snp.makeConstraints { make in
make.top.equalTo(avatarView.snp.top)
make.leading.equalTo(avatarView.snp.trailing).offset(10.0)
}
blockButton.setContentHuggingPriority(UILayoutPriority(UILayoutPriority.defaultLow.rawValue + 1.0), for: .horizontal)
containerView.addSubview(blockButton)
blockButton.snp.makeConstraints { make in
make.leading.equalTo(usernameLabel.snp.trailing).offset(10.0)
make.trailing.equalTo(containerView.snp.trailing).offset(-10.0)
make.top.equalTo(usernameLabel.snp.top)
make.bottom.equalTo(usernameLabel.snp.bottom)
}
containerView.addSubview(customStatusLabel)
customStatusLabel.snp.makeConstraints { make in
make.top.equalTo(usernameLabel.snp.bottom).offset(10.0)
make.leading.equalTo(usernameLabel.snp.leading)
make.trailing.equalTo(blockButton.snp.trailing)
}
containerView.addSubview(infoLabel)
infoLabel.snp.makeConstraints { make in
make.top.greaterThanOrEqualTo(avatarView.snp.bottom).offset(10.0)
make.top.greaterThanOrEqualTo(customStatusLabel.snp.bottom).offset(10.0)
make.leading.equalTo(avatarView.snp.leading)
make.trailing.equalTo(blockButton.snp.trailing)
make.bottom.equalTo(containerView.snp.bottom).offset(-10.0)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
didReceivePaletteChangeNotification(nil)
}
}
// MARK: - Style
extension UserViewController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return AppEnvironment.current.colorManager.isDarkTheme() ? .lightContent : .default
}
override func didReceivePaletteChangeNotification(_: Notification?) {
let colorManager = AppEnvironment.current.colorManager
view.backgroundColor = colorManager.colorForKey("content.background")
usernameLabel.textColor = colorManager.colorForKey("default.text.tint")
customStatusLabel.textColor = colorManager.colorForKey("default.text.tint")
infoLabel.textColor = colorManager.colorForKey("default.text.tint")
avatarView.layer.borderColor = colorManager.colorForKey("user.avatar.border").cgColor
setNeedsStatusBarAppearanceUpdate()
}
}
| bsd-3-clause | 65e9bc4daeb95a3cff9627200563815c | 35.571429 | 125 | 0.640299 | 4.682927 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/TalkPageFetcher.swift | 2 | 7198 |
class NetworkTalkPage {
let url: URL
let topics: [NetworkTopic]
var revisionId: Int?
let displayTitle: String
init(url: URL, topics: [NetworkTopic], revisionId: Int?, displayTitle: String) {
self.url = url
self.topics = topics
self.revisionId = revisionId
self.displayTitle = displayTitle
}
}
class NetworkBase: Codable {
let topics: [NetworkTopic]
}
class NetworkTopic: NSObject, Codable {
let html: String
let replies: [NetworkReply]
let sectionID: Int
let shas: NetworkTopicShas
var sort: Int?
enum CodingKeys: String, CodingKey {
case html
case shas
case replies
case sectionID = "id"
}
}
class NetworkTopicShas: Codable {
let html: String
let indicator: String
}
class NetworkReply: NSObject, Codable {
let html: String
let depth: Int16
let sha: String
var sort: Int!
enum CodingKeys: String, CodingKey {
case html
case depth
case sha
}
}
import Foundation
import WMF
enum TalkPageType: Int {
case user
case article
func canonicalNamespacePrefix(for siteURL: URL) -> String? {
let namespace: PageNamespace
switch self {
case .article:
namespace = PageNamespace.talk
case .user:
namespace = PageNamespace.userTalk
}
return namespace.canonicalName + ":"
}
func titleWithCanonicalNamespacePrefix(title: String, siteURL: URL) -> String {
return (canonicalNamespacePrefix(for: siteURL) ?? "") + title
}
func titleWithoutNamespacePrefix(title: String) -> String {
if let firstColon = title.range(of: ":") {
var returnTitle = title
returnTitle.removeSubrange(title.startIndex..<firstColon.upperBound)
return returnTitle
} else {
return title
}
}
func urlTitle(for title: String) -> String? {
assert(title.contains(":"), "Title must already be prefixed with namespace.")
return title.wmf_denormalizedPageTitle()
}
}
enum TalkPageFetcherError: Error {
case talkPageDoesNotExist
}
class TalkPageFetcher: Fetcher {
private let sectionUploader = WikiTextSectionUploader()
func addTopic(to title: String, siteURL: URL, subject: String, body: String, completion: @escaping (Result<[AnyHashable : Any], Error>) -> Void) {
guard let url = postURL(for: title, siteURL: siteURL) else {
completion(.failure(RequestError.invalidParameters))
return
}
sectionUploader.addSection(withSummary: subject, text: body, forArticleURL: url) { (result, error) in
if let error = error {
completion(.failure(error))
return
}
guard let result = result else {
completion(.failure(RequestError.unexpectedResponse))
return
}
completion(.success(result))
}
}
func addReply(to topic: TalkPageTopic, title: String, siteURL: URL, body: String, completion: @escaping (Result<[AnyHashable : Any], Error>) -> Void) {
guard let url = postURL(for: title, siteURL: siteURL) else {
completion(.failure(RequestError.invalidParameters))
return
}
//todo: should sectionID in CoreData be string?
sectionUploader.append(toSection: String(topic.sectionID), text: body, forArticleURL: url) { (result, error) in
if let error = error {
completion(.failure(error))
return
}
guard let result = result else {
completion(.failure(RequestError.unexpectedResponse))
return
}
completion(.success(result))
}
}
func fetchTalkPage(urlTitle: String, displayTitle: String, siteURL: URL, revisionID: Int?, completion: @escaping (Result<NetworkTalkPage, Error>) -> Void) {
guard let taskURLWithRevID = getURL(for: urlTitle, siteURL: siteURL, revisionID: revisionID),
let taskURLWithoutRevID = getURL(for: urlTitle, siteURL: siteURL, revisionID: nil) else {
completion(.failure(RequestError.invalidParameters))
return
}
//todo: track tasks/cancel
session.jsonDecodableTask(with: taskURLWithRevID) { (networkBase: NetworkBase?, response: URLResponse?, error: Error?) in
if let statusCode = (response as? HTTPURLResponse)?.statusCode,
statusCode == 404 {
completion(.failure(TalkPageFetcherError.talkPageDoesNotExist))
return
}
if let error = error {
completion(.failure(error))
return
}
guard let networkBase = networkBase else {
completion(.failure(RequestError.unexpectedResponse))
return
}
//update sort
//todo performance: should we go back to NSOrderedSets or move sort up into endpoint?
for (topicIndex, topic) in networkBase.topics.enumerated() {
topic.sort = topicIndex
for (replyIndex, reply) in topic.replies.enumerated() {
reply.sort = replyIndex
}
}
let talkPage = NetworkTalkPage(url: taskURLWithoutRevID, topics: networkBase.topics, revisionId: revisionID, displayTitle: displayTitle)
completion(.success(talkPage))
}
}
func getURL(for urlTitle: String, siteURL: URL) -> URL? {
return getURL(for: urlTitle, siteURL: siteURL, revisionID: nil)
}
}
//MARK: Private
private extension TalkPageFetcher {
func getURL(for urlTitle: String, siteURL: URL, revisionID: Int?) -> URL? {
assert(urlTitle.contains(":"), "Title must already be prefixed with namespace.")
guard let host = siteURL.host,
let percentEncodedUrlTitle = urlTitle.addingPercentEncoding(withAllowedCharacters: .wmf_articleTitlePathComponentAllowed) else {
return nil
}
var pathComponents = ["page", "talk", percentEncodedUrlTitle]
if let revisionID = revisionID {
pathComponents.append(String(revisionID))
}
guard let taskURL = configuration.wikipediaMobileAppsServicesAPIURLComponentsForHost(host, appending: pathComponents).url else {
return nil
}
return taskURL
}
func postURL(for urlTitle: String, siteURL: URL) -> URL? {
assert(urlTitle.contains(":"), "Title must already be prefixed with namespace.")
guard let host = siteURL.host else {
return nil
}
let components = configuration.articleURLForHost(host, appending: [urlTitle])
return components.url
}
}
| mit | 18c1248d99fdcf4f2d61796b7b0ed843 | 30.432314 | 160 | 0.587524 | 5.072586 | false | false | false | false |
hironytic/Formulitic | Sources/Value/DoubleValue.swift | 1 | 2764 | //
// DoubleValue.swift
// Formulitic
//
// Copyright (c) 2016-2018 Hironori Ichimiya <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A calculated value which represents a double number
public struct DoubleValue: NumerableValue, Hashable {
/// A raw number.
public let number: Double
/// Initializes the object.
/// - Parameters:
/// - number: A raw number.
public init(number: Double) {
self.number = number
}
public func cast(to capability: ValueCapability, context: EvaluateContext) -> Value {
switch capability {
case .numerable:
return self
case .stringable:
return StringValue(string: "\(number)")
case .booleanable:
return BoolValue(bool: !number.isZero)
}
}
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func ==(lhs: DoubleValue, rhs: DoubleValue) -> Bool {
return lhs.number == rhs.number
}
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
public var hashValue: Int {
get {
return number.hashValue
}
}
}
extension DoubleValue: CustomDebugStringConvertible {
public var debugDescription: String {
return "DoubleValue(\(number))"
}
}
| mit | 22a40a6f004706ba96a0c5ed4aec7c85 | 34.435897 | 89 | 0.667873 | 4.538588 | false | false | false | false |
rpcarson/mtg-sdk-swift | MTGSDKSwift/SearchParameter.swift | 1 | 1214 | //
// SearchParameter.swift
// MTGSDKSwift
//
// Created by Reed Carson on 2/27/17.
// Copyright © 2017 Reed Carson. All rights reserved.
//
import Foundation
public class SearchParameter {
public var name: String = ""
public var value: String = ""
}
public class CardSearchParameter: SearchParameter {
public enum CardQueryParameterType: String {
case name
case cmc
case colors
case type
case supertypes
case subtypes
case rarity
case text
case set
case artist
case power
case toughness
case multiverseid
case gameFormat
}
public init(parameterType: CardQueryParameterType, value: String) {
super.init()
self.name = parameterType.rawValue
self.value = value
}
}
public class SetSearchParameter: SearchParameter {
public enum SetQueryParameterType: String {
case name
case block
}
public init(parameterType: SetQueryParameterType, value: String) {
super.init()
self.name = parameterType.rawValue
self.value = value
}
}
//
| mit | 76fdd90c28a01d5b60d5e1c64264ea98 | 17.378788 | 71 | 0.59357 | 4.719844 | false | false | false | false |
wesj/firefox-ios-1 | Sync/Synchronizer.swift | 1 | 1447 | /* 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
// TODO: return values?
/**
* A Synchronizer is (unavoidably) entirely in charge of what it does within a sync.
* For example, it might make incremental progress in building a local cache of remote records, never actually performing an upload or modifying local storage.
* It might only upload data. Etc.
*
* Eventually I envision an intent-like approach, or additional methods, to specify preferences and constraints
* (e.g., "do what you can in a few seconds", or "do a full sync, no matter how long it takes"), but that'll come in time.
*/
public protocol Synchronizer {
init(info: InfoCollections, prefs: Prefs)
func synchronize()
}
public class ClientsSynchronizer: Synchronizer {
private let info: InfoCollections
private let prefs: Prefs
private let prefix = "clients"
private let collection = "clients"
required public init(info: InfoCollections, prefs: Prefs) {
self.info = info
self.prefs = prefs
}
public func synchronize() {
if let last = prefs.longForKey(self.prefix + "last") {
if last == info.modified(self.collection) {
// Nothing to do.
return;
}
}
}
} | mpl-2.0 | ef2d77900d22b2b1986bf087ccecb34d | 33.47619 | 159 | 0.67519 | 4.281065 | false | false | false | false |
ngoctuanqt/IOS | FireBaseAuthTest/FireBaseAuthTest/RegisterViewController.swift | 1 | 2354 | //
// RegisterViewController.swift
// FireBaseAuthTest
//
// Created by nguyen ngoc tuan on 10/31/16.
// Copyright © 2016 samsung. All rights reserved.
//
import UIKit
import FirebaseAuth
class RegisterViewController: UIViewController {
let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
override func viewDidLoad() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
view.addGestureRecognizer(tapGesture)
}
func hideKeyboard() {
view.endEditing(true)
}
@IBOutlet weak var txtEmail: UITextField!
@IBOutlet weak var txtPassword: UITextField!
@IBOutlet weak var txtPassword2nd: UITextField!
@IBOutlet weak var activitySpin: UIActivityIndicatorView!
@IBAction func doBack(_ sender: Any) {
let loginViewController = mainStoryBoard.instantiateViewController(withIdentifier: "LoginView")
self.present(loginViewController, animated: true, completion: nil)
}
@IBAction func doSave(_ sender: Any) {
if let email = txtEmail.text,
let password = txtPassword.text,
let password2 = txtPassword2nd.text {
activitySpin.startAnimating()
if password != password2 {
showAlertView(message: "Password not match", title: "Error")
activitySpin.stopAnimating()
return
}
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, error) in
if let error = error {
self.showAlertView(message: error.localizedDescription, title: "Error")
self.activitySpin.stopAnimating()
} else {
let done: UIAlertAction = UIAlertAction(title: "OK", style: .default, handler: { (_) in
let loginViewController = self.mainStoryBoard.instantiateViewController(withIdentifier: "LoginView")
self.present(loginViewController, animated: true, completion: nil)
})
let actions: [UIAlertAction] = [done]
self.showAlertView(message: "Sign up success, back to login!", title: "Success", actions: actions)
}
})
}
}
}
| mit | 6c5ac38ae37bc4a8477dce69acf2d75a | 38.216667 | 124 | 0.61241 | 5.240535 | false | false | false | false |
KrishMunot/swift | test/1_stdlib/Strideable.swift | 3 | 4545 | //===--- Strideable.swift - Tests for strided iteration -------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
//
import StdlibUnittest
// Check that the generic parameter is called 'Element'.
protocol TestProtocol1 {}
extension StrideToIterator where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideTo where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideThroughIterator where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideThrough where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
var StrideTestSuite = TestSuite("Strideable")
struct R : RandomAccessIndex {
typealias Distance = Int
var x: Int
init(_ x: Int) {
self.x = x
}
func successor() -> R {
return R(x + 1)
}
func predecessor() -> R {
return R(x - 1)
}
func distance(to rhs: R) -> Int {
return rhs.x - x
}
func advanced(by n: Int) -> R {
return R(x + n)
}
func advanced(by n: Int, limit: R) -> R {
let d = distance(to: limit)
if d == 0 || (d > 0 ? d <= n : d >= n) {
return limit
}
return self.advanced(by: n)
}
}
StrideTestSuite.test("Double") {
// Doubles are not yet ready for testing, since they still conform
// to RandomAccessIndex
}
StrideTestSuite.test("HalfOpen") {
func check(from start: Int, to end: Int, by stepSize: Int, sum: Int) {
// Work on Ints
expectEqual(
sum,
stride(from: start, to: end, by: stepSize).reduce(0, combine: +))
// Work on an arbitrary RandomAccessIndex
expectEqual(
sum,
stride(from: R(start), to: R(end), by: stepSize).reduce(0) { $0 + $1.x })
}
check(from: 1, to: 15, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, to: 16, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, to: 17, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, to: -13, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, to: -14, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, to: -15, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 4, to: 16, by: -3, sum: 0)
check(from: 1, to: -16, by: 3, sum: 0)
}
StrideTestSuite.test("Closed") {
func check(from start: Int, through end: Int, by stepSize: Int, sum: Int) {
// Work on Ints
expectEqual(
sum,
stride(from: start, through: end, by: stepSize).reduce(0, combine: +))
// Work on an arbitrary RandomAccessIndex
expectEqual(
sum,
stride(from: R(start), through: R(end), by: stepSize).reduce(0) { $0 + $1.x })
}
check(from: 1, through: 15, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, through: 16, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, through: 17, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, through: -13, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, through: -14, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 1, through: -15, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 4, through: 16, by: -3, sum: 0)
check(from: 1, through: -16, by: 3, sum: 0)
}
StrideTestSuite.test("OperatorOverloads") {
var r1 = R(50)
var r2 = R(70)
var stride: Int = 5
do {
var result = r1 + stride
expectType(R.self, &result)
expectEqual(55, result.x)
}
do {
var result = stride + r1
expectType(R.self, &result)
expectEqual(55, result.x)
}
do {
var result = r1 - stride
expectType(R.self, &result)
expectEqual(45, result.x)
}
do {
var result = r1 - r2
expectType(Int.self, &result)
expectEqual(-20, result)
}
do {
var result = r1
result += stride
expectType(R.self, &result)
expectEqual(55, result.x)
}
do {
var result = r1
result -= stride
expectType(R.self, &result)
expectEqual(45, result.x)
}
}
runAllTests()
| apache-2.0 | 59a0a003f11474e6598fd0a67d2c79c0 | 25.424419 | 84 | 0.579098 | 3.12586 | false | true | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Picker/Model/LocalAsset.swift | 1 | 4837 | //
// LocalAsset.swift
// HXPHPicker
//
// Created by Slience on 2021/5/24.
//
import UIKit
public struct LocalImageAsset {
public var image: UIImage?
public var imageData: Data?
public var imageURL: URL?
public init(image: UIImage) {
self.image = image
}
public init(imageData: Data) {
self.imageData = imageData
self.image = UIImage(data: imageData)
}
public init(imageURL: URL) {
self.imageURL = imageURL
}
var thumbnail: UIImage?
}
public struct LocalVideoAsset {
/// 视频本地地址
public let videoURL: URL
/// 视频封面
public var image: UIImage?
/// 视频时长
public var duration: TimeInterval
/// 视频尺寸
public var videoSize: CGSize
public init(videoURL: URL,
coverImage: UIImage? = nil,
duration: TimeInterval = 0,
videoSize: CGSize = .zero) {
self.videoURL = videoURL
self.image = coverImage
self.duration = duration
self.videoSize = videoSize
}
}
public struct LocalLivePhotoAsset {
/// 封面图片本地地址
public let imageURL: URL
/// 视频内容地址(支持本地、网络)
public let videoURL: URL
public init(imageURL: URL, videoURL: URL) {
self.imageURL = imageURL
self.videoURL = videoURL
}
}
extension LocalImageAsset: Codable {
enum CodingKeys: CodingKey {
case image
case imageData
case imageURL
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let data = try container.decodeIfPresent(Data.self, forKey: .image) {
image = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? UIImage
}else {
image = nil
}
imageURL = try container.decodeIfPresent(URL.self, forKey: .imageURL)
imageData = try container.decodeIfPresent(Data.self, forKey: .imageData)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if let image = image {
if #available(iOS 11.0, *) {
let data = try NSKeyedArchiver.archivedData(withRootObject: image, requiringSecureCoding: false)
try container.encode(data, forKey: .image)
} else {
let data = NSKeyedArchiver.archivedData(withRootObject: image)
try container.encode(data, forKey: .image)
}
}
try container.encode(imageURL, forKey: .imageURL)
try container.encode(imageData, forKey: .imageData)
}
}
extension LocalVideoAsset: Codable {
enum CodingKeys: CodingKey {
case videoURL
case image
case duration
case videoSize
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
videoURL = try container.decode(URL.self, forKey: .videoURL)
if let data = try container.decodeIfPresent(Data.self, forKey: .image) {
image = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? UIImage
}else {
image = nil
}
duration = try container.decode(TimeInterval.self, forKey: .duration)
videoSize = try container.decode(CGSize.self, forKey: .videoSize)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(videoURL, forKey: .videoURL)
if let image = image {
if #available(iOS 11.0, *) {
let data = try NSKeyedArchiver.archivedData(withRootObject: image, requiringSecureCoding: false)
try container.encode(data, forKey: .image)
} else {
let data = NSKeyedArchiver.archivedData(withRootObject: image)
try container.encode(data, forKey: .image)
}
}
try container.encode(duration, forKey: .duration)
try container.encode(videoSize, forKey: .videoSize)
}
}
extension LocalLivePhotoAsset: Codable {
enum CodingKeys: CodingKey {
case imageURL
case videoURL
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
imageURL = try container.decode(URL.self, forKey: .imageURL)
videoURL = try container.decode(URL.self, forKey: .videoURL)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(imageURL, forKey: .imageURL)
try container.encode(videoURL, forKey: .videoURL)
}
}
| mit | 727fafc04db8b153ff98e6ccb82c721d | 31.128378 | 112 | 0.624185 | 4.661765 | false | false | false | false |
zerovagner/iOS-Studies | RetroCalculator/RetroCalculator/ViewController.swift | 1 | 1450 | //
// ViewController.swift
// RetroCalculator
//
// Created by Vagner Oliveira on 5/5/17.
// Copyright © 2017 Vagner Oliveira. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var outputLabel: UILabel!
private var calculator = Calculator()
override func viewDidLoad() {
super.viewDidLoad()
CalculatorButton.setup()
outputLabel.text = "0"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func numberPressed(_ sender: CalculatorButton) {
sender.playSound()
calculator.addNumber("\(sender.tag)")
outputLabel.text = calculator.runningNumber
}
/**
* In this case, each operator button has its own corresponding tag
* "+" -> 10
* "-" -> 11
* "*" -> 12
* "/" -> 13
*/
@IBAction func operatorPressed(_ sender: CalculatorButton) {
var operation = Calculator.Operation.Empty
sender.playSound()
switch sender.tag {
case 10:
operation = Calculator.Operation.Add
case 11:
operation = Calculator.Operation.Subtract
case 12:
operation = Calculator.Operation.Multiply
case 13:
operation = Calculator.Operation.Divide
default:
operation = calculator.currentOperation
}
calculator.performOperation(operation)
outputLabel.text = calculator.result
}
@IBAction func clearPressed(_ sender: Any) {
calculator.clear()
outputLabel.text = "0"
}
}
| gpl-3.0 | 0508e281edf1d61310d076350d461632 | 21.292308 | 67 | 0.711525 | 3.715385 | false | false | false | false |
iotize/iotize.github.io | Sources/Publisher/CustomTheme.swift | 1 | 7198 | import Plot
import Publish
public extension Theme {
static var custom: Self {
Theme(
htmlFactory: CustomHTMLFactory(),
resourcePaths: ["assets/css/styles.css"]
)
}
}
private struct CustomHTMLFactory<Site: Website>: HTMLFactory {
func makeIndexHTML(for index: Index,
context: PublishingContext<Site>) throws -> HTML {
HTML(
.lang(context.site.language),
.head(for: index, on: context.site),
.body(
.header(for: context, selectedSection: nil),
.wrapper(
.h1(.text(index.title)),
.p(
.class("description"),
.text(context.site.description)
),
.h2("Latest content"),
.itemList(
for: context.allItems(
sortedBy: \.date,
order: .descending
),
on: context.site
)
),
.footer(for: context.site)
)
)
}
func makeSectionHTML(for section: Section<Site>,
context: PublishingContext<Site>) throws -> HTML {
HTML(
.lang(context.site.language),
.head(for: section, on: context.site),
.body(
.header(for: context, selectedSection: section.id),
.wrapper(
.h1(.text(section.title)),
.itemList(for: section.items, on: context.site)
),
.footer(for: context.site)
)
)
}
func makeItemHTML(for item: Item<Site>,
context: PublishingContext<Site>) throws -> HTML {
HTML(
.lang(context.site.language),
.head(for: item, on: context.site),
.body(
.class("item-page"),
.header(for: context, selectedSection: item.sectionID),
.wrapper(
.article(
.div(
.class("content"),
.contentBody(item.body)
),
.span("Tagged with: "),
.tagList(for: item, on: context.site)
)
),
.footer(for: context.site)
)
)
}
func makePageHTML(for page: Page,
context: PublishingContext<Site>) throws -> HTML {
HTML(
.lang(context.site.language),
.head(for: page, on: context.site),
.body(
.header(for: context, selectedSection: nil),
.wrapper(.contentBody(page.body)),
.footer(for: context.site)
)
)
}
func makeTagListHTML(for page: TagListPage,
context: PublishingContext<Site>) throws -> HTML? {
HTML(
.lang(context.site.language),
.head(for: page, on: context.site),
.body(
.header(for: context, selectedSection: nil),
.wrapper(
.h1("Browse all tags"),
.ul(
.class("all-tags"),
.forEach(page.tags.sorted()) { tag in
.li(
.class("tag"),
.a(
.href(context.site.path(for: tag)),
.text(tag.string)
)
)
}
)
),
.footer(for: context.site)
)
)
}
func makeTagDetailsHTML(for page: TagDetailsPage,
context: PublishingContext<Site>) throws -> HTML? {
HTML(
.lang(context.site.language),
.head(for: page, on: context.site),
.body(
.header(for: context, selectedSection: nil),
.wrapper(
.h1(
"Tagged with ",
.span(.class("tag"), .text(page.tag.string))
),
.a(
.class("browse-all"),
.text("Browse all tags"),
.href(context.site.tagListPath)
),
.itemList(
for: context.items(
taggedWith: page.tag,
sortedBy: \.date,
order: .descending
),
on: context.site
)
),
.footer(for: context.site)
)
)
}
}
private extension Node where Context == HTML.BodyContext {
static func wrapper(_ nodes: Node...) -> Node {
.div(.class("wrapper"), .group(nodes))
}
static func header<T: Website>(
for context: PublishingContext<T>,
selectedSection: T.SectionID?
) -> Node {
let sectionIDs = T.SectionID.allCases
return .header(
.wrapper(
.a(.class("site-name"), .href("/"), .text(context.site.name)),
.if(sectionIDs.count > 1,
.nav(
.ul(.forEach(sectionIDs) { section in
.li(.a(
.class(section == selectedSection ? "selected" : ""),
.href(context.sections[section].path),
.text(context.sections[section].title)
))
})
)
)
)
)
}
static func itemList<T: Website>(for items: [Item<T>], on site: T) -> Node {
return .ul(
.class("item-list"),
.forEach(items) { item in
.li(.article(
.h1(.a(
.href(item.path),
.text(item.title)
)),
.tagList(for: item, on: site),
.p(.text(item.description))
))
}
)
}
static func tagList<T: Website>(for item: Item<T>, on site: T) -> Node {
return .ul(.class("tag-list"), .forEach(item.tags) { tag in
.li(.a(
.href(site.path(for: tag)),
.text(tag.string)
))
})
}
static func footer<T: Website>(for site: T) -> Node {
return .footer(
.p(
.text("Generated using "),
.a(
.text("Publish"),
.href("https://github.com/johnsundell/publish")
)
),
.p(.a(
.text("RSS feed"),
.href("/feed.rss")
))
)
}
}
| mit | 39f2e2eec30b1d5ef6512ef6876903b8 | 31.570136 | 85 | 0.384273 | 5.040616 | false | false | false | false |
scarlettwu93/test | Example/Pods/SwiftLocation/Pod/Classes/SwiftLocation.swift | 1 | 44310 | //
// SwiftLocation.swift
// SwiftLocations
//
// Copyright (c) 2015 Daniele Margutti
// Web: http://www.danielemargutti.com
// Mail: [email protected]
// Twitter: @danielemargutti
//
// First version: July 15, 2015
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreLocation
import MapKit
enum SwiftLocationError: ErrorType {
case ServiceUnavailable
case LocationServicesUnavailable
}
/// Type of a request ID
public typealias RequestIDType = Int
//MARK: Handlers
// Location related handler
public typealias onSuccessLocate = ( (location: CLLocation?) -> Void)
public typealias onErrorLocate = ( (error: NSError?) -> Void )
// Generic timeout handler
public typealias onTimeoutReached = ( Void -> (NSTimeInterval?) )
// Region/Beacon Proximity related handlers
public typealias onRegionEvent = ( (region: AnyObject?) -> Void)
public typealias onRangingBacon = ( (beacons: [AnyObject]) -> Void)
// Geocoding related handlers
public typealias onSuccessGeocoding = ( (place: CLPlacemark?) -> Void)
public typealias onErrorGeocoding = ( (error: NSError?) -> Void)
//MARK: Service Status Enum
/**
Apple location services are subject to authorization step. This enum indicate the current status of the location manager into the device. You can query it via SwiftLocation.state property.
- Available: User has already granted this app permissions to access location services, and they are enabled and ready for use by this app.
Note: this state will be returned for both the "When In Use" and "Always" permission levels.
- Undetermined: User has not yet responded to the dialog that grants this app permission to access location services.
- Denied: User has explicitly denied this app permission to access location services. (The user can enable permissions again for this app from the system Settings app.)
- Restricted: User does not have ability to enable location services (e.g. parental controls, corporate policy, etc).
- Disabled: User has turned off location services device-wide (for all apps) from the system Settings app.
*/
public enum ServiceStatus :Int {
case Available
case Undetermined
case Denied
case Restricted
case Disabled
}
//MARK: Service Type Enum
/**
For reverse geocoding service you can choose what service use to make your request.
- Apple: Apple built-in CoreLocation services
- GoogleMaps: Google Geocoding Services (https://developers.google.com/maps/documentation/geocoding/intro)
*/
public enum Service: Int, CustomStringConvertible {
case Apple = 0
case GoogleMaps = 1
public var description: String {
get {
switch self {
case .Apple:
return "Apple"
case .GoogleMaps:
return "Google"
}
}
}
}
//MARK: Accuracy
/**
Accuracy is used to set the minimum level of precision required during location discovery
- None: Unknown level detail
- Country: Country detail. It's used only for a single shot location request and uses IP based location discovery (no auth required). Inaccurate (>5000 meters, and/or received >10 minutes ago).
- City: 5000 meters or better, and received within the last 10 minutes. Lowest accuracy.
- Neighborhood: 1000 meters or better, and received within the last 5 minutes.
- Block: 100 meters or better, and received within the last 1 minute.
- House: 15 meters or better, and received within the last 15 seconds.
- Room: 5 meters or better, and received within the last 5 seconds. Highest accuracy.
*/
public enum Accuracy:Int, CustomStringConvertible {
case None = 0
case Country = 1
case City = 2
case Neighborhood = 3
case Block = 4
case House = 5
case Room = 6
public var description: String {
get {
switch self {
case .None:
return "None"
case .Country:
return "Country"
case .City:
return "City"
case .Neighborhood:
return "Neighborhood"
case .Block:
return "Block"
case .House:
return "House"
case .Room:
return "Room"
}
}
}
/**
This is the threshold of accuracy to validate a location
- returns: value in meters
*/
func accuracyThreshold() -> Double {
switch self {
case .None:
return Double.infinity
case .Country:
return Double.infinity
case .City:
return 5000.0
case .Neighborhood:
return 1000.0
case .Block:
return 100.0
case .House:
return 15.0
case .Room:
return 5.0
}
}
/**
Time threshold to validate the accuracy of a location
- returns: in seconds
*/
func timeThreshold() -> Double {
switch self {
case .None:
return Double.infinity
case .Country:
return Double.infinity
case .City:
return 600.0
case .Neighborhood:
return 300.0
case .Block:
return 60.0
case .House:
return 15.0
case .Room:
return 5.0
}
}
}
//MARK: ===== [PUBLIC] SwiftLocation Class =====
public class SwiftLocation: NSObject, CLLocationManagerDelegate {
//MARK: Private vars
private var manager: CLLocationManager // CoreLocationManager shared instance
private var requests: [SwiftLocationRequest]! // This is the list of running requests (does not include geocode requests)
private let blocksDispatchQueue = dispatch_queue_create("SynchronizedArrayAccess", DISPATCH_QUEUE_SERIAL) // sync operation queue for CGD
//MARK: Public vars
public static let shared = SwiftLocation()
//MARK: Simulate location and location updates
/// Set this to a valid non-nil location to receive it as current location for single location search
public var fixedLocation: CLLocation?
public var fixedLocationDictionary: [String: AnyObject]?
/// Set it to a valid existing gpx file url to receive positions during continous update
//public var fixedLocationGPX: NSURL?
/// This property report the current state of the CoreLocationManager service based on user authorization
class var state: ServiceStatus {
get {
if CLLocationManager.locationServicesEnabled() == false {
return .Disabled
} else {
switch CLLocationManager.authorizationStatus() {
case .NotDetermined:
return .Undetermined
case .Denied:
return .Denied
case .Restricted:
return .Restricted
case .AuthorizedAlways, .AuthorizedWhenInUse:
return .Available
}
}
}
}
//MARK: Private Init
/**
Private init. This is called only to allocate the singleton instance
- returns: the object itself, what else?
*/
override private init() {
requests = []
manager = CLLocationManager()
super.init()
manager.delegate = self
}
//MARK: [Public] Cancel a running request
/**
Cancel a running request
- parameter identifier: identifier of the request
- returns: true if request is marked as cancelled, no if it was not found
*/
public func cancelRequest(identifier: Int) -> Bool {
if let request = request(identifier) as SwiftLocationRequest! {
request.markAsCancelled(nil)
}
return false
}
/**
Mark as cancelled any running request
*/
public func cancelAllRequests() {
for request in requests {
request.markAsCancelled(nil)
}
}
//MARK: [Public] Reverse Geocoding
/**
Submits a forward-geocoding request using the specified string and optional region information.
- parameter service: service to use
- parameter address: A string describing the location you want to look up. For example, you could specify the string “1 Infinite Loop, Cupertino, CA” to locate Apple headquarters.
- parameter region: (Optional) A geographical region to use as a hint when looking up the specified address. Region is used only when service is set to Apple
- parameter onSuccess: on success handler
- parameter onFail: on error handler
*/
public func reverseAddress(service: Service!, address: String!, region: CLRegion?, onSuccess: onSuccessGeocoding?, onFail: onErrorGeocoding? ) {
if service == Service.Apple {
reverseAppleAddress(address, region: region, onSuccess: onSuccess, onFail: onFail)
} else {
reverseGoogleAddress(address, onSuccess: onSuccess, onFail: onFail)
}
}
/**
This method submits the specified location data to the geocoding server asynchronously and returns.
- parameter service: service to use
- parameter coordinates: coordinates to reverse
- parameter onSuccess: on success handler with CLPlacemarks objects
- parameter onFail: on error handler with error description
*/
public func reverseCoordinates(service: Service!, coordinates: CLLocationCoordinate2D!, onSuccess: onSuccessGeocoding?, onFail: onErrorGeocoding? ) {
if service == Service.Apple {
reverseAppleCoordinates(coordinates, onSuccess: onSuccess, onFail: onFail)
} else {
reverseGoogleCoordinates(coordinates, onSuccess: onSuccess, onFail: onFail)
}
}
//MARK: [Public] Search Location / Subscribe Location Changes
/**
Get the current location from location manager with given accuracy
- parameter accuracy: minimum accuracy value to accept (country accuracy uses IP based location, not the CoreLocationManager, and it does not require user authorization)
- parameter timeout: search timeout. When expired, method return directly onFail
- parameter onSuccess: handler called when location is found
- parameter onFail: handler called when location manager fails due to an error
- returns: return an object to manage the request itself
*/
public func currentLocation(accuracy: Accuracy, timeout: NSTimeInterval, onSuccess: onSuccessLocate, onFail: onErrorLocate) throws -> RequestIDType {
if let fixedLocation = fixedLocation as CLLocation! {
// If a fixed location is set we want to return it
onSuccess(location: fixedLocation)
return -1 // request cannot be aborted, of course
}
if SwiftLocation.state == ServiceStatus.Disabled {
throw SwiftLocationError.LocationServicesUnavailable
}
if accuracy == Accuracy.Country {
let newRequest = SwiftLocationRequest(requestType: RequestType.SingleShotIPLocation, accuracy:accuracy, timeout: timeout, success: onSuccess, fail: onFail)
locateByIP(newRequest, refresh: false, timeout: timeout, onEnd: { (place, error) -> Void in
if error != nil {
onFail(error: error)
} else {
onSuccess(location: place?.location)
}
})
addRequest(newRequest)
return newRequest.ID
} else {
let newRequest = SwiftLocationRequest(requestType: RequestType.SingleShotLocation, accuracy:accuracy, timeout: timeout, success: onSuccess, fail: onFail)
addRequest(newRequest)
return newRequest.ID
}
}
/**
This method continously report found locations with desidered or better accuracy. You need to stop it manually by calling cancel() method into the request.
- parameter accuracy: minimum accuracy value to accept (country accuracy is not allowed)
- parameter onSuccess: handler called each time a new position is found
- parameter onFail: handler called when location manager fail (the request itself is aborted automatically)
- returns: return the id of the request. Use cancelRequest() to abort it.
*/
public func continuousLocation(accuracy: Accuracy, onSuccess: onSuccessLocate, onFail: onErrorLocate) throws -> RequestIDType {
if SwiftLocation.state == ServiceStatus.Disabled {
throw SwiftLocationError.LocationServicesUnavailable
}
let newRequest = SwiftLocationRequest(requestType: RequestType.ContinuousLocationUpdate, accuracy:accuracy, timeout: 0, success: onSuccess, fail: onFail)
addRequest(newRequest)
return newRequest.ID
}
/**
This method continously return only significant location changes. This capability provides tremendous power savings for apps that want to track a user’s approximate location and do not need highly accurate position information. You need to stop it manually by calling cancel() method into the request.
- parameter onSuccess: handler called each time a new position is found
- parameter onFail: handler called when location manager fail (the request itself is aborted automatically)
- returns: return the id of the request. Use cancelRequest() to abort it.
*/
public func significantLocation(onSuccess: onSuccessLocate, onFail: onErrorLocate) throws -> RequestIDType {
if SwiftLocation.state == ServiceStatus.Disabled {
throw SwiftLocationError.LocationServicesUnavailable
}
let newRequest = SwiftLocationRequest(requestType: RequestType.ContinuousSignificantLocation, accuracy:Accuracy.None, timeout: 0, success: onSuccess, fail: onFail)
addRequest(newRequest)
return newRequest.ID
}
//MARK: [Public] Monitor Regions
/**
Start monitoring specified region by reporting when users move in/out from it. You must call this method once for each region you want to monitor. You need to stop it manually by calling cancel() method into the request.
- parameter region: region to monitor
- parameter onEnter: handler called when user move into the region
- parameter onExit: handler called when user move out from the region
- returns: return the id of the request. Use cancelRequest() to abort it.
*/
public func monitorRegion(region: CLRegion!, onEnter: onRegionEvent?, onExit: onRegionEvent?) throws -> RequestIDType? {
// if beacons region monitoring is not available on this device we can't satisfy the request
let isAvailable = CLLocationManager.isMonitoringAvailableForClass(CLRegion.self)
if isAvailable == true {
let request = SwiftLocationRequest(region: region, onEnter: onEnter, onExit: onExit)
manager.startMonitoringForRegion(region)
self.updateLocationManagerStatus()
return request.ID
} else {
throw SwiftLocationError.ServiceUnavailable
}
}
//MARK: [Public] Monitor Beacons Proximity
/**
Starts the delivery of notifications for beacons in the specified region.
- parameter region: region to monitor
- parameter onRanging: handler called every time one or more beacon are in range, ordered by distance (closest is the first one)
- returns: return the id of the request. Use cancelRequest() to abort it.
*/
public func monitorBeaconsInRegion(region: CLBeaconRegion!, onRanging: onRangingBacon? ) throws -> RequestIDType? {
let isAvailable = CLLocationManager.isRangingAvailable() // if beacons monitoring is not available on this device we can't satisfy the request
if isAvailable == true {
let request = SwiftLocationRequest(beaconRegion: region, onRanging: onRanging)
addRequest(request)
return request.ID
} else {
throw SwiftLocationError.ServiceUnavailable
}
}
//MARK: [Private] Google / Reverse Geocoding
private func reverseGoogleCoordinates(coordinates: CLLocationCoordinate2D!, onSuccess: onSuccessGeocoding?, onFail: onErrorGeocoding? ) {
var APIURLString = "https://maps.googleapis.com/maps/api/geocode/json?latlng=\(coordinates.latitude),\(coordinates.longitude)" as NSString
APIURLString = APIURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let APIURL = NSURL(string: APIURLString as String)
let APIURLRequest = NSURLRequest(URL: APIURL!)
NSURLConnection.sendAsynchronousRequest(APIURLRequest, queue: NSOperationQueue.mainQueue()) { (response, data, error) in
if error != nil {
onFail?(error: error)
} else {
if data != nil {
let jsonResult: NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
let (error,noResults) = self.validateGoogleJSONResponse(jsonResult)
if noResults == true { // request is ok but not results are returned
onSuccess?(place: nil)
} else if (error != nil) { // something went wrong with request
onFail?(error: error)
} else { // we have some good results to show
let address = SwiftLocationParser()
address.parseGoogleLocationData(jsonResult)
let placemark:CLPlacemark = address.getPlacemark()
onSuccess?(place: placemark)
}
}
}
}
}
private func reverseGoogleAddress(address: String!, onSuccess: onSuccessGeocoding?, onFail: onErrorGeocoding?) {
var APIURLString = "https://maps.googleapis.com/maps/api/geocode/json?address=\(address)" as NSString
APIURLString = APIURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let APIURL = NSURL(string: APIURLString as String)
let APIURLRequest = NSURLRequest(URL: APIURL!)
NSURLConnection.sendAsynchronousRequest(APIURLRequest, queue: NSOperationQueue.mainQueue()) { (response, data, error) in
if error != nil {
onFail?(error: error)
} else {
if data != nil {
let jsonResult: NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
let (error,noResults) = self.validateGoogleJSONResponse(jsonResult)
if noResults == true { // request is ok but not results are returned
onSuccess?(place: nil)
} else if (error != nil) { // something went wrong with request
onFail?(error: error)
} else { // we have some good results to show
let address = SwiftLocationParser()
address.parseGoogleLocationData(jsonResult)
let placemark:CLPlacemark = address.getPlacemark()
onSuccess?(place: placemark)
}
}
}
}
}
private func validateGoogleJSONResponse(jsonResult: NSDictionary!) -> (error: NSError?, noResults: Bool!) {
var status = jsonResult.valueForKey("status") as! NSString
status = status.lowercaseString
if status.isEqualToString("ok") == true { // everything is fine, the sun is shining and we have results!
return (nil,false)
} else if status.isEqualToString("zero_results") == true { // No results error
return (nil,true)
} else if status.isEqualToString("over_query_limit") == true { // Quota limit was excedeed
let message = "Query quota limit was exceeded"
return (NSError(domain: NSCocoaErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey : message]),false)
} else if status.isEqualToString("request_denied") == true { // Request was denied
let message = "Request denied"
return (NSError(domain: NSCocoaErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey : message]),false)
} else if status.isEqualToString("invalid_request") == true { // Invalid parameters
let message = "Invalid input sent"
return (NSError(domain: NSCocoaErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey : message]),false)
}
return (nil,false) // okay!
}
//MARK: [Private] Apple / Reverse Geocoding
private func reverseAppleCoordinates(coordinates: CLLocationCoordinate2D!, onSuccess: onSuccessGeocoding?, onFail: onErrorGeocoding? ) {
let geocoder = CLGeocoder()
let location = CLLocation(latitude: coordinates.latitude, longitude: coordinates.longitude)
geocoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in
if error != nil {
onFail?(error: error)
} else {
if let placemark = placemarks?[0] {
let address = SwiftLocationParser()
address.parseAppleLocationData(placemark)
onSuccess?(place: address.getPlacemark())
} else {
onSuccess?(place: nil)
}
}
})
}
private func reverseAppleAddress(address: String!, region: CLRegion?, onSuccess: onSuccessGeocoding?, onFail: onErrorGeocoding? ) {
let geocoder = CLGeocoder()
if region != nil {
geocoder.geocodeAddressString(address, inRegion: region, completionHandler: { (placemarks, error) in
if error != nil {
onFail?(error: error)
} else {
if let placemark = placemarks?[0] {
let address = SwiftLocationParser()
address.parseAppleLocationData(placemark)
onSuccess?(place: address.getPlacemark())
} else {
onSuccess?(place: nil)
}
}
})
} else {
geocoder.geocodeAddressString(address, completionHandler: { (placemarks, error) in
if error != nil {
onFail?(error: error)
} else {
if let placemark = placemarks?[0] {
let address = SwiftLocationParser()
address.parseAppleLocationData(placemark)
onSuccess?(place: address.getPlacemark())
} else {
onSuccess?(place: nil)
}
}
})
}
}
//MARK: [Private] Helper Methods
private func locateByIP(request: SwiftLocationRequest, refresh: Bool = false, timeout: NSTimeInterval, onEnd: ( (place: CLPlacemark?, error: NSError?) -> Void)? ) {
let policy = (refresh == false ? NSURLRequestCachePolicy.ReturnCacheDataElseLoad : NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData)
let URLRequest = NSURLRequest(URL: NSURL(string: "https://ip-api.com/json")!, cachePolicy: policy, timeoutInterval: timeout)
NSURLConnection.sendAsynchronousRequest(URLRequest, queue: NSOperationQueue.mainQueue()) { response, data, error in
if request.isCancelled == true {
onEnd?(place: nil, error: nil)
return
}
if let data = data as NSData? {
do {
if let resultDict = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
let address = SwiftLocationParser()
address.parseIPLocationData(resultDict)
let placemark = address.getPlacemark()
onEnd?(place: placemark, error:nil)
}
} catch let error {
onEnd?(place: nil, error: NSError(domain: "\(error)", code: 1, userInfo: nil))
}
}
}
}
/**
Request will be added to the pool and related services are enabled automatically
- parameter request: request to add
*/
private func addRequest(request: SwiftLocationRequest!) {
// Add a new request to the array. Please note: add/remove is a sync operation due to avoid problems in a multitrheading env
dispatch_sync(blocksDispatchQueue) {
self.requests.append(request)
self.updateLocationManagerStatus()
}
}
/**
Search for a request with given identifier into the pool of requests
- parameter identifier: identifier of the request
- returns: the request object or nil
*/
private func request(identifier: Int?) -> SwiftLocationRequest? {
if let identifier = identifier as Int! {
for cRequest in self.requests {
if cRequest.ID == identifier {
return cRequest
}
}
}
return nil
}
/**
Return the requesta associated with a given CLRegion object
- parameter region: region instance
- returns: request if found, nil otherwise.
*/
private func requestForRegion(region: CLRegion!) -> SwiftLocationRequest? {
for request in requests {
if request.type == RequestType.RegionMonitor && request.region == region {
return request
}
}
return nil
}
/**
This method is called to complete an existing request, send result to the appropriate handler and remove it from the pool
(the last action will not occur for subscribe continuosly location notifications, until the request is not marked as cancelled)
- parameter request: request to complete
- parameter object: optional return object
- parameter error: optional error to report
*/
private func completeRequest(request: SwiftLocationRequest!, object: AnyObject?, error: NSError?) {
if request.type == RequestType.RegionMonitor { // If request is a region monitor we need to explictly stop it
manager.stopMonitoringForRegion(request.region!)
} else if (request.type == RequestType.BeaconRegionProximity) { // If request is a proximity beacon monitor we need to explictly stop it
manager.stopRangingBeaconsInRegion(request.beaconReg!)
}
// Sync remove item from requests pool
dispatch_sync(blocksDispatchQueue) {
var idx = 0
for cRequest in self.requests {
if cRequest.ID == request.ID {
cRequest.stopTimeout() // stop any running timeout timer
if cRequest.type == RequestType.ContinuousSignificantLocation ||
cRequest.type == RequestType.ContinuousLocationUpdate ||
cRequest.type == RequestType.SingleShotLocation ||
cRequest.type == RequestType.SingleShotIPLocation ||
cRequest.type == RequestType.BeaconRegionProximity {
// for location related event we want to report the last fetched result
if error != nil {
cRequest.onError?(error: error)
} else {
if object != nil {
cRequest.onSuccess?(location: object as! CLLocation?)
}
}
}
// If result is not continous location update notifications or, anyway, for any request marked as cancelled
// we want to remove it from the pool
if cRequest.isCancelled == true || cRequest.type != RequestType.ContinuousLocationUpdate {
self.requests.removeAtIndex(idx)
}
}
idx++
}
// Turn off any non-used hardware based upon the new list of running requests
self.updateLocationManagerStatus()
}
}
/**
This method return the highest accuracy you want to receive into the current bucket of requests
- returns: highest accuracy level you want to receive
*/
private func highestRequiredAccuracy() -> CLLocationAccuracy {
var highestAccuracy = CLLocationAccuracy(Double.infinity)
for request in requests {
let accuracyLevel = CLLocationAccuracy(request.desideredAccuracy.accuracyThreshold())
if accuracyLevel < highestAccuracy {
highestAccuracy = accuracyLevel
}
}
return highestAccuracy
}
/**
This method simply turn off/on hardware required by the list of active running requests.
The same method also ask to the user permissions to user core location.
*/
private func updateLocationManagerStatus() {
if requests.count > 0 {
let hasAlwaysKey = (NSBundle.mainBundle().objectForInfoDictionaryKey("NSLocationAlwaysUsageDescription") != nil)
let hasWhenInUseKey = (NSBundle.mainBundle().objectForInfoDictionaryKey("NSLocationWhenInUseUsageDescription") != nil)
if hasAlwaysKey == true {
manager.requestAlwaysAuthorization()
} else if hasWhenInUseKey == true {
manager.requestWhenInUseAuthorization()
} else {
// You've forgot something essential
assert(false, "To use location services in iOS 8+, your Info.plist must provide a value for either NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription.")
}
}
// Location Update
if hasActiveRequests([RequestType.ContinuousLocationUpdate,RequestType.SingleShotLocation]) == true {
let requiredAccuracy = self.highestRequiredAccuracy()
if requiredAccuracy != manager.desiredAccuracy {
manager.stopUpdatingLocation()
manager.desiredAccuracy = requiredAccuracy
}
manager.startUpdatingLocation()
} else {
manager.stopUpdatingLocation()
}
// Significant Location Changes
if hasActiveRequests([RequestType.ContinuousSignificantLocation]) == true {
manager.startMonitoringSignificantLocationChanges()
} else {
manager.stopMonitoringSignificantLocationChanges()
}
// Beacon/Region monitor is turned off automatically on completeRequest()
let beaconRegions = self.activeRequests([RequestType.BeaconRegionProximity])
for beaconRegion in beaconRegions {
manager.startRangingBeaconsInRegion(beaconRegion.beaconReg!)
}
}
/**
Return true if a request into the pool is of type described by the list of types passed
- parameter list: allowed types
- returns: true if at least one request with one the specified type is running
*/
private func hasActiveRequests(list: [RequestType]) -> Bool! {
for request in requests {
let idx = list.indexOf(request.type)
if idx != nil {
return true
}
}
return false
}
/**
Return the list of all request of a certain type
- parameter list: list of types to filter
- returns: output list with filtered active requests
*/
private func activeRequests(list: [RequestType]) -> [SwiftLocationRequest] {
var filteredList : [SwiftLocationRequest] = []
for request in requests {
let idx = list.indexOf(request.type)
if idx != nil {
filteredList.append(request)
}
}
return filteredList
}
/**
In case of an error we want to expire all queued notifications
- parameter error: error to notify
*/
private func expireAllRequests(error: NSError?, types: [RequestType]?) {
for request in requests {
let canMark = (types == nil ? true : (types!.indexOf(request.type) != nil))
if canMark == true {
request.markAsCancelled(error)
}
}
}
//MARK: [Private] Location Manager Delegate
public func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationsReceived(locations)
}
private func locationsReceived(locations: [AnyObject]!) {
if let location = locations.last as? CLLocation {
for request in requests {
if request.isAcceptable(location) == true {
completeRequest(request, object: location, error: nil)
}
}
}
}
public func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
let expiredTypes = [RequestType.ContinuousLocationUpdate,
RequestType.ContinuousSignificantLocation,
RequestType.SingleShotLocation,
RequestType.ContinuousHeadingUpdate,
RequestType.RegionMonitor]
expireAllRequests(error, types: expiredTypes)
}
public func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.Denied || status == CLAuthorizationStatus.Restricted {
// Clear out any pending location requests (which will execute the blocks with a status that reflects
// the unavailability of location services) since we now no longer have location services permissions
let err = NSError(domain: NSCocoaErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey : "Location services denied/restricted by parental control"])
locationManager(manager, didFailWithError: err)
} else if status == CLAuthorizationStatus.AuthorizedAlways || status == CLAuthorizationStatus.AuthorizedWhenInUse {
for request in requests {
request.startTimeout(nil)
}
updateLocationManagerStatus()
} else if status == CLAuthorizationStatus.NotDetermined {
print("not")
}
}
public func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) {
let request = requestForRegion(region)
request?.onRegionEnter?(region: region)
}
public func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) {
let request = requestForRegion(region)
request?.onRegionExit?(region: region)
}
public func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
for request in requests {
if request.beaconReg == region {
request.onRangingBeaconEvent?(beacons: beacons)
}
}
}
public func locationManager(manager: CLLocationManager, rangingBeaconsDidFailForRegion region: CLBeaconRegion, withError error: NSError) {
let expiredTypes = [RequestType.BeaconRegionProximity]
expireAllRequests(error, types: expiredTypes)
}
}
/**
This is the request type
- SingleShotLocation: Single location request with desidered accuracy level
- SingleShotIPLocation: Single location request with IP-based location search (used automatically with accuracy set to Country)
- ContinuousLocationUpdate: Continous location update
- ContinuousSignificantLocation: Significant location update requests
- ContinuousHeadingUpdate: Continous heading update requests
- RegionMonitor: Monitor specified region
- BeaconRegionProximity: Search for beacon services nearby the device
*/
enum RequestType {
case SingleShotLocation
case SingleShotIPLocation
case ContinuousLocationUpdate
case ContinuousSignificantLocation
case ContinuousHeadingUpdate
case RegionMonitor
case BeaconRegionProximity
}
private extension CLLocation {
func accuracyOfLocation() -> Accuracy! {
let timeSinceUpdate = fabs( self.timestamp.timeIntervalSinceNow )
let horizontalAccuracy = self.horizontalAccuracy
if horizontalAccuracy <= Accuracy.Room.accuracyThreshold() &&
timeSinceUpdate <= Accuracy.Room.timeThreshold() {
return Accuracy.Room
} else if horizontalAccuracy <= Accuracy.House.accuracyThreshold() &&
timeSinceUpdate <= Accuracy.House.timeThreshold() {
return Accuracy.House
} else if horizontalAccuracy <= Accuracy.Block.accuracyThreshold() &&
timeSinceUpdate <= Accuracy.Block.timeThreshold() {
return Accuracy.Block
} else if horizontalAccuracy <= Accuracy.Neighborhood.accuracyThreshold() &&
timeSinceUpdate <= Accuracy.Neighborhood.timeThreshold() {
return Accuracy.Neighborhood
} else if horizontalAccuracy <= Accuracy.City.accuracyThreshold() &&
timeSinceUpdate <= Accuracy.City.timeThreshold() {
return Accuracy.City
} else {
return Accuracy.None
}
}
}
//MARK: ===== [PRIVATE] SwiftLocationRequest Class =====
var requestNextID: RequestIDType = 0
/// This is the class which represent a single request.
/// Usually you should not interact with it. The only action you can perform on it is to call the cancel method to abort a running request.
public class SwiftLocationRequest: NSObject {
private(set) var type: RequestType
private(set) var ID: RequestIDType
private(set) var isCancelled: Bool!
var onTimeOut: onTimeoutReached?
// location related handlers
private var onSuccess: onSuccessLocate?
private var onError: onErrorLocate?
// region/beacon related handlers
private var region: CLRegion?
private var beaconReg: CLBeaconRegion?
private var onRegionEnter: onRegionEvent?
private var onRegionExit: onRegionEvent?
private var onRangingBeaconEvent: onRangingBacon?
var desideredAccuracy: Accuracy!
private var timeoutTimer: NSTimer?
private var timeoutInterval: NSTimeInterval
private var hasTimeout: Bool!
//MARK: Init - Private Methods
private init(requestType: RequestType, accuracy: Accuracy,timeout: NSTimeInterval, success: onSuccessLocate, fail: onErrorLocate?) {
type = requestType
requestNextID++
ID = requestNextID
isCancelled = false
onSuccess = success
onError = fail
desideredAccuracy = accuracy
timeoutInterval = timeout
hasTimeout = false
super.init()
if SwiftLocation.state == ServiceStatus.Available {
self.startTimeout(nil)
}
}
private init(region: CLRegion!, onEnter: onRegionEvent?, onExit: onRegionEvent?) {
type = RequestType.RegionMonitor
requestNextID++
ID = requestNextID
isCancelled = false
onRegionEnter = onEnter
onRegionExit = onExit
desideredAccuracy = Accuracy.None
timeoutInterval = 0
hasTimeout = false
super.init()
}
private init(beaconRegion: CLBeaconRegion!, onRanging: onRangingBacon?) {
type = RequestType.BeaconRegionProximity
requestNextID++
ID = requestNextID
isCancelled = false
onRangingBeaconEvent = onRanging
desideredAccuracy = Accuracy.None
timeoutInterval = 0
hasTimeout = false
beaconReg = beaconRegion
super.init()
}
//MARK: Public Methods
/**
Cancel method abort a running request
*/
private func markAsCancelled(error: NSError?) {
isCancelled = true
stopTimeout()
SwiftLocation.shared.completeRequest(self, object: nil, error: error)
}
//MARK: Private Methods
private func isAcceptable(location: CLLocation) -> Bool! {
if isCancelled == true {
return false
}
if desideredAccuracy == Accuracy.None {
return true
}
let locAccuracy: Accuracy! = location.accuracyOfLocation()
let valid = (locAccuracy.rawValue >= desideredAccuracy.rawValue)
return valid
}
private func startTimeout(forceValue: NSTimeInterval?) {
if hasTimeout == false && timeoutInterval > 0 {
let value = (forceValue != nil ? forceValue! : timeoutInterval)
timeoutTimer = NSTimer.scheduledTimerWithTimeInterval(value, target: self, selector: "timeoutReached", userInfo: nil, repeats: false)
}
}
private func stopTimeout() {
timeoutTimer?.invalidate()
timeoutTimer = nil
}
public func timeoutReached() {
let additionalTime: NSTimeInterval? = onTimeOut?()
if additionalTime == nil {
timeoutTimer?.invalidate()
timeoutTimer = nil
hasTimeout = true
isCancelled = false
let error = NSError(domain: NSCocoaErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey : "Timeout reached"])
SwiftLocation.shared.completeRequest(self, object: nil, error: error)
} else {
hasTimeout = false
startTimeout(additionalTime!)
}
}
}
//MARK: ===== [PRIVATE] SwiftLocationParser Class =====
// Portions of this class are part of the LocationManager mady by varshylmobile (AddressParser class):
// (Made by https://github.com/varshylmobile/LocationManager)
private class SwiftLocationParser: NSObject {
private var latitude = NSString()
private var longitude = NSString()
private var streetNumber = NSString()
private var route = NSString()
private var locality = NSString()
private var subLocality = NSString()
private var formattedAddress = NSString()
private var administrativeArea = NSString()
private var administrativeAreaCode = NSString()
private var subAdministrativeArea = NSString()
private var postalCode = NSString()
private var country = NSString()
private var subThoroughfare = NSString()
private var thoroughfare = NSString()
private var ISOcountryCode = NSString()
private var state = NSString()
override init() {
super.init()
}
private func parseIPLocationData(JSON: NSDictionary) -> Bool {
let status = JSON["status"] as? String
if status != "success" {
return false
}
self.country = JSON["country"] as! NSString
self.ISOcountryCode = JSON["countryCode"] as! NSString
if let lat = JSON["lat"] as? NSNumber, lon = JSON["lon"] as? NSNumber {
self.longitude = lat.description
self.latitude = lon.description
}
self.postalCode = JSON["zip"] as! NSString
return true
}
private func parseAppleLocationData(placemark:CLPlacemark) {
let addressLines = placemark.addressDictionary?["FormattedAddressLines"] as! NSArray
//self.streetNumber = placemark.subThoroughfare ? placemark.subThoroughfare : ""
self.streetNumber = placemark.thoroughfare ?? ""
self.locality = placemark.locality ?? ""
self.postalCode = placemark.postalCode ?? ""
self.subLocality = placemark.subLocality ?? ""
self.administrativeArea = placemark.administrativeArea ?? ""
self.country = placemark.country ?? ""
if let location = placemark.location {
self.longitude = location.coordinate.longitude.description;
self.latitude = location.coordinate.latitude.description
}
if addressLines.count>0 {
self.formattedAddress = addressLines.componentsJoinedByString(", ")
} else {
self.formattedAddress = ""
}
}
private func parseGoogleLocationData(resultDict:NSDictionary) {
let locationDict = (resultDict.valueForKey("results") as! NSArray).firstObject as! NSDictionary
let formattedAddrs = locationDict.objectForKey("formatted_address") as! NSString
let geometry = locationDict.objectForKey("geometry") as! NSDictionary
let location = geometry.objectForKey("location") as! NSDictionary
let lat = location.objectForKey("lat") as! Double
let lng = location.objectForKey("lng") as! Double
self.latitude = lat.description
self.longitude = lng.description
let addressComponents = locationDict.objectForKey("address_components") as! NSArray
self.subThoroughfare = component("street_number", inArray: addressComponents, ofType: "long_name")
self.thoroughfare = component("route", inArray: addressComponents, ofType: "long_name")
self.streetNumber = self.subThoroughfare
self.locality = component("locality", inArray: addressComponents, ofType: "long_name")
self.postalCode = component("postal_code", inArray: addressComponents, ofType: "long_name")
self.route = component("route", inArray: addressComponents, ofType: "long_name")
self.subLocality = component("subLocality", inArray: addressComponents, ofType: "long_name")
self.administrativeArea = component("administrative_area_level_1", inArray: addressComponents, ofType: "long_name")
self.administrativeAreaCode = component("administrative_area_level_1", inArray: addressComponents, ofType: "short_name")
self.subAdministrativeArea = component("administrative_area_level_2", inArray: addressComponents, ofType: "long_name")
self.country = component("country", inArray: addressComponents, ofType: "long_name")
self.ISOcountryCode = component("country", inArray: addressComponents, ofType: "short_name")
self.formattedAddress = formattedAddrs;
}
private func getPlacemark() -> CLPlacemark {
var addressDict = [String:AnyObject]()
let formattedAddressArray = self.formattedAddress.componentsSeparatedByString(", ") as Array
let kSubAdministrativeArea = "SubAdministrativeArea"
let kSubLocality = "SubLocality"
let kState = "State"
let kStreet = "Street"
let kThoroughfare = "Thoroughfare"
let kFormattedAddressLines = "FormattedAddressLines"
let kSubThoroughfare = "SubThoroughfare"
let kPostCodeExtension = "PostCodeExtension"
let kCity = "City"
let kZIP = "ZIP"
let kCountry = "Country"
let kCountryCode = "CountryCode"
addressDict[kSubAdministrativeArea] = self.subAdministrativeArea
addressDict[kSubLocality] = self.subLocality
addressDict[kState] = self.administrativeAreaCode
addressDict[kStreet] = formattedAddressArray.first! as NSString
addressDict[kThoroughfare] = self.thoroughfare
addressDict[kFormattedAddressLines] = formattedAddressArray
addressDict[kSubThoroughfare] = self.subThoroughfare
addressDict[kPostCodeExtension] = ""
addressDict[kCity] = self.locality
addressDict[kZIP] = self.postalCode
addressDict[kCountry] = self.country
addressDict[kCountryCode] = self.ISOcountryCode
let lat = self.latitude.doubleValue
let lng = self.longitude.doubleValue
let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDict)
return (placemark as CLPlacemark)
}
private func component(component:NSString,inArray:NSArray,ofType:NSString) -> NSString {
let index:NSInteger = inArray.indexOfObjectPassingTest { (obj, idx, stop) -> Bool in
let objDict:NSDictionary = obj as! NSDictionary
let types:NSArray = objDict.objectForKey("types") as! NSArray
let type = types.firstObject as! NSString
return type.isEqualToString(component as String)
}
if index == NSNotFound {
return ""
}
if index >= inArray.count {
return ""
}
let type = ((inArray.objectAtIndex(index) as! NSDictionary).valueForKey(ofType as String)!) as! NSString
if type.length > 0 {
return type
}
return ""
}
} | mit | 3d748f72edbd4d60e576e749fa1ee7a8 | 36.578456 | 302 | 0.725217 | 4.316446 | false | false | false | false |
mleiv/SerializableData | SerializableDataDemo/SerializableDataDemo/CoreDataPersonController.swift | 1 | 2720 | //
// CoreDataPersonController.swift
// SerializableDataDemo
//
// Created by Emily Ivie on 10/16/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import UIKit
class CoreDataPersonController: UIViewController {
var isNew = true
var person = CoreDataPerson(name: "")
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var professionField: UITextField!
@IBOutlet weak var organizationField: UITextField!
@IBOutlet weak var notesField: UITextView!
@IBOutlet weak var deleteButton: UIButton!
var spinner: Spinner?
override func viewDidLoad() {
super.viewDidLoad()
spinner = Spinner(parent: self)
spinner?.start()
if person.name.isEmpty == false {
isNew = false
}
deleteButton.isHidden = isNew
setFieldValues()
spinner?.stop()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func savePerson(_ sender: UIButton) {
spinner?.start()
saveFieldValues()
let name = person.name
if name.isEmpty == false {
_ = person.save()
showMessage("Saved \(name).", handler: { _ in
self.spinner?.stop()
_ = self.navigationController?.popViewController(animated: true)
})
} else {
showMessage("Please enter a name before saving.", handler: { _ in
self.spinner?.stop()
})
}
}
@IBAction func deletePerson(_ sender: UIButton) {
spinner?.start()
let name = person.name
_ = person.delete()
showMessage("Deleted \(name).", handler: { _ in
self.spinner?.stop()
_ = self.navigationController?.popViewController(animated: true)
})
}
func setFieldValues() {
nameField.text = person.name
professionField.text = person.profession
organizationField.text = person.organization
notesField.text = person.notes
}
func saveFieldValues() {
person.name = nameField.text ?? ""
person.profession = professionField.text
person.organization = organizationField.text
person.notes = notesField.text
}
func showMessage(_ message: String, handler: @escaping ((UIAlertAction) -> Void) = { _ in }) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Okay", style: .default, handler: handler))
self.present(alertController, animated: true) {}
}
}
| mit | 926e2e79b3ed6233e5d12ec4571444b8 | 30.252874 | 101 | 0.60868 | 4.87276 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/PledgeView/Views/PledgeViewCTAContainerView.swift | 1 | 8353 | import KsApi
import Library
import PassKit
import Prelude
import UIKit
protocol PledgeViewCTAContainerViewDelegate: AnyObject {
func applePayButtonTapped()
func goToLoginSignup()
func submitButtonTapped()
func termsOfUseTapped(with helptype: HelpType)
}
private enum Layout {
enum Button {
static let minHeight: CGFloat = 48.0
}
}
final class PledgeViewCTAContainerView: UIView {
// MARK: - Properties
private lazy var applePayButton: PKPaymentButton = { PKPaymentButton() }()
private lazy var ctaStackView: UIStackView = {
UIStackView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var termsTextView: UITextView = { UITextView(frame: .zero) |> \.delegate .~ self }()
private lazy var disclaimerStackView: UIStackView = {
UIStackView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var continueButton: UIButton = {
UIButton(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var submitButton: UIButton = {
UIButton(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var rootStackView: UIStackView = {
UIStackView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
weak var delegate: PledgeViewCTAContainerViewDelegate?
private let viewModel: PledgeViewCTAContainerViewModelType = PledgeViewCTAContainerViewModel()
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
self.configureSubviews()
self.setupConstraints()
self.bindViewModel()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Styles
override func bindStyles() {
super.bindStyles()
_ = self
|> \.layoutMargins .~ .init(all: Styles.grid(3))
_ = self.applePayButton
|> applePayButtonStyle
_ = self.ctaStackView
|> ctaStackViewStyle
_ = self.termsTextView
|> termsTextViewStyle
_ = self.disclaimerStackView
|> disclaimerStackViewStyle
_ = self.layer
|> layerStyle
_ = self.continueButton
|> greenButtonStyle
|> UIButton.lens.title(for: .normal) %~ { _ in Strings.Continue() }
_ = self.submitButton
|> greenButtonStyle
_ = self.rootStackView
|> rootStackViewStyle
}
// MARK: - View Model
override func bindViewModel() {
super.bindViewModel()
self.viewModel.outputs.notifyDelegateToGoToLoginSignup
.observeForUI()
.observeValues { [weak self] in
guard let self = self else { return }
self.delegate?.goToLoginSignup()
}
self.viewModel.outputs.notifyDelegateSubmitButtonTapped
.observeForUI()
.observeValues { [weak self] in
guard let self = self else { return }
self.delegate?.submitButtonTapped()
}
self.viewModel.outputs.notifyDelegateApplePayButtonTapped
.observeForUI()
.observeValues { [weak self] in
guard let self = self else { return }
self.delegate?.applePayButtonTapped()
}
self.viewModel.outputs.notifyDelegateOpenHelpType
.observeForUI()
.observeValues { [weak self] helpType in
guard let self = self else { return }
self.delegate?.termsOfUseTapped(with: helpType)
}
self.applePayButton.rac.hidden = self.viewModel.outputs.applePayButtonIsHidden
self.continueButton.rac.hidden = self.viewModel.outputs.continueButtonIsHidden
self.submitButton.rac.hidden = self.viewModel.outputs.submitButtonIsHidden
self.submitButton.rac.title = self.viewModel.outputs.submitButtonTitle
self.submitButton.rac.enabled = self.viewModel.outputs.submitButtonIsEnabled
}
// MARK: - Configuration
func configureWith(value: PledgeViewCTAContainerViewData) {
self.viewModel.inputs.configureWith(value: value)
}
// MARK: Functions
private func configureSubviews() {
_ = (self.rootStackView, self)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToEdgesInParent()
_ = ([self.continueButton, self.submitButton, self.applePayButton], self.ctaStackView)
|> ksr_addArrangedSubviewsToStackView()
_ = ([self.termsTextView], self.disclaimerStackView)
|> ksr_addArrangedSubviewsToStackView()
_ = ([self.ctaStackView, self.disclaimerStackView], self.rootStackView)
|> ksr_addArrangedSubviewsToStackView()
self.submitButton.addTarget(
self, action: #selector(self.submitButtonTapped), for: .touchUpInside
)
self.continueButton.addTarget(
self, action: #selector(self.continueButtonTapped), for: .touchUpInside
)
self.applePayButton.addTarget(
self,
action: #selector(self.applePayButtonTapped),
for: .touchUpInside
)
}
private func setupConstraints() {
NSLayoutConstraint.activate([
self.submitButton.heightAnchor.constraint(greaterThanOrEqualToConstant: Layout.Button.minHeight),
self.applePayButton.heightAnchor.constraint(greaterThanOrEqualToConstant: Layout.Button.minHeight)
])
}
@objc func submitButtonTapped() {
self.viewModel.inputs.submitButtonTapped()
}
@objc func continueButtonTapped() {
self.viewModel.inputs.continueButtonTapped()
}
@objc func applePayButtonTapped() {
self.viewModel.inputs.applePayButtonTapped()
}
}
extension PledgeViewCTAContainerView: UITextViewDelegate {
func textView(
_: UITextView, shouldInteractWith _: NSTextAttachment,
in _: NSRange, interaction _: UITextItemInteraction
) -> Bool {
return false
}
func textView(
_: UITextView, shouldInteractWith url: URL, in _: NSRange,
interaction _: UITextItemInteraction
) -> Bool {
self.viewModel.inputs.tapped(url)
return false
}
}
// MARK: - Styles
private let rootStackViewStyle: StackViewStyle = { stackView in
stackView
|> \.axis .~ NSLayoutConstraint.Axis.vertical
|> \.isLayoutMarginsRelativeArrangement .~ true
|> \.layoutMargins .~ UIEdgeInsets.init(
top: Styles.grid(2),
left: Styles.grid(3),
bottom: Styles.grid(0),
right: Styles.grid(3)
)
|> \.spacing .~ Styles.grid(1)
}
private let ctaStackViewStyle: StackViewStyle = { stackView in
stackView
|> \.axis .~ .horizontal
|> \.distribution .~ .fillEqually
|> \.spacing .~ Styles.grid(2)
|> \.layoutMargins .~ UIEdgeInsets.init(topBottom: Styles.grid(2), leftRight: Styles.grid(0))
|> \.isLayoutMarginsRelativeArrangement .~ true
}
private let disclaimerStackViewStyle: StackViewStyle = { stackView in
stackView
|> \.axis .~ .horizontal
|> \.layoutMargins .~ UIEdgeInsets.init(
top: Styles.grid(0),
left: Styles.grid(5),
bottom: Styles.grid(1),
right: Styles.grid(5)
)
|> \.isLayoutMarginsRelativeArrangement .~ true
}
private let layerStyle: LayerStyle = { layer in
layer
|> checkoutLayerCardRoundedStyle
|> \.backgroundColor .~ UIColor.ksr_white.cgColor
|> \.shadowColor .~ UIColor.ksr_black.cgColor
|> \.shadowOpacity .~ 0.12
|> \.shadowOffset .~ CGSize(width: 0, height: -1.0)
|> \.shadowRadius .~ CGFloat(1.0)
|> \.maskedCorners .~ [
CACornerMask.layerMaxXMinYCorner,
CACornerMask.layerMinXMinYCorner
]
}
private let termsTextViewStyle: TextViewStyle = { (textView: UITextView) -> UITextView in
_ = textView
|> tappableLinksViewStyle
|> \.attributedText .~ attributedTermsText()
|> \.accessibilityTraits .~ [.staticText]
|> \.textAlignment .~ .center
return textView
}
private func attributedTermsText() -> NSAttributedString? {
let baseUrl = AppEnvironment.current.apiService.serverConfig.webBaseUrl
guard
let termsOfUseLink = HelpType.terms.url(withBaseUrl: baseUrl)?.absoluteString,
let privacyPolicyLink = HelpType.privacy.url(withBaseUrl: baseUrl)?.absoluteString,
let cookiePolicyLink = HelpType.cookie.url(withBaseUrl: baseUrl)?.absoluteString
else { return nil }
let string = Strings.By_pledging_you_agree_to_Kickstarters_Terms_of_Use_Privacy_Policy_and_Cookie_Policy(
terms_of_use_link: termsOfUseLink,
privacy_policy_link: privacyPolicyLink,
cookie_policy_link: cookiePolicyLink
)
return checkoutAttributedLink(with: string)
}
| apache-2.0 | e4777af6b30fb6f87ba5b69acd0f75ee | 27.411565 | 107 | 0.697235 | 4.684801 | false | false | false | false |
szpnygo/firefox-ios | Sync/Synchronizers/TabsSynchronizer.swift | 4 | 3490 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import XCGLogger
// TODO: same comment as for SyncAuthState.swift!
private let log = XCGLogger.defaultInstance()
private let TabsStorageVersion = 1
public class TabsSynchronizer: BaseSingleCollectionSynchronizer, Synchronizer {
public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) {
super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, collection: "tabs")
}
override var storageVersion: Int {
return TabsStorageVersion
}
public func synchronizeLocalTabs(localTabs: RemoteClientsAndTabs, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult {
func onResponseReceived(response: StorageResponse<[Record<TabsPayload>]>) -> Success {
func afterWipe() -> Success {
log.info("Fetching tabs.")
func doInsert(record: Record<TabsPayload>) -> Deferred<Result<(Int)>> {
let remotes = record.payload.remoteTabs
log.debug("\(remotes)")
log.info("Inserting \(remotes.count) tabs for client \(record.id).")
return localTabs.insertOrUpdateTabsForClientGUID(record.id, tabs: remotes)
}
// TODO: decide whether to upload ours.
let ourGUID = self.scratchpad.clientGUID
let records = response.value
let responseTimestamp = response.metadata.lastModifiedMilliseconds
log.debug("Got \(records.count) tab records.")
let allDone = all(records.filter({ $0.id != ourGUID }).map(doInsert))
return allDone.bind { (results) -> Success in
if let failure = find(results, { $0.isFailure }) {
return deferResult(failure.failureValue!)
}
self.lastFetched = responseTimestamp!
return succeed()
}
}
// If this is a fresh start, do a wipe.
if self.lastFetched == 0 {
log.info("Last fetch was 0. Wiping tabs.")
return localTabs.wipeTabs()
>>== afterWipe
}
return afterWipe()
}
if let reason = self.reasonToNotSync(storageClient) {
return deferResult(SyncStatus.NotStarted(reason))
}
if !self.remoteHasChanges(info) {
// Nothing to do.
// TODO: upload local tabs if they've changed or we're in a fresh start.
return deferResult(.Completed)
}
let keys = self.scratchpad.keys?.value
let encoder = RecordEncoder<TabsPayload>(decode: { TabsPayload($0) }, encode: { $0 })
if let encrypter = keys?.encrypter(self.collection, encoder: encoder) {
let tabsClient = storageClient.clientForCollection(self.collection, encrypter: encrypter)
return tabsClient.getSince(self.lastFetched)
>>== onResponseReceived
>>> { deferResult(.Completed) }
}
log.error("Couldn't make tabs factory.")
return deferResult(FatalError(message: "Couldn't make tabs factory."))
}
}
| mpl-2.0 | b6618955f0eaaccb95128d064b6ac72c | 39.581395 | 155 | 0.604298 | 5.271903 | false | false | false | false |
EclipseSoundscapes/EclipseSoundscapes | EclipseSoundscapes/Features/MediaCenter/Views/MediaSlider.swift | 1 | 1430 | //
// MediaSlider.swift
// EclipseSoundscapes
//
// Created by Arlindo on 5/10/20.
// Copyright © 2020 Arlindo Goncalves. All rights reserved.
//
import UIKit
class MediaSlider: UISlider {
private var thumbImageView: UIImageView?
private var maxValueLabel: String?
override var maximumValue: Float {
didSet {
maxValueLabel = TimeInterval(maximumValue).detailedTimeString
setAccessibilityLabel()
}
}
override func setValue(_ value: Float, animated: Bool) {
super.setValue(value, animated: animated)
setAccessibilityLabel()
}
override func accessibilityDecrement() {
super.accessibilityDecrement()
setAccessibilityLabel()
}
override func accessibilityIncrement() {
super.accessibilityIncrement()
setAccessibilityLabel()
}
func setAccessibilityLabel() {
accessibilityValue = localizedString(key: "MediaSliderTrackPosition", arguments: TimeInterval(value).detailedTimeString, maxValueLabel ?? "")
}
func expand() {
thumbImageView = subviews.last as? UIImageView
UIView.animate(withDuration: 0.2) {
self.thumbImageView?.transform = CGAffineTransform.init(scaleX: 1.5, y: 1.5)
}
}
func compress() {
UIView.animate(withDuration: 0.1, animations: {
self.thumbImageView?.transform = .identity
})
}
}
| gpl-3.0 | 224053bc8c51f06e37044f49c581b7f5 | 25.462963 | 149 | 0.653604 | 4.979094 | false | false | false | false |
srosskopf/DMpruefungen | DMpruefer/Reachability.swift | 1 | 1300 | //
// Reachability.swift
// DMpruefer
//
// Created by Sebastian Roßkopf on 01.03.16.
// Copyright © 2016 ross. All rights reserved.
//
import Foundation
import SystemConfiguration
public class Reachability {
/*
see http://stackoverflow.com/questions/30743408/check-for-internet-connection-in-swift-2-ios-9?lq=1 for details
big thanks to http://stackoverflow.com/users/2303865/leo-dabus
*/
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
}
| mit | 79ec7128d1643b6d149a1804aa44b7f7 | 25.489796 | 119 | 0.624807 | 4.916667 | false | false | false | false |
piars777/TheMovieDatabaseSwiftWrapper | Sources/Client/Client_People.swift | 1 | 734 | //
// Client_People.swift
// MDBSwiftWrapper
//
// Created by George on 2016-03-08.
// Copyright © 2016 GeorgeKye. All rights reserved.
//
import Foundation
extension Client{
static func Person(urlType: String!, api_key: String!, language: String?, page: Int?, completion: (ClientReturn) -> ()) -> (){
let url = "http://api.themoviedb.org/3/person/\(urlType)"
var parameters: [String : AnyObject] = ["api_key": api_key]
if(language != nil){ parameters["language"] = language }
if(page != nil){parameters["page"] = page}
networkRequest(url: url, parameters: parameters, completion: {
apiReturn in
completion(apiReturn)
})
}
} | mit | 3d34a26716be878d5beeac1e9a5c5f72 | 28.36 | 130 | 0.59618 | 4.072222 | false | false | false | false |
mnisn/zhangchu | zhangchu/zhangchu/classes/recipe/recommend/main/view/RecommendHeaderView.swift | 1 | 2570 | //
// RecommendHeaderView.swift
// zhangchu
//
// Created by 苏宁 on 2016/10/27.
// Copyright © 2016年 suning. All rights reserved.
//
import UIKit
class RecommendHeaderView: UIView {
var clickClosure:RecipClickClosure?
var listModel:RecipeRecommendWidgetList?{
didSet{
configText((listModel?.title)!)
}
}
private var titleLabel:UILabel?
private var imgView:UIImageView?
private var space:CGFloat = 40
private var margin:CGFloat = 20
private var iconWidth:CGFloat = 22
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(white: 0.9, alpha: 1)
let bgView = UIView.createView()
bgView.backgroundColor = UIColor.whiteColor()
bgView.frame = CGRectMake(0, 10, bounds.width, 44)
addSubview(bgView)
let tap = UITapGestureRecognizer(target: self, action: #selector(tapClick))
bgView.addGestureRecognizer(tap)
//
titleLabel = UILabel.createLabel(nil, textAlignment: .Left, font: UIFont.systemFontOfSize(17))
bgView.addSubview(titleLabel!)
//
let iconImg = UIImage(named: "more_icon")
imgView = UIImageView(image: iconImg)
bgView.addSubview(imgView!)
}
//显示文字
func configText(text:String)
{
//计算文字的宽度
let str = NSString(string: text)
//参1 文字的最大范围
//参2 文字的显示规范
//参3 文字的属性
//参4 上下文
let maxWidth = bounds.width - space * 2 - iconWidth - margin
let textWidth = str.boundingRectWithSize(CGSizeMake(maxWidth, 44), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(17)], context: nil).size.width
let labelSpaceX = (maxWidth - textWidth) / 2
//设置文字
titleLabel!.text = text
//
titleLabel?.frame = CGRectMake(space + labelSpaceX, 0, textWidth, 44)
titleLabel?.textAlignment = .Center
imgView?.frame = CGRectMake(((titleLabel?.frame.origin.x)! + margin + textWidth), 11, iconWidth, iconWidth)
}
func tapClick()
{
if clickClosure != nil && listModel?.title_link != nil
{
clickClosure!((listModel?.title_link)!)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 7e54593b21d7ccb9869d054f511183b6 | 22.855769 | 197 | 0.598146 | 4.569061 | false | false | false | false |
JadenGeller/Parsley | Parsley/ParsleyTests/LanguageTest.swift | 1 | 9363 | //
// LanguageTest.swift
// Parsley
//
// Created by Jaden Geller on 2/16/16.
// Copyright © 2016 Jaden Geller. All rights reserved.
//
import Foundation
import XCTest
import Parsley
enum Sign: Character, Matchable {
case Negative = "-"
case Positive = "+"
static var all: [Sign] = [.Negative, .Positive]
var matcher: Parser<Character, ()> {
return character(rawValue).discard()
}
}
enum Operator: String, Matchable, Equatable {
case Assignment = ":="
case Lambda = "->"
case Binding = "::"
static var all: [Operator] = [.Assignment, .Lambda, .Binding]
var matcher: Parser<Character, ()> {
return string(rawValue).discard()
}
var description: String {
return rawValue
}
}
func ==(lhs: Operator, rhs: Operator) -> Bool {
switch (lhs, rhs) {
case (.Assignment, .Assignment): return true
case (.Lambda, .Lambda): return true
case (.Binding, .Binding): return true
default:
return false
}
}
enum ControlFlow: Matchable {
case Nested(PairedDelimiter)
case Terminator
case Infix(Operator)
static let terminatorCharacter: Character = ";"
static var all = PairedDelimiter.all.map(ControlFlow.Nested) + [.Terminator] + Operator.all.map(ControlFlow.Infix)
var matcher: Parser<Character, ()> {
switch self {
case .Nested(let pairedDelimiter): return pairedDelimiter.matcher
case .Terminator: return character(ControlFlow.terminatorCharacter).discard()
case .Infix(let infixOperator): return infixOperator.matcher
}
}
var description: String {
switch self {
case .Nested(let pairedDelimiter): return pairedDelimiter.description
case .Terminator: return String(ControlFlow.terminatorCharacter)
case .Infix(let infixOperator): return infixOperator.description
}
}
}
enum Token: Parsable {
case Bare(String)
case Literal(LiteralValue)
case Flow(ControlFlow)
private static let bareWord = prepend(
letter ?? character("_"),
many(letter ?? digit ?? character("_"))
).stringify().withError("bareWord")
static var parser = LiteralValue.parser.map(Token.Literal) ?? ControlFlow.parser.map(Token.Flow) ?? bareWord.map(Token.Bare)
var description: String {
switch self {
case .Bare(let value): return value
case .Literal(let value): return "\(value)"
case .Flow(let value): return value.description
}
}
}
struct PairedDelimiter: Equatable, Matchable {
enum Symbol: Equatable {
case Parenthesis
case CurlyBracket
static var all: [Symbol] = [.Parenthesis, .CurlyBracket]
}
enum Facing: Equatable {
case Open
case Close
static var all: [Facing] = [.Open, .Close]
}
let symbol: Symbol
let facing: Facing
var characterValue: Character {
switch symbol {
case .Parenthesis:
switch facing {
case .Open: return "("
case .Close: return ")"
}
case .CurlyBracket:
switch facing {
case .Open: return "{"
case .Close: return "}"
}
}
}
static var all = Symbol.all.flatMap{ symbol in
Facing.all.map{ facing in
return PairedDelimiter(symbol: symbol, facing: facing)
}
}
var matcher: Parser<Character, ()> {
return character(characterValue).discard()
}
var description: String {
return String(characterValue)
}
}
func ==(lhs: PairedDelimiter.Symbol, rhs: PairedDelimiter.Symbol) -> Bool {
switch (lhs, rhs) {
case (.Parenthesis, .Parenthesis): return true
case (.CurlyBracket, .CurlyBracket): return true
default: return false
}
}
func ==(lhs: PairedDelimiter.Facing, rhs: PairedDelimiter.Facing) -> Bool {
switch (lhs, rhs) {
case (.Open, .Open): return true
case (.Close, .Close): return true
default: return false
}
}
func ==(lhs: PairedDelimiter, rhs: PairedDelimiter) -> Bool {
return lhs.facing == rhs.facing && lhs.symbol == rhs.symbol
}
extension Sign {
init?(character: Character) {
switch character {
case "-":
self = .Negative
case "+":
self = .Positive
default:
return nil
}
}
}
enum LiteralValue: Parsable, Equatable {
case IntegerLiteral(sign: Sign, digits: DigitList)
case FloatingPointLiteral(sign: Sign, significand: DigitList, exponent: Int)
case StringLiteral(String)
private static let sign = Sign.parser.otherwise(.Positive)
private static let digits = many1(digit)
.stringify()
.map(DigitList.init).map{ $0! }
private static let integerLiteral = pair(sign, digits)
.map(LiteralValue.IntegerLiteral)
.withError("integerLiteral")
private static let floatingPointLiteral = Parser<Character, LiteralValue> { state in
let theSign = try sign.parse(state)
let leftDigits = try digits.parse(state)
let decimal = try character(".").parse(state)
let rightDigits = try digits.parse(state)
return .FloatingPointLiteral(sign: theSign, significand: leftDigits + rightDigits, exponent: -rightDigits.digits.count)
}
private static let stringLiteral = between(character("\""), parseFew: any(), usingEscape: character("\\"))
.stringify()
.map(LiteralValue.StringLiteral)
static var parser = floatingPointLiteral ?? integerLiteral ?? stringLiteral
var description: String {
switch self {
case let .IntegerLiteral(sign, digits):
// TODO: Clean this up!
return String([sign.rawValue] + digits.digits.flatMap{ String($0.rawValue).characters })
case .FloatingPointLiteral:
fatalError("Not implemented")
case let .StringLiteral(string):
return "\"" + string + "\""
}
}
}
func ==(lhs: LiteralValue, rhs: LiteralValue) -> Bool {
switch (lhs, rhs) {
case let (.IntegerLiteral(l), .IntegerLiteral(r)):
return l.sign == r.sign && l.digits == r.digits
case let (.FloatingPointLiteral(l), .FloatingPointLiteral(r)):
return l.sign == r.sign && l.significand == r.significand && l.exponent == r.exponent
case let (.StringLiteral(l), .StringLiteral(r)):
return l == r
default:
return false
}
}
enum Digit: Int, Equatable {
case Zero
case One
case Two
case Three
case Four
case Five
case Six
case Seven
case Eight
case Nine
}
func ==(lhs: Digit, rhs: Digit) -> Bool {
return lhs.rawValue == rhs.rawValue
}
struct DigitList: SequenceType, Equatable {
let digits: [Digit]
init(digits: [Digit]) {
self.digits = digits
}
init?(string: String) {
struct Exception: ErrorType { }
do {
self.digits = try string.characters.map { c in
guard let v = Int(String(c)) else { throw Exception() }
guard let d = Digit(rawValue: v) else { throw Exception() }
return d
}
} catch {
return nil
}
}
func generate() -> IndexingGenerator<[Digit]> {
return digits.generate()
}
}
private enum Expression {
}
private enum Statement {
case Binding(identifier: String, value: Expression)
}
func +(lhs: DigitList, rhs: DigitList) -> DigitList {
return DigitList(digits: lhs.digits + rhs.digits)
}
func ==(lhs: DigitList, rhs: DigitList) -> Bool {
return lhs.digits == rhs.digits
}
class LanguageTest: XCTestCase {
func testDelimiter() {
XCTAssertEqual(PairedDelimiter(symbol: .CurlyBracket, facing: .Open), try? PairedDelimiter.parser.parse("{".characters))
}
func testLiteral() {
XCTAssertEqual(
LiteralValue.IntegerLiteral(sign: .Positive, digits: DigitList(string: "5232")!),
try? LiteralValue.parser.parse("+5232")
)
XCTAssertEqual(
LiteralValue.IntegerLiteral(sign: .Positive, digits: DigitList(string: "085328235")!),
try? LiteralValue.parser.parse("085328235")
)
XCTAssertEqual(
LiteralValue.FloatingPointLiteral(sign: .Negative, significand: DigitList(string: "583253218")!, exponent: -5),
try? LiteralValue.parser.parse("-5832.53218")
)
XCTAssertEqual(
LiteralValue.StringLiteral("Hello \"world\""),
try? LiteralValue.parser.parse("\"Hello \\\"world\\\"\"")
)
}
func testOperator() {
XCTAssertEqual(
Operator.Assignment,
Operator.parse(":=")
)
XCTAssertEqual(
Operator.Lambda,
Operator.parse("->")
)
XCTAssertEqual(
Operator.Binding,
Operator.parse("::")
)
}
func testTokenize() {
print(try? tokens(Token.self).parse("factorial := (x :: Int) -> {\n mutable x := x\n mutable result := 1\n while (_ -> greater x 0) (_ -> set result (multiply result x))\n result\n} :: Int"))
}
}
| mit | 71050e96c966dd21c1f42864661ffe41 | 27.369697 | 212 | 0.596667 | 4.393243 | false | false | false | false |
larryhou/swift | VisionPower/VisionPower/BarcodeViewController.swift | 1 | 2411 | //
// BarcodeViewController.swift
// VisionPower
//
// Created by larryhou on 06/09/2017.
// Copyright © 2017 larryhou. All rights reserved.
//
import Foundation
import UIKit
class BarcodeViewController: UIViewController {
var snapshotController: PhotoViewController?
var cameraController: CameraViewController?
var currentController: UIViewController!
override func viewDidLoad() {
super.viewDidLoad()
if let controller = storyboard?.instantiateViewController(withIdentifier: "CameraViewController") as? CameraViewController {
self.cameraController = controller
addChildViewController(controller)
}
if let controller = storyboard?.instantiateViewController(withIdentifier: "PhotoViewController") as? PhotoViewController {
self.snapshotController = controller
addChildViewController(controller)
}
currentController = snapshotController!
view.insertSubview(currentController.view, at: 0)
let pan = UIPanGestureRecognizer(target: self, action: #selector(switchInputMode(_:)))
view.addGestureRecognizer(pan)
}
@objc func switchInputMode(_ sender: UIPanGestureRecognizer) {
guard sender.state == .began else {return}
let options: UIViewAnimationOptions
let translation = sender.translation(in: view)
if abs(translation.x) > abs(translation.y) {
if translation.x > 0 {
options = .transitionFlipFromLeft
} else {
options = .transitionFlipFromRight
}
} else {
if translation.y > 0 {
options = .transitionFlipFromBottom
} else {
options = .transitionFlipFromTop
}
}
let toController: UIViewController
if currentController == snapshotController {
toController = cameraController!
} else {
toController = snapshotController!
}
transition(from: currentController, to: toController, duration: 1, options: options, animations: { [unowned self] in
self.view.addSubview(toController.view)
self.currentController.view.removeFromSuperview()
}) { [unowned self] (success) in
if success {
self.currentController = toController
}
}
}
}
| mit | ad6af2b2622f49c989931d2930236148 | 31.133333 | 132 | 0.636929 | 5.738095 | false | false | false | false |
asm-products/cakebird | CakeBird/ProfileViewController.swift | 1 | 1168 | //
// ProfileViewController.swift
// CakeBird
//
// Created by Rhett Rogers on 8/23/14.
// Copyright (c) 2014 Lyokotech. All rights reserved.
//
import Foundation
import UIKit
class ProfileViewController : SuperViewController {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var handleLabel: UILabel!
@IBOutlet weak var tweetsLabel: UILabel!
@IBOutlet weak var followingLabel: UILabel!
@IBOutlet weak var followersLabel: UILabel!
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var bannerImage: UIImageView!
override func viewWillAppear(animated: Bool) {
if let user = UserManager.sharedInstance() {
nameLabel.text = user.name
handleLabel.text = user.handle
tweetsLabel.text = "Tweets: \(user.tweets!)"
followingLabel.text = "Following: \(user.following!)"
followersLabel.text = "Followers: \(user.followers!)"
// profileImage.image = user.profileImage!
// bannerImage.image = user.bannerImage!
} else {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
| agpl-3.0 | 756579d230bc2a6481d6798d360d2ae9 | 29.736842 | 69 | 0.65411 | 4.653386 | false | false | false | false |
GenerallyHelpfulSoftware/Scalar2D | SwiftUI/Sources/SVGPath+SwiftUI.swift | 1 | 3101 | //
// File.swift
//
//
// Created by Glenn Howes on 7/1/19.
//
//
// The MIT License (MIT)
// Copyright (c) 2016-2019 Generally Helpful Software
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
#if os(iOS) || os(tvOS) || os(OSX) || os(watchOS)
import Foundation
import CoreGraphics
import SwiftUI
import Scalar2D_GraphicPath
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public extension Path
{
/// create a SwiftUI Path element from a svg formatted string
/// https://www.w3.org/TR/SVG11/paths.html
/// For example, creating a half circle with a radius of 26:
/// private let cgPath = CGPath.path(fromSVGPath: "M 0 0 A 25 25 0 1 0 0 50Z")!
init?(svgPath: String)
{
guard let cgPath = CGPath.path(fromSVGPath: svgPath) else
{
return nil
}
self.init(cgPath)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public extension CGPath
{
/// Transform this CGPath to fit int the GeometryProxy's size. Will maintain aspect ratio
/// - Parameter geometry: geometry environment to fit into
func fitting(geometry : GeometryProxy) -> CGPath
{
let baseBox = self.boundingBoxOfPath
guard !baseBox.isEmpty && !baseBox.isInfinite && !baseBox.isNull else
{
return self
}
let nativeWidth = baseBox.width
let nativeHeight = baseBox.height
let nativeAspectRatio = nativeWidth/nativeHeight;
let boundedAspectRatio = geometry.size.width/geometry.size.height;
var scale : CGFloat!
if(nativeAspectRatio >= boundedAspectRatio) // blank space on top and bottom
{
scale = geometry.size.width / nativeWidth
}
else
{
scale = geometry.size.height / nativeHeight
}
var requiredTransform = CGAffineTransform(scaleX: scale, y: scale).translatedBy(x: -baseBox.minX*scale, y: -baseBox.minY*scale)
return self.copy(using: &requiredTransform) ?? self
}
}
#endif
| mit | 947eb37a1b856f7a9eb9e00768acc5fe | 34.643678 | 135 | 0.673976 | 4.091029 | false | false | false | false |
asm-products/cakebird | CakeBird/Tweet.swift | 1 | 1303 | //
// Tweet.swift
// CakeBird
//
// Created by Rhett Rogers on 8/23/14.
// Copyright (c) 2014 Lyokotech. All rights reserved.
//
import Foundation
import SwifteriOS
import UIKit
class Tweet {
var author: String?
var authorAvatar: UIImage?
var authorName: String?
var text: String?
var urls: [String]?
var retweetCount: String
// var replyCount: String
var favoriteCount: String
init(jsonTweet: JSON) {
text = Tweet.parseText(jsonTweet["text"].string!)
retweetCount = String(jsonTweet["retweet_count"].integer!)
favoriteCount = String(jsonTweet["favorite_count"].integer!)
var userId = jsonTweet["user"].object!["id_str"]!.string!
UserManager.Static.swifter?.getUsersLookupWithUserIDs([userId], includeEntities: true, success: { (users) -> Void in
let user = users![0]
self.author = "@".stringByAppendingString(user["screen_name"].string!)
// self.authorAvatar =
// user["profile_image_url"].string!
self.authorName = user["name"].string!
}, failure: { (error) -> Void in
println(error)
})
println(userId)
}
class func parseText(text: String) -> String {
var returnText = text.stringByReplacingOccurrencesOfString("<", withString: "<", options: nil, range: nil)
return returnText
}
} | agpl-3.0 | 94ee96a3f51b5c08d192d574faaae22a | 26.744681 | 120 | 0.669225 | 3.821114 | false | false | false | false |
AboutObjectsTraining/swift-comp-reston-2017-02 | examples/swift-tool/Tuples.playground/Contents.swift | 1 | 2539 | import UIKit
// Tuples
let vals = (12, "Hi")
print(vals.0)
print(vals.1)
let explicitlyTypedVals: (Int, String) = (12, "Hi")
let vals2 = (x: 12, y: "Hi")
print(vals2.x)
print(vals2.y)
func area(size: (width: Int, height: Int)) -> Int
{
return size.width * size.height
}
func discount1(originalPrice: Double, percentage: Double) -> (Double, Double)
{
let amount = originalPrice * percentage
let price = originalPrice - amount
return (price, amount)
}
let newPrice1: (Double, Double) = discount1(25.00, percentage: 0.15)
func discount2(originalPrice: Double, percentage: Double)
-> (price: Double, discount: Double)
{
let amount = originalPrice * percentage
let price = originalPrice - amount
return (price, amount)
}
let newPrice2: (Double, Double) = discount2(19.95, percentage: 0.15)
discount2(19.95, percentage: 0.15).price
discount2(19.95, percentage: 0.15).discount
let newPrice3: (Double, Double) = discount2(19.95, percentage: 0.15)
let (price, discount) = discount2(19.95, percentage: 0.15)
print(price)
print(discount)
let (discountedPrice, _) = discount2(19.95, percentage: 0.15)
print(discountedPrice)
extension Double
{
var currencyString: String {
return String(format: "%.2f", self)
}
}
price.currencyString
let names = [ "Jane", "Bill", "Jan", "Pat" ]
for (index, value) in names.enumerate()
{
print("name \(index + 1) is \(value)")
}
// Empty Tuple and Void
func sayHello(_: Void) -> Void
{
print("Hello")
}
func say2(_: ()) -> ()
{
print("Hello")
}
func say3()
{
print("Hello")
}
// Switch Statement Pattern Matching
func matchMyTuple(myTuple: (Int?, Int, Int?))
{
switch myTuple
{
case (.Some, 99, .None):
print ("Matched first case: \(myTuple)")
case (.Some, _, .None):
print ("Matched second case: \(myTuple)")
case (.Some, _, .Some):
print ("Matched third case: \(myTuple)")
case (.None, _, .Some):
print ("Matched fourth case: \(myTuple)")
case (.None, _, .None):
print ("Matched fifth case: \(myTuple)")
}
}
matchMyTuple((Int("1"), 99, nil))
matchMyTuple((Int("1"), 42, nil))
matchMyTuple((Int("1"), 42, Int("2")))
matchMyTuple((nil, 42, nil))
matchMyTuple((nil, 42, Int("2")))
//let x: Int? = 42
//let y = 99
//let z: Int? = nil
//
//var myTuple = (x: x, y: y, z: z)
//matchMyTuple(myTuple)
//
//myTuple.x = nil
//matchMyTuple(myTuple)
//
//myTuple.x = 42
//myTuple.y = 100
//matchMyTuple(myTuple)
//
//myTuple.z = 1
//matchMyTuple(myTuple)
| mit | da0a93044351d64db91cd728ac7adffb | 18.530769 | 77 | 0.623868 | 3.044365 | false | false | false | false |
Rostmen/TimelineController | RZTimelineCollection/RZPostCollectionViewCell.swift | 1 | 10635 | //
// RZPostCollectionViewCell.swift
// RZTimelineCollection
//
// Created by Rostyslav Kobizsky on 12/18/14.
// Copyright (c) 2014 Rozdoum. All rights reserved.
//
import UIKit
@objc protocol RZPostCollectionViewCellDelegate {
optional func postCollectionViewCellDidTapAvatar(cell: RZPostCollectionViewCell)
optional func postCollectionViewCellDidTapContent(cell: RZPostCollectionViewCell)
optional func postCollectionViewCellDidTapCell(cell: RZPostCollectionViewCell, atPoint point: CGPoint)
}
class RZPostCollectionViewCell: UICollectionViewCell {
weak var delegate: RZPostCollectionViewCellDelegate?
/**
* Returns the label that is pinned to the top of the cell.
* This label is most commonly used to display message timestamps.
*/
@IBOutlet weak var cellTopLabel: RZPostLabel!
/**
* Returns the label that is pinned to the bottom of the cell.
* This label is most commonly used to display message delivery status.
*/
@IBOutlet weak var cellBottomLabel: RZPostLabel!
/**
* Returns the text view of the cell. This text view contains the message body text.
*
* @warning If mediaView returns a non-nil view, then this value will be `nil`.
*/
@IBOutlet weak var textView: RZPostCellTextView!
/**
* Returns the background image view of the cell that is responsible for displaying post background images.
*
* @warning If mediaView returns a non-nil view, then this value will be `nil`.
*/
@IBOutlet weak var postBackgroundImageView: UIImageView!
/**
* Returns the post container view of the cell. This view is the superview of
* the cell's textView and messageBubbleImageView.
*
* @discussion You may customize the cell by adding custom views to this container view.
* To do so, override `collectionView:cellForItemAtIndexPath:`
*
* @warning You should not try to manipulate any properties of this view, for example adjusting
* its frame, nor should you remove this view from the cell or remove any of its subviews.
* Doing so could result in unexpected behavior.
*/
@IBOutlet weak var postContainerView: UIView!
/**
* Returns the avatar image view of the cell that is responsible for displaying avatar images.
*/
@IBOutlet weak var avatarImageView: UIImageView!
/**
* Returns the avatar container view of the cell. This view is the superview of
* the cell's avatarImageView.
*
* @discussion You may customize the cell by adding custom views to this container view.
* To do so, override `collectionView:cellForItemAtIndexPath:`
*
* @warning You should not try to manipulate any properties of this view, for example adjusting
* its frame, nor should you remove this view from the cell or remove any of its subviews.
* Doing so could result in unexpected behavior.
*/
@IBOutlet weak var avatarContainerView: UIView!
@IBOutlet private weak var postContainerWidthConstraint: NSLayoutConstraint!
@IBOutlet private weak var textViewTopVerticalSpaceConstraint: NSLayoutConstraint!
@IBOutlet private weak var textViewBottomVerticalSpaceConstraint: NSLayoutConstraint!
@IBOutlet private weak var textViewAvatarHorizontalSpaceConstraint: NSLayoutConstraint!
@IBOutlet private weak var textViewMarginHorizontalSpaceConstraint: NSLayoutConstraint!
@IBOutlet private weak var cellTopLabelHeightConstraint: NSLayoutConstraint!
@IBOutlet private weak var cellBottomLabelHeightConstraint: NSLayoutConstraint!
@IBOutlet private weak var avatarContainerViewWidthConstraint: NSLayoutConstraint!
@IBOutlet private weak var avatarContainerViewHeightConstraint: NSLayoutConstraint!
private var textViewFrameInsets: UIEdgeInsets {
set(newValue) {
if UIEdgeInsetsEqualToEdgeInsets(textViewFrameInsets, newValue) {
rz_updateConstraint(textViewTopVerticalSpaceConstraint, withConstant: newValue.top)
rz_updateConstraint(textViewBottomVerticalSpaceConstraint, withConstant: newValue.bottom)
rz_updateConstraint(textViewMarginHorizontalSpaceConstraint, withConstant: newValue.left)
rz_updateConstraint(textViewAvatarHorizontalSpaceConstraint, withConstant: newValue.right)
}
}
get {
return UIEdgeInsetsMake(
textViewTopVerticalSpaceConstraint.constant,
textViewMarginHorizontalSpaceConstraint.constant,
textViewBottomVerticalSpaceConstraint.constant,
textViewAvatarHorizontalSpaceConstraint.constant
)
}
}
private var avatarViewSize: CGSize {
set(newValue) {
if (!CGSizeEqualToSize(avatarViewSize, newValue)) {
rz_updateConstraint(avatarContainerViewWidthConstraint, withConstant: newValue.width)
rz_updateConstraint(avatarContainerViewHeightConstraint, withConstant: newValue.height)
}
}
get {
return CGSize(width: avatarContainerViewWidthConstraint.constant, height: avatarContainerViewHeightConstraint.constant)
}
}
weak var mediaView: UIView? {
willSet {
if (newValue != mediaView && newValue != nil) {
postBackgroundImageView.removeFromSuperview()
textView.removeFromSuperview()
newValue!.setTranslatesAutoresizingMaskIntoConstraints(true)
newValue!.frame = postContainerView.bounds
postContainerView.addSubview(newValue!)
postContainerView.rz_pinAllEdgesOfSubview(newValue!)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
for index in 0..<self.postContainerView.subviews.count {
if (self.postContainerView.subviews[index] as? UIView) != newValue {
(self.postContainerView.subviews[index] as? UIView)?.removeFromSuperview()
}
}
})
}
}
}
var tapGestureRecognizer: UITapGestureRecognizer!
override var bounds: CGRect {
didSet {
if UIDevice.rz_isCurrentDeviceBeforeiOS8() {
contentView.frame = bounds
}
}
}
override var selected: Bool {
didSet {
postBackgroundImageView.highlighted = selected
}
}
override var highlighted: Bool {
didSet {
postBackgroundImageView.highlighted = highlighted
}
}
override var backgroundColor: UIColor? {
didSet {
cellTopLabel.backgroundColor = backgroundColor
cellBottomLabel.backgroundColor = backgroundColor
postBackgroundImageView.backgroundColor = backgroundColor
postContainerView.backgroundColor = backgroundColor
avatarImageView.backgroundColor = backgroundColor
avatarContainerView.backgroundColor = backgroundColor
}
}
// MARK: Methods
class func nib() -> UINib {
return UINib(nibName: "RZPostCollectionViewCell", bundle: NSBundle.mainBundle())
}
class func cellReuseIdentifier() -> String {
return "RZPostCollectionViewCell"
}
class func mediaCellReuseIdentifier() -> String {
return cellReuseIdentifier() + "_RZMedia"
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = UIColor.clearColor()
avatarViewSize = CGSizeZero
cellTopLabelHeightConstraint.constant = 0
cellBottomLabelHeightConstraint.constant = 0
cellTopLabel.textAlignment = NSTextAlignment.Center
cellTopLabel.font = UIFont.boldSystemFontOfSize(12)
cellTopLabel.textColor = UIColor.lightGrayColor()
cellBottomLabel.font = UIFont.systemFontOfSize(12)
cellBottomLabel.textColor = UIColor.lightGrayColor()
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTapGesture:")
self.addGestureRecognizer(tapGestureRecognizer)
}
override func prepareForReuse() {
super.prepareForReuse()
cellTopLabel.text = nil
cellBottomLabel.text = nil
textView.dataDetectorTypes = UIDataDetectorTypes.None
textView.text = nil
textView.attributedText = nil
avatarImageView.image = nil
avatarImageView.highlightedImage = nil
}
override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes) {
super.applyLayoutAttributes(layoutAttributes)
let customAttributes = (layoutAttributes as RZPostCollectionViewLayoutAttribures)
if (textView.font != customAttributes.postFont) {
textView.font = customAttributes.postFont
}
if !UIEdgeInsetsEqualToEdgeInsets(textView.textContainerInset, customAttributes.textViewTextContainerInsets) {
textView.textContainerInset = customAttributes.textViewTextContainerInsets
}
textViewFrameInsets = customAttributes.textViewFrameInsets
rz_updateConstraint(postContainerWidthConstraint, withConstant: customAttributes.postContainerViewWidth)
rz_updateConstraint(cellTopLabelHeightConstraint, withConstant: customAttributes.cellTopLabelHeight)
rz_updateConstraint(cellBottomLabelHeightConstraint, withConstant: customAttributes.cellBottomLabelHeight)
avatarViewSize = customAttributes.avatarViewSize
}
func rz_updateConstraint(constraint: NSLayoutConstraint, withConstant constant: CGFloat) {
if constraint.constant == constant {
return
}
constraint.constant = constant
}
func handleTapGesture(sender: UITapGestureRecognizer) {
let location = sender.locationInView(self)
if CGRectContainsPoint(avatarContainerView.frame, location) {
delegate?.postCollectionViewCellDidTapAvatar?(self)
} else if CGRectContainsPoint(postContainerView.frame, location) {
delegate?.postCollectionViewCellDidTapContent?(self)
} else {
delegate?.postCollectionViewCellDidTapCell?(self, atPoint: location)
}
}
}
| apache-2.0 | d36db273fd6997c3a322f9c1ef07faf3 | 38.535316 | 131 | 0.679079 | 5.836992 | false | false | false | false |
dokun1/Lumina | Sources/Lumina/UI/LuminaTextPromptView.swift | 1 | 3048 | //
// LuminaTextPromptView.swift
// Lumina
//
// Created by David Okun on 5/7/17.
// Copyright © 2017 David Okun. All rights reserved.
//
import UIKit
enum LuminaTextError: Error {
case fontError
}
extension UIFont {
static func fontsURLs() -> [URL]? {
let bundle = Bundle(identifier: "com.okun.io.Lumina")
let fileNames = ["IBMPlexSans-SemiBold"]
let newNames = fileNames.map({ bundle?.url(forResource: $0, withExtension: "ttf") })
return newNames as? [URL]
}
static func register(from url: URL) throws {
guard let fontDataProvider = CGDataProvider(url: url as CFURL) else {
throw LuminaTextError.fontError
}
guard let font = CGFont(fontDataProvider) else {
throw LuminaTextError.fontError
}
var error: Unmanaged<CFError>?
guard CTFontManagerRegisterGraphicsFont(font, &error) else {
throw error!.takeUnretainedValue()
}
}
}
final class LuminaTextPromptView: UIView {
private var textLabel = UILabel()
static private let animationDuration = 0.3
init() {
super.init(frame: CGRect.zero)
self.textLabel = UILabel()
self.textLabel.backgroundColor = UIColor.clear
self.textLabel.textColor = UIColor.white
self.textLabel.textAlignment = .center
do {
if let fonts = UIFont.fontsURLs() {
try fonts.forEach { try UIFont.register(from: $0) }
}
} catch {
LuminaLogger.debug(message: "Special fonts already registered")
}
if let font = UIFont(name: "IBM Plex Sans", size: 22) {
self.textLabel.font = font
} else {
self.textLabel.font = UIFont.systemFont(ofSize: 22, weight: .bold)
}
self.textLabel.numberOfLines = 3
self.textLabel.minimumScaleFactor = 10/UIFont.labelFontSize
self.textLabel.adjustsFontSizeToFitWidth = true
self.textLabel.layer.shadowOffset = CGSize(width: 0, height: 0)
self.textLabel.layer.shadowOpacity = 1
self.textLabel.layer.shadowRadius = 6
self.addSubview(textLabel)
self.backgroundColor = UIColor.clear
self.alpha = 0.0
self.layer.cornerRadius = 5.0
}
func updateText(to text: String) {
DispatchQueue.main.async {
if text.isEmpty {
self.hide(andErase: true)
} else {
self.textLabel.text = text
self.makeAppear()
}
}
}
func hide(andErase: Bool) {
DispatchQueue.main.async {
UIView.animate(withDuration: LuminaTextPromptView.animationDuration, animations: {
self.alpha = 0.0
}, completion: { _ in
if andErase {
self.textLabel.text = ""
}
})
}
}
private func makeAppear() {
DispatchQueue.main.async {
UIView.animate(withDuration: LuminaTextPromptView.animationDuration) {
self.alpha = 1
}
}
}
override func layoutSubviews() {
self.textLabel.frame = CGRect(origin: CGPoint(x: 5, y: 5), size: CGSize(width: frame.width - 10, height: frame.height - 10))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | e74a69b4f9990eac9cb0905717a5321a | 26.7 | 128 | 0.659009 | 3.983007 | false | false | false | false |
Yalantis/ColorMatchTabs | Example/Example/Classes/ViewControllers/ExampleViewContoller.swift | 1 | 2033 | //
// ExampleViewContoller.swift
// ColorMatchTabs
//
// Created by Serhii Butenko on 26/6/16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import UIKit
import ColorMatchTabs
class ExampleViewContoller: ColorMatchTabsViewController {
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.font = UIFont.navigationTitleFont()
// to hide bottom button remove the following line
popoverViewController = ExamplePopoverViewController()
popoverViewController?.modalPresentationStyle = .fullScreen
popoverViewController?.delegate = self
colorMatchTabDataSource = self
}
}
extension ExampleViewContoller: ColorMatchTabsViewControllerDataSource {
func numberOfItems(inController controller: ColorMatchTabsViewController) -> Int {
return TabItemsProvider.items.count
}
func tabsViewController(_ controller: ColorMatchTabsViewController, viewControllerAt index: Int) -> UIViewController {
return StubContentViewControllersProvider.viewControllers[index]
}
func tabsViewController(_ controller: ColorMatchTabsViewController, titleAt index: Int) -> String {
return TabItemsProvider.items[index].title
}
func tabsViewController(_ controller: ColorMatchTabsViewController, iconAt index: Int) -> UIImage {
return TabItemsProvider.items[index].normalImage
}
func tabsViewController(_ controller: ColorMatchTabsViewController, hightlightedIconAt index: Int) -> UIImage {
return TabItemsProvider.items[index].highlightedImage
}
func tabsViewController(_ controller: ColorMatchTabsViewController, tintColorAt index: Int) -> UIColor {
return TabItemsProvider.items[index].tintColor
}
}
extension ExampleViewContoller: PopoverViewControllerDelegate {
func popoverViewController(_ popoverViewController: PopoverViewController, didSelectItemAt index: Int) {
selectItem(at: index)
}
}
| mit | 3d85992e0f8e43f4c1e1cadde41a0883 | 31.774194 | 122 | 0.725394 | 5.404255 | false | false | false | false |
OHeroJ/twicebook | Sources/App/Models/User.swift | 1 | 3961 | //
// User.swift
// seesometop
//
// Created by laijihua on 28/08/2017.
//
//
import Foundation
import Vapor
import FluentProvider
final class User: Model{
let storage: Storage = Storage()
var email: String
var name: String
var avator: String
var info: String
var password: String
var reportCount: Int
var createTime: String
var isFriend: Bool = false
var wxSign: String = ""
var wxNumber: String = ""
struct Key {
static let email = "email"
static let name = "name"
static let avator = "avator"
static let info = "info"
static let password = "password"
static let id = "id"
static let reportCount = "report_count"
static let createTime = "create_time"
static let isFriend = "is_friend"
static let active = "active"
static let wxSign = "wx_sign"
static let wxNumber = "wx_number"
}
init(email: String,
password: String,
name:String,
avator: String = "",
info:String = "" ) {
self.email = email
self.password = password
self.name = name
self.avator = avator
self.info = info
self.reportCount = 0
self.createTime = Date().toString
}
init(row: Row) throws {
email = try row.get(Key.email)
name = try row.get(Key.name)
avator = try row.get(Key.avator)
info = try row.get(Key.info)
password = try row.get(Key.password)
reportCount = try row.get(Key.reportCount)
createTime = try row.get(Key.createTime)
wxSign = try row.get(Key.wxSign)
wxNumber = try row.get(Key.wxNumber)
}
func makeRow() throws -> Row {
var row = Row()
try row.set(Key.email, email)
try row.set(Key.name, name)
try row.set(Key.avator, avator)
try row.set(Key.info, info)
try row.set(Key.password, password)
try row.set(Key.reportCount, reportCount)
try row.set(Key.createTime, createTime)
try row.set(Key.wxSign, wxSign)
try row.set(Key.wxNumber, wxNumber)
return row
}
}
extension User: JSONRepresentable {
func makeJSON() throws -> JSON {
let isActive = try activeCode()?.state ?? false
var json = JSON()
try json.set(Key.id, id)
try json.set(Key.email, email)
try json.set(Key.avator, avator)
try json.set(Key.info, info)
try json.set(Key.name, name)
try json.set(Key.active, isActive)
try json.set(Key.reportCount, reportCount)
try json.set(Key.createTime, createTime)
try json.set(Key.isFriend, isFriend)
try json.set(Key.wxNumber, Key.wxNumber)
return json
}
}
extension User {
// 激活码
func activeCode() throws -> UserActicode? {
return try children(type: UserActicode.self, foreignIdKey: UserActicode.Key.userId).first()
}
func userToken() throws -> UserToken? {
return try children(type: UserToken.self, foreignIdKey: UserToken.Key.userId).first()
}
/// 收藏的书籍
var collectBooks: Siblings<User, Book, Collect> {
return siblings()
}
/// 创建的书籍
func createBooks() throws -> [Book] {
return try children(type: Book.self, foreignIdKey: Book.Key.createId).all()
}
}
extension User: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self, closure: { (builder) in
builder.id()
builder.string(Key.email)
builder.string(Key.name)
builder.string(Key.avator)
builder.string(Key.info, length: 1024)
builder.string(Key.password)
builder.int(Key.reportCount)
builder.string(Key.createTime)
})
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
| mit | 28050025cf289aa086036d554c7fcd12 | 26.907801 | 99 | 0.593393 | 3.816683 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS | Aztec/Classes/TextKit/ParagraphProperty/Header.swift | 2 | 2604 | import Foundation
import UIKit
// MARK: - Header property for paragraphs
//
open class Header: ParagraphProperty {
// MARK: - Nested Types
/// Available Heading Types
///
public enum HeaderType: Int {
case none = 0
case h1 = 1
case h2 = 2
case h3 = 3
case h4 = 4
case h5 = 5
case h6 = 6
public static var fontSizeMap: [HeaderType: Float] = {
return [
.h1: 24,
.h2: 22,
.h3: 20,
.h4: 18,
.h5: 16,
.h6: 14,
.none: Constants.defaultFontSize
]
}()
public var fontSize: Float {
let fontSize = HeaderType.fontSizeMap[self] ?? Constants.defaultFontSize
return Float(UIFontMetrics.default.scaledValue(for: CGFloat(fontSize)))
}
}
// MARK: - Properties
/// Kind of Header: Header 1, Header 2, etc..
///
let level: HeaderType
/// Default Font Size (corresponding to HeaderType.none)
///
let defaultFontSize: Float
// MARK: - Initializers
init(level: HeaderType, with representation: HTMLRepresentation? = nil, defaultFontSize: Float? = nil) {
self.defaultFontSize = defaultFontSize ?? Constants.defaultFontSize
self.level = level
super.init(with: representation)
}
public required init?(coder aDecoder: NSCoder) {
if aDecoder.containsValue(forKey: Keys.level),
let decodedLevel = HeaderType(rawValue: aDecoder.decodeInteger(forKey: Keys.level))
{
level = decodedLevel
} else {
level = .none
}
if aDecoder.containsValue(forKey: Keys.level) {
defaultFontSize = aDecoder.decodeFloat(forKey: Keys.defaultFontSize)
} else {
defaultFontSize = Constants.defaultFontSize
}
super.init(coder: aDecoder)
}
// MARK: - NSCoder
public override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
aCoder.encode(defaultFontSize, forKey: Keys.defaultFontSize)
aCoder.encode(level.rawValue, forKey: Keys.level)
}
static func ==(lhs: Header, rhs: Header) -> Bool {
return lhs.level == rhs.level
}
}
// MARK: - Private Helpers
//
private extension Header {
struct Constants {
static let defaultFontSize = Float(16)
}
struct Keys {
static let defaultFontSize = "defaultFontSize"
static let level = String(describing: HeaderType.self)
}
}
| mpl-2.0 | 539f05a50520d431574b8ea6a036262a | 24.281553 | 108 | 0.576037 | 4.512998 | false | false | false | false |
jdkelley/Udacity-OnTheMap-ExampleApps | TheMovieManager-v2/TheMovieManager/MoviePickerViewController.swift | 1 | 4535 | //
// MoviePickerTableView.swift
// TheMovieManager
//
// Created by Jarrod Parkes on 2/11/15.
// Copyright (c) 2015 Jarrod Parkes. All rights reserved.
//
import UIKit
// MARK: - MoviePickerViewControllerDelegate
protocol MoviePickerViewControllerDelegate {
func moviePicker(moviePicker: MoviePickerViewController, didPickMovie movie: TMDBMovie?)
}
// MARK: - MoviePickerViewController: UIViewController
class MoviePickerViewController: UIViewController {
// MARK: Properties
// the data for the table
var movies = [TMDBMovie]()
// the delegate will typically be a view controller, waiting for the Movie Picker to return an movie
var delegate: MoviePickerViewControllerDelegate?
// the most recent data download task. We keep a reference to it so that it can be canceled every time the search text changes
var searchTask: NSURLSessionDataTask?
// MARK: Outlets
@IBOutlet weak var movieTableView: UITableView!
@IBOutlet weak var movieSearchBar: UISearchBar!
// MARK: Life Cycle
override func viewDidLoad() {
parentViewController!.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Reply, target: self, action: #selector(logout))
// configure tap recognizer
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap(_:)))
tapRecognizer.numberOfTapsRequired = 1
tapRecognizer.delegate = self
view.addGestureRecognizer(tapRecognizer)
}
// MARK: Dismissals
func handleSingleTap(recognizer: UITapGestureRecognizer) {
view.endEditing(true)
}
private func cancel() {
delegate?.moviePicker(self, didPickMovie: nil)
logout()
}
func logout() {
dismissViewControllerAnimated(true, completion: nil)
}
}
// MARK: - MoviePickerViewController: UIGestureRecognizerDelegate
extension MoviePickerViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
return movieSearchBar.isFirstResponder()
}
}
// MARK: - MoviePickerViewController: UISearchBarDelegate
extension MoviePickerViewController: UISearchBarDelegate {
// each time the search text changes we want to cancel any current download and start a new one
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
// cancel the last task
if let task = searchTask {
task.cancel()
}
// if the text is empty we are done
if searchText == "" {
movies = [TMDBMovie]()
movieTableView?.reloadData()
return
}
// new search
searchTask = TMDBClient.sharedInstance().getMoviesForSearchString(searchText) { (movies, error) in
self.searchTask = nil
if let movies = movies {
self.movies = movies
performUIUpdatesOnMain {
self.movieTableView!.reloadData()
}
}
}
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
}
// MARK: - MoviePickerViewController: UITableViewDelegate, UITableViewDataSource
extension MoviePickerViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellReuseId = "MovieSearchCell"
let movie = movies[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(CellReuseId) as UITableViewCell!
if let releaseYear = movie.releaseYear {
cell.textLabel!.text = "\(movie.title) (\(releaseYear))"
} else {
cell.textLabel!.text = "\(movie.title)"
}
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let movie = movies[indexPath.row]
let controller = storyboard!.instantiateViewControllerWithIdentifier("MovieDetailViewController") as! MovieDetailViewController
controller.movie = movie
navigationController!.pushViewController(controller, animated: true)
}
}
| mit | d8c5315cc2066f3124e4e20c524002c8 | 31.862319 | 150 | 0.672988 | 5.682957 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformKit/BuySellKit/Analytics/NewAnalyticsEvents+Deposit.swift | 1 | 903 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import Foundation
extension AnalyticsEvents.New {
public enum Deposit: AnalyticsEvent {
public var type: AnalyticsEventType { .nabu }
case depositClicked(origin: Origin = .currencyPage)
case depositViewed
case depositAmountEntered(
amount: Double,
currency: String,
depositMethod: Method
)
case depositMethodSelected(
currency: String,
depositMethod: Method
)
public enum Method: String, StringRawRepresentable {
case bankTransfer = "BANK_TRANSFER"
case bankAccount = "BANK_ACCOUNT"
}
public enum Origin: String, StringRawRepresentable {
case currencyPage = "CURRENCY_PAGE"
case portfolio = "PORTFOLIO"
}
}
}
| lgpl-3.0 | f5363be39ba96622e0fcc3e2333813ea | 26.333333 | 62 | 0.613082 | 5.067416 | false | false | false | false |
dobleuber/my-swift-exercises | Challenge7/Challenge7/ViewController.swift | 1 | 2284 | //
// ViewController.swift
// Challenge7
//
// Created by Wbert Castro on 26/07/17.
// Copyright © 2017 Wbert Castro. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
var notes = [Note]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(newNote))
let defaults = UserDefaults.standard
if let savedNotes = defaults.object(forKey: "notes") as? Data {
notes = NSKeyedUnarchiver.unarchiveObject(with: savedNotes) as! [Note]
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "note", for: indexPath)
cell.textLabel!.text = notes[indexPath.row].title
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
vc.note = notes[indexPath.row].text
vc.rowIndex = indexPath.row
navigationController?.pushViewController(vc, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func newNote() {
notes.insert(Note("New note"), at: 0)
let indexPath = IndexPath(row: 0, section: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
tableView(tableView, didSelectRowAt: indexPath)
}
func saveNote(_ note: String, at index: Int) {
notes[index].text = note
saveNotes()
}
func deleteNote(at index: Int) {
notes.remove(at: index)
saveNotes()
}
func saveNotes() {
let savedData = NSKeyedArchiver.archivedData(withRootObject: notes)
UserDefaults.standard.set(savedData, forKey: "notes")
tableView.reloadData()
}
}
| mit | f723587995d41ae38ffc984027f0b10b | 29.44 | 127 | 0.631187 | 4.952278 | false | false | false | false |
jovito-royeca/ManaKit | Example/ManaKit/Maintainer/Maintainer+TCGPlayer.swift | 1 | 6666 | //
// Maintainer+TCGPlayer.swift
// ManaKit_Example
//
// Created by Jovito Royeca on 23/10/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
import ManaKit
import PostgresClientKit
import PromiseKit
extension Maintainer {
func getTcgPlayerToken() -> Promise<Void> {
return Promise { seal in
guard let urlString = "https://api.tcgplayer.com/token".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let url = URL(string: urlString) else {
fatalError("Malformed url")
}
let query = "grant_type=client_credentials&client_id=\(ManaKit.Constants.TcgPlayerPublicKey)&client_secret=\(ManaKit.Constants.TcgPlayerPrivateKey)"
var rq = URLRequest(url: url)
rq.httpMethod = "POST"
rq.setValue("application/json", forHTTPHeaderField: "Content-Type")
rq.httpBody = query.data(using: .utf8)
firstly {
URLSession.shared.dataTask(.promise, with: rq)
}.compactMap {
try JSONSerialization.jsonObject(with: $0.data) as? [String: Any]
}.done { json in
guard let token = json["access_token"] as? String else {
fatalError("access_token is nil")
}
self.tcgplayerAPIToken = token
seal.fulfill(())
}.catch { error in
print("\(error)")
seal.reject(error)
}
}
}
func fetchSets() -> Promise<[Int32]> {
return Promise { seal in
setsModel.predicate = NSPredicate(format: "tcgplayerId > 0")
firstly {
setsModel.fetchRemoteData()
}.compactMap { (data, result) in
try JSONSerialization.jsonObject(with: data) as? [[String: Any]]
}.then { data in
self.setsModel.saveLocalData(data: data)
}.then {
self.setsModel.fetchLocalData()
}.done {
var tcgplayerIds = [Int32]()
try! self.setsModel.getFetchedResultsController(with: self.setsModel.fetchRequest).performFetch()
if let sets = self.setsModel.allObjects() as? [MGSet] {
tcgplayerIds = sets.map( { set in
set.tcgplayerId
})
}
seal.fulfill(tcgplayerIds)
}.catch { error in
self.setsModel.deleteCache()
seal.reject(error)
}
}
}
func createStorePromise(name: String, connection: Connection) -> Promise<Void> {
let nameSection = self.sectionFor(name: name) ?? "NULL"
let query = "SELECT createOrUpdateStore($1,$2)"
let parameters = [name,
nameSection]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func fetchTcgPlayerCardPricing(groupIds: [Int32], connection: Connection) -> Promise<[()->Promise<Void>]> {
return Promise { seal in
var array = [Promise<[()->Promise<Void>]>]()
var promises = [()->Promise<Void>]()
for groupId in groupIds {
array.append(fetchCardPricingBy(groupId: groupId,
connection: connection))
}
firstly {
when(fulfilled: array)
}.done { results in
for result in results {
promises.append(contentsOf: result)
}
seal.fulfill(promises)
}.catch { error in
seal.reject(error)
}
}
}
func fetchCardPricingBy(groupId: Int32, connection: Connection) -> Promise<[()->Promise<Void>]> {
return Promise { seal in
guard let urlString = "https://api.tcgplayer.com/\(ManaKit.Constants.TcgPlayerApiVersion)/pricing/group/\(groupId)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let url = URL(string: urlString) else {
fatalError("Malformed url")
}
var rq = URLRequest(url: url)
rq.httpMethod = "GET"
rq.setValue("application/json", forHTTPHeaderField: "Content-Type")
rq.setValue("Bearer \(tcgplayerAPIToken)", forHTTPHeaderField: "Authorization")
firstly {
URLSession.shared.dataTask(.promise, with:rq)
}.compactMap {
try JSONSerialization.jsonObject(with: $0.data) as? [String: Any]
}.done { json in
guard let results = json["results"] as? [[String: Any]] else {
fatalError("results is nil")
}
var promises = [()->Promise<Void>]()
for result in results {
promises.append({
return self.createCardPricingPromise(price: result,
connection: connection)
})
}
seal.fulfill(promises)
}.catch { error in
print(error)
seal.reject(error)
}
}
}
func createCardPricingPromise(price: [String: Any], connection: Connection) -> Promise<Void> {
let low = price["lowPrice"] as? Double ?? 0.0
let median = price["midPrice"] as? Double ?? 0.0
let high = price["highPrice"] as? Double ?? 0.0
let market = price["marketPrice"] as? Double ?? 0.0
let directLow = price["directLowPrice"] as? Double ?? 0.0
let tcgPlayerId = price["productId"] as? Int ?? 0
let cmstore = self.storeName
let isFoil = price["subTypeName"] as? String ?? "Foil" == "Foil" ? true : false
let query = "SELECT createOrUpdateCardPrice($1,$2,$3,$4,$5,$6,$7,$8)"
let parameters = [
low,
median,
high,
market,
directLow,
tcgPlayerId,
cmstore,
isFoil
] as [Any]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
}
| mit | 0993498e495bb3b93a28672c727121fa | 37.085714 | 191 | 0.501125 | 5.003754 | false | false | false | false |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeCore/AwesomeCore/Classes/NetworkServices/MVAnalyticsRegisterDeviceNS.swift | 1 | 1264 | //
// MVAnalyticsRegisterDeviceNS.swift
// Pods
//
// Created by Leonardo Vinicius Kaminski Ferreira on 18/03/19.
//
import Foundation
class MVAnalyticsRegisterDeviceNS: BaseNS {
static let shared = MVAnalyticsRegisterDeviceNS()
lazy var requester: AwesomeCoreRequester = AwesomeCoreRequester(cacheType: .realm)
override init() {}
func register(_ register: MVAnalyticsRegisterDevice, params: AwesomeCoreNetworkServiceParams, _ response:@escaping (MVAnalyticsIdentifyStatus?, ErrorData?) -> Void) {
_ = requester.performRequestAuthorized(
ACConstants.shared.mvAnalyticsRegisterURL, headersParam: ACConstants.shared.analyticsHeadersMV, method: .POST, jsonBody: register.encoded, completion: { (data, error, responseType) in
guard let data = data else {
response(nil, nil)
return
}
if let error = error {
print("Error fetching from API: \(error.message)")
response(nil, error)
return
}
let status = MVAnalyticsIdentifyStatusMP.parse(data)
response(status, nil)
})
}
}
| mit | 0b2c3e375aa2229e748cbcfabe08d4c7 | 34.111111 | 195 | 0.601266 | 5.076305 | false | false | false | false |
fthomasmorel/insapp-iOS | Insapp/AssociationViewController.swift | 1 | 11209 | //
// AssociationViewController.swift
// Insapp
//
// Created by Florent THOMAS-MOREL on 9/13/16.
// Copyright © 2016 Florent THOMAS-MOREL. All rights reserved.
//
import Foundation
import UIKit
class AssociationViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, AssociationPostsDelegate, AssociationEventsDelegate {
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var associationNameLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var coverImageView: UIImageView!
@IBOutlet weak var blurCoverView: UIVisualEffectView!
var association: Association!
var events:[Event] = []
var posts:[Post] = []
var hasLoaded = false
let downloadGroup = DispatchGroup()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.separatorStyle = .none
self.tableView.tableFooterView = UIView()
self.tableView.register(UINib(nibName: "AssociationHeaderCell", bundle: nil), forCellReuseIdentifier: kAssociationHeaderCell)
self.tableView.register(UINib(nibName: "AssociationPostsCell", bundle: nil), forCellReuseIdentifier: kAssociationPostsCell)
self.tableView.register(UINib(nibName: "AssociationEventsCell", bundle: nil), forCellReuseIdentifier: kAssociationEventsCell)
self.tableView.register(UINib(nibName: "AssociationDescriptionCell", bundle: nil), forCellReuseIdentifier: kAssociationDescriptionCell)
self.tableView.register(UINib(nibName: "AssociationContactCell", bundle: nil), forCellReuseIdentifier: kAssociationContactCell)
self.tableView.register(UINib(nibName: "LoadingCell", bundle: nil), forCellReuseIdentifier: kLoadingCell)
self.coverImageView.downloadedFrom(link: kCDNHostname + self.association.coverPhotoURL!)
self.profileImageView.downloadedFrom(link: kCDNHostname + self.association.profilePhotoURL!)
self.profileImageView.layer.cornerRadius = 50
self.profileImageView.layer.masksToBounds = true
self.associationNameLabel.text = "@"+self.association.name!
self.associationNameLabel.alpha = 0
self.blurCoverView.alpha = 0
}
override func viewWillAppear(_ animated: Bool) {
self.hideNavBar()
self.notifyGoogleAnalytics()
self.tableView.backgroundColor = UIColor.hexToRGB(self.association.bgColor!)
if self.association.fgColor! == "ffffff" {
self.backButton.setImage(#imageLiteral(resourceName: "arrow_left_white"), for: .normal)
self.lightStatusBar()
}else{
self.backButton.setImage(#imageLiteral(resourceName: "arrow_left_black"), for: .normal)
self.darkStatusBar()
}
self.associationNameLabel.textColor = UIColor.hexToRGB(self.association.fgColor!)
}
override func viewDidAppear(_ animated: Bool) {
self.fetchPosts()
self.fetchEvents()
self.downloadGroup.notify(queue: DispatchQueue.main) {
self.events = self.events.sorted(by: { (e1, e2) -> Bool in
e1.dateStart!.timeIntervalSince(e2.dateStart! as Date) > 0
})
self.posts = self.posts.sorted(by: { (p1, p2) -> Bool in
p1.date!.timeIntervalSince(p2.date! as Date) > 0
})
self.hasLoaded = true
self.tableView.reloadData()
}
}
func fetchPosts(){
self.posts = []
for postId in self.association.posts! {
self.downloadGroup.enter()
APIManager.fetchPost(post_id: postId, controller: self, completion: { (opt_post) in
guard let post = opt_post else { return }
self.posts.append(post)
self.downloadGroup.leave()
})
}
}
func fetchEvents(){
self.events = []
for eventId in self.association.events! {
self.downloadGroup.enter()
APIManager.fetchEvent(event_id: eventId, controller: self, completion: { (opt_event) in
guard let event = opt_event else { return }
self.events.append(event)
self.downloadGroup.leave()
})
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 { return 0 }
return 20
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 { return .none }
let view = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.frame.width, height: 20))
view.backgroundColor = UIColor.hexToRGB(self.association.bgColor!)
return view
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 { return 1 }
return 5
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 { return 233 }
if indexPath.row == 0 { return self.hasLoaded ? 0 : 44 } //LoadingCell
if indexPath.row == 1 { return AssociationEventsCell.getHeightForEvents(events: self.events) }
if indexPath.row == 2 { return self.posts.count == 0 ? 0 : 225 + 30 }
if indexPath.row == 3 { return AssociationDescriptionCell.getHeightForAssociation(association, forWidth: self.tableView.frame.width) }
return 60
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: kAssociationHeaderCell, for: indexPath) as! AssociationHeaderCell
cell.load(association: self.association)
cell.parent = self
return cell
}else{
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: kLoadingCell, for: indexPath) as! LoadingCell
cell.load(association: self.association)
return cell
}else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: kAssociationEventsCell, for: indexPath) as! AssociationEventsCell
cell.load(events: self.events, forAssociation: self.association)
cell.delegate = self
return cell
}else if indexPath.row == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: kAssociationPostsCell, for: indexPath) as! AssociationPostsCell
cell.load(posts: self.posts, forAssociation: self.association)
cell.delegate = self
return cell
}else if indexPath.row == 3 {
let cell = tableView.dequeueReusableCell(withIdentifier: kAssociationDescriptionCell, for: indexPath) as! AssociationDescriptionCell
cell.load(association: self.association)
return cell
}else{
let cell = tableView.dequeueReusableCell(withIdentifier: kAssociationContactCell, for: indexPath) as! AssociationContactCell
cell.load(association: self.association)
return cell
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 1, indexPath.row == 4 {
let email = self.association.email!
let url = URL(string: "mailto:\(email)")
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let value = scrollView.contentOffset.y
if value >= 0 {
self.coverImageView.frame = CGRect(x: 0, y: max(-105,-value), width: self.view.frame.width, height: 175)
self.blurCoverView.frame = self.coverImageView.frame
self.blurCoverView.alpha = (20-(105-max(value, 85)))/20
self.associationNameLabel.alpha = (20-(145-max(value, 125)))/20
if value >= 105 {
self.profileImageView.frame = CGRect(x: self.view.frame.width-8-40, y: 20, width: 40, height: 40)
}else{
let coef = -0.0048*value+0.91
self.profileImageView.frame = CGRect(x: self.view.frame.width-8-100*coef, y: 125-value, width: 100*coef, height: 100*coef)
}
self.profileImageView.layer.cornerRadius = self.profileImageView.frame.width/2
}else{
self.coverImageView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 175 - value)
self.blurCoverView.frame = self.coverImageView.frame
self.blurCoverView.alpha = (self.coverImageView.frame.height-175)/100
self.profileImageView.frame = CGRect(x: self.view.frame.width-8-100, y: 125-value, width: 100, height: 100)
self.profileImageView.layer.cornerRadius = self.profileImageView.frame.width/2
self.associationNameLabel.alpha = 0
}
}
func show(post: Post){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "NewsViewController") as! NewsViewController
vc.activePost = post
vc.canReturn = true
vc.canSearch = false
vc.canRefresh = false
self.navigationController?.pushViewController(vc, animated: true)
}
func showAllPostAction() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "SeeMoreViewController") as! SeeMoreViewController
vc.posts = self.posts
vc.searchedText = "@" + self.association.name!
vc.type = 2
vc.prt = self
self.navigationController?.pushViewController(vc, animated: true)
}
func show(event: Event, association: Association){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "EventViewController") as! EventViewController
vc.event = event
vc.association = association
self.navigationController?.pushViewController(vc, animated: true)
}
func showAllEventAction(){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "SeeMoreViewController") as! SeeMoreViewController
vc.events = self.events
vc.associationTable = [ self.association.id! : self.association ]
vc.searchedText = self.association.name!
vc.type = 3
vc.prt = self
self.navigationController?.pushViewController(vc, animated: true)
}
@IBAction func dismissAction(_ sender: AnyObject) {
self.navigationController!.popViewController(animated: true)
}
}
| mit | b8d020d4486e39bf1a09620497d1138e | 45.895397 | 148 | 0.647573 | 4.749153 | false | false | false | false |
tensorflow/examples | lite/examples/speech_commands/ios/SpeechCommands/ModelDataHandler/RecognizeCommands.swift | 1 | 5668 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
struct RecognizedCommand {
var score: Float
var name: String
var isNew: Bool
}
/**
This class smoothes out the results by averaging them over a window duration and making sure the
commands are not duplicated for display.
*/
class RecognizeCommands {
// MARK: Structures that handles results.
private struct Command {
var score: Float
let name: String
}
private struct ResultsAtTime {
let time: TimeInterval
let scores: [Float]
}
// MARK: Constants
private let averageWindowDuration: Double
private let suppressionTime: Double
private let minimumCount: Int
private let minimumTimeBetweenSamples: Double
private let detectionThreshold: Float
private let classLabels: [String]
private let silenceLabel = "_silence_"
private var previousTopLabel = "_silence_"
private var previousTopScore: Float = 0.0
private var previousTopLabelTime: TimeInterval = Date.distantPast.timeIntervalSince1970 * 1000
private var previousResults: [ResultsAtTime] = []
/**
Initializes RecognizeCommands with specified parameters.
*/
init(averageWindowDuration: Double, detectionThreshold: Float, minimumTimeBetweenSamples: Double, suppressionTime: Double, minimumCount: Int, classLabels: [String]) {
self.averageWindowDuration = averageWindowDuration
self.detectionThreshold = detectionThreshold
self.minimumTimeBetweenSamples = minimumTimeBetweenSamples
self.suppressionTime = suppressionTime
self.minimumCount = minimumCount
self.classLabels = classLabels
}
/**
This function averages the results obtained over an average window duration and prunes out any
old results.
*/
func process(latestResults: [Float], currentTime: TimeInterval) -> RecognizedCommand? {
guard latestResults.count == classLabels.count else {
fatalError("There should be \(classLabels.count) in results. But there are \(latestResults.count) results")
}
// Checks if the new results were identified at a later time than the currently identified
// results.
if let first = previousResults.first, first.time > currentTime {
fatalError("Results should be provided in increasing time order")
}
if let lastResult = previousResults.last {
let timeSinceMostRecent = currentTime - previousResults[previousResults.count - 1].time
// If not enough time has passed after the last inference, we return the previously identified
// result as legitimate one.
if timeSinceMostRecent < minimumTimeBetweenSamples {
return RecognizedCommand(score: previousTopScore, name: previousTopLabel, isNew: false)
}
}
// Appends the new results to the identified results
let results: ResultsAtTime = ResultsAtTime(time: currentTime, scores: latestResults)
previousResults.append(results)
let timeLimit = currentTime - averageWindowDuration
// Flushes out all the results currently held that less than the average window duration since
// they are considered too old for averaging.
while previousResults[0].time < timeLimit {
previousResults.removeFirst()
guard previousResults.count > 0 else {
break
}
}
// If number of results currently held to average is less than a minimum count, return the score
// as zero so that no command is identified.
if previousResults.count < minimumCount {
return RecognizedCommand(score: 0.0, name: previousTopLabel, isNew: false)
}
// Creates an average of the scores of each classes currently held by this class.
var averageScores:[Command] = []
for i in 0...classLabels.count - 1 {
let command = Command(score: 0.0, name: classLabels[i])
averageScores.append(command)
}
for result in previousResults {
let scores = result.scores
for i in 0...scores.count - 1 {
averageScores[i].score = averageScores[i].score + scores[i] / Float(previousResults.count)
}
}
// Sorts scores in descending order of confidence.
averageScores.sort { (first, second) -> Bool in
return first.score > second.score
}
var timeSinceLastTop: Double = 0.0
// If silence was detected previously, consider the current result with the best average as a
// new command to be displayed.
if (previousTopLabel == silenceLabel ||
previousTopLabelTime == (Date.distantPast.timeIntervalSince1970 * 1000)) {
timeSinceLastTop = Date.distantFuture.timeIntervalSince1970 * 1000
}
else {
timeSinceLastTop = currentTime - previousTopLabelTime
}
// Return the results
var isNew = false
if (averageScores[0].score > detectionThreshold && timeSinceLastTop > suppressionTime) {
previousTopScore = averageScores[0].score
previousTopLabel = averageScores[0].name
previousTopLabelTime = currentTime
isNew = true
}
else {
isNew = false
}
return RecognizedCommand(
score: previousTopScore, name: previousTopLabel, isNew: isNew)
}
}
| apache-2.0 | ea5dac0bc8505787bd7dd9a491349ab4 | 32.738095 | 168 | 0.719301 | 4.630719 | false | false | false | false |
aleckretch/Bloom | iOS/Bloom/Bloom/Components/Add Card/Cells/AddCardTextTableViewCell.swift | 1 | 758 | //
// AddCardTextTableViewCell.swift
// Bloom
//
// Created by Alec Kretch on 10/22/17.
// Copyright © 2017 Alec Kretch. All rights reserved.
//
import Foundation
import UIKit
class AddCardTextTableViewCell: UITableViewCell {
@IBOutlet weak var descriptionLabel: UILabel! {
didSet {
descriptionLabel.font = UIFont.systemFont(ofSize: 14.0)
descriptionLabel.textColor = Constant.Color.lightGray
descriptionLabel.numberOfLines = 0
}
}
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: UIScreen.main.bounds.size.width * 2)
// Initialization code
}
}
| mit | 900cf60329eeb7bbad265a5901795e00 | 25.103448 | 109 | 0.647292 | 4.532934 | false | false | false | false |
cornerstonecollege/402 | Digby/class_10/Pokedex/Pokedex/TableViewController.swift | 1 | 1744 | //
// TableViewController.swift
// Pokedex
//
// Created by Digby Andrews on 2016-07-08.
// Copyright © 2016 Digby Andrews. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController
{
internal static var currentIndex = 0
internal static let pokedex =
[
["Name": "Bulbasaur", "Height": "0.7m",],
["Name": "Ivysaur", "Height": "1m"],
["Name": "Venosaur", "Height": "2m"],
["Name": "Squirtle", "Height": "0.4m"],
["Name": "Wartotle", "Height": "0.6m"],
["Name": "Blastoise", "Height": "2m"],
["Name": "Charmander", "Height": "0.9m"],
["Name": "Charmeleon", "Height": "1.5m"],
["Name": "Charizard", "Height": "3m"]
]
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return TableViewController.pokedex.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell = self.tableView.dequeueReusableCellWithIdentifier("CellId")
if cell == nil
{
cell = UITableViewCell(style: .Default, reuseIdentifier: "CellId")
}
cell!.textLabel?.text = TableViewController.pokedex [indexPath.row]["Name"]
return cell!
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath?
{
TableViewController.currentIndex = indexPath.row
return indexPath
}
}
| gpl-3.0 | 4f169265c4384c9468d115583df4e357 | 27.112903 | 116 | 0.607573 | 4.435115 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.