repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sroebert/JSONCoding
|
Sources/JSONExtensions.swift
|
1
|
5827
|
//
// JSONExtensions.swift
// JSONCoding
//
// Created by Steven Roebert on 04/05/17.
// Copyright © 2017 Steven Roebert. All rights reserved.
//
import Foundation
public extension JSONDecoder {
// MARK: - JSONInteger from String
private func integerFromString<Number: JSONInteger>(_ path: JSONPath, value: String) throws -> Number {
guard let number = Number(value, radix: 10) else {
throw JSONDecodingError.custom(path, "Could not convert string into an integer.")
}
return number
}
public func decodeNumberFromString<Number: JSONInteger>(_ path: JSONPath = nil) throws -> Number {
let string: String = try decode(path)
return try integerFromString(path, value: string)
}
public func decodeNumberFromString<Number: JSONInteger>(_ path: JSONPath = nil) throws -> Number? {
let string: String? = try decode(path)
guard string != nil else {
return nil
}
let number: Number = try integerFromString(path, value: string!)
return number
}
// MARK: - JSONFloat from String
private func floatFromString<Number: JSONFloat>(_ path: JSONPath, value: String) throws -> Number {
guard let number = Number(value) else {
throw JSONDecodingError.custom(path, "Could not convert string into a float.")
}
return number
}
public func decodeNumberFromString<Number: JSONFloat>(_ path: JSONPath = nil) throws -> Number {
let string: String = try decode(path)
return try floatFromString(path, value: string)
}
public func decodeNumberFromString<Number: JSONFloat>(_ path: JSONPath = nil) throws -> Number? {
let string: String? = try decode(path)
guard string != nil else {
return nil
}
let number: Number = try floatFromString(path, value: string!)
return number
}
// MARK: - Date
public struct DateParsing {
public static var decoder: (_ decoder: JSONDecoder, _ path: JSONPath) throws -> Date = { decoder, path in
return try decoder.decode(path) { (timeInterval: Int64, fullPath) in
return JSONDecoder.date(from: timeInterval)
}
}
public static var optionalDecoder: (_ decoder: JSONDecoder, _ path: JSONPath) throws -> Date? = { decoder, path in
return try decoder.decode(path) { (timeInterval: Int64, fullPath) in
return JSONDecoder.date(from: timeInterval)
}
}
}
private static func date(from value: Int64) -> Date {
return Date(timeIntervalSince1970: Double(value) / 1000)
}
private static func date(from string: String, format: String, locale: Locale, path: JSONPath) throws -> Date {
let formatter = DateFormatter()
formatter.locale = locale
formatter.dateFormat = format
guard let date = formatter.date(from: string) else {
throw JSONDecodingError.custom(path, "Could not convert '\(string)' into date.")
}
return date
}
public func decode(_ path: JSONPath = nil) throws -> Date {
return try DateParsing.decoder(self, path)
}
public func decode(_ path: JSONPath = nil) throws -> Date? {
return try DateParsing.optionalDecoder(self, path)
}
public func decode(_ path: JSONPath = nil, format: String, locale: Locale = Locale.current) throws -> Date {
return try decode(path) { (string: String, fullPath) in
return try JSONDecoder.date(from: string, format: format, locale: locale, path: path)
}
}
public func decode(_ path: JSONPath = nil, format: String, locale: Locale = Locale.current) throws -> Date? {
return try decode(path) { (string: String, fullPath) in
return try JSONDecoder.date(from: string, format: format, locale: locale, path: path)
}
}
}
public extension JSONEncoder {
// MARK: - Date
public struct DateParsing {
public static var encoder: (_ encoder: JSONEncoder, _ value: Date, _ path: JSONPath) throws -> Void = { encoder, value, path in
return try encoder.encode(value, path: path) { (date: Date, fullPath) in
return Int64(round(date.timeIntervalSince1970 * 1000))
}
}
public static var optionalEncoder: (_ encoder: JSONEncoder, _ value: Date?, _ path: JSONPath) throws -> Void = { encoder, value, path in
return try encoder.encode(value, path: path) { (date: Date, fullPath) in
return Int64(round(date.timeIntervalSince1970 * 1000))
}
}
}
public func encode(_ value: Date, path: JSONPath = nil) throws {
return try DateParsing.encoder(self, value, path)
}
public func encode(_ value: Date?, path: JSONPath = nil) throws {
return try DateParsing.optionalEncoder(self, value, path)
}
public func encode(_ value: Date, path: JSONPath = nil, format: String, locale: Locale = Locale.current) throws {
return try encode(value, path: path) { (date: Date, fullPath) in
let formatter = DateFormatter()
formatter.locale = locale
formatter.dateFormat = format
return formatter.string(from: date)
}
}
public func encode(_ value: Date?, path: JSONPath = nil, format: String, locale: Locale = Locale.current) throws {
return try encode(value, path: path) { (date: Date, fullPath) in
let formatter = DateFormatter()
formatter.locale = locale
formatter.dateFormat = format
return formatter.string(from: date)
}
}
}
|
mit
|
08d10d0d08765137025bb30b20765511
| 36.831169 | 144 | 0.610882 | 4.572998 | false | false | false | false |
okkhoury/SafeNights_iOS
|
Pods/JSONHelper/JSONHelper/Conversion.swift
|
1
|
4068
|
//
// Copyright © 2016 Baris Sencan. All rights reserved.
//
import Foundation
/// Operator for use in right hand side to left hand side conversion.
infix operator <-- : convert
precedencegroup convert
{
associativity: right
}
/// Thrown when a conversion operation fails.
public enum ConversionError: Error {
/// TODOC
case unsupportedType
/// TODOC
case invalidValue
}
/// An object that can attempt to convert values of unknown types to its own type.
public protocol Convertible {
/// TODOC
static func convert<T>(fromValue value: T?) throws -> Self?
}
// MARK: - Basic Conversion
@discardableResult public func <-- <T, U>(lhs: inout T?, rhs: U?) -> T? {
if !(lhs is NSNull) {
lhs = JSONHelper.convertToNilIfNull(rhs) as? T
} else {
lhs = rhs as? T
}
return lhs
}
@discardableResult public func <-- <T, U>(lhs: inout T, rhs: U?) -> T {
var newValue: T?
newValue <-- rhs
lhs = newValue ?? lhs
return lhs
}
@discardableResult public func <-- <C: Convertible, T>(lhs: inout C?, rhs: T?) -> C? {
lhs = nil
do {
lhs = try C.convert(fromValue: JSONHelper.convertToNilIfNull(rhs))
} catch ConversionError.invalidValue {
#if DEBUG
print("Invalid value \(rhs.debugDescription) for supported type.")
#endif
} catch ConversionError.unsupportedType {
#if DEBUG
print("Unsupported type.")
#endif
} catch {}
return lhs
}
@discardableResult public func <-- <C: Convertible, T>(lhs: inout C, rhs: T?) -> C {
var newValue: C?
newValue <-- rhs
lhs = newValue ?? lhs
return lhs
}
// MARK: - Array Conversion
@discardableResult public func <-- <C: Convertible, T>(lhs: inout [C]?, rhs: [T]?) -> [C]? {
guard let rhs = rhs else {
lhs = nil
return lhs
}
lhs = [C]()
for element in rhs {
var convertedElement: C?
convertedElement <-- element
if let convertedElement = convertedElement {
lhs?.append(convertedElement)
}
}
return lhs
}
@discardableResult public func <-- <C: Convertible, T>(lhs: inout [C], rhs: [T]?) -> [C] {
var newValue: [C]?
newValue <-- rhs
lhs = newValue ?? lhs
return lhs
}
@discardableResult public func <-- <C: Convertible, T>(lhs: inout [C]?, rhs: T?) -> [C]? {
guard let rhs = rhs else {
lhs = nil
return lhs
}
if let elements = rhs as? NSArray as [AnyObject]? {
return lhs <-- elements
}
return nil
}
@discardableResult public func <-- <C: Convertible, T>(lhs: inout [C], rhs: T?) -> [C] {
var newValue: [C]?
newValue <-- rhs
lhs = newValue ?? lhs
return lhs
}
// MARK: - Dictionary Conversion
@discardableResult public func <-- <T, C: Convertible, U>(lhs: inout [T : C]?, rhs: [T : U]?) -> [T : C]? {
guard let rhs = rhs else {
lhs = nil
return lhs
}
lhs = [T : C]()
for (key, value) in rhs {
var convertedValue: C?
convertedValue <-- value
if let convertedValue = convertedValue {
lhs?[key] = convertedValue
}
}
return lhs
}
@discardableResult public func <-- <T, C: Convertible, U>(lhs: inout [T : C], rhs: [T : U]?) -> [T : C] {
var newValue: [T : C]?
newValue <-- rhs
lhs = newValue ?? lhs
return lhs
}
@discardableResult public func <-- <T, C: Convertible, U>(lhs: inout [T : C]?, rhs: U?) -> [T : C]? {
guard let rhs = rhs else {
lhs = nil
return lhs
}
if let elements = rhs as? NSDictionary as? [T : AnyObject] {
return lhs <-- elements
}
return nil
}
@discardableResult public func <-- <T, C: Convertible, U>(lhs: inout [T : C], rhs: U?) -> [T : C] {
var newValue: [T : C]?
newValue <-- rhs
lhs = newValue ?? lhs
return lhs
}
// MARK: - Enum Conversion
@discardableResult public func <-- <T: RawRepresentable, U>(lhs: inout T?, rhs: U?) -> T? {
var newValue: T?
if let
rawValue = rhs as? T.RawValue,
let enumValue = T(rawValue: rawValue) {
newValue = enumValue
}
lhs = newValue
return lhs
}
@discardableResult public func <-- <T: RawRepresentable, U>(lhs: inout T, rhs: U?) -> T {
var newValue: T?
newValue <-- rhs
lhs = newValue ?? lhs
return lhs
}
|
mit
|
839becddee0b9eddfca3efb54d4a89ca
| 20.518519 | 107 | 0.616917 | 3.576957 | false | false | false | false |
velvetroom/columbus
|
Source/View/Store/VStoreStatusReadyListCellAvailable+Constants.swift
|
1
|
318
|
import UIKit
extension VStoreStatusReadyListCellAvailable
{
struct Constants
{
static let priceFontSize:CGFloat = 15
static let priceHeight:CGFloat = 50
static let priceBottom:CGFloat = -50
static let priceRight:CGFloat = -12
static let priceWith:CGFloat = 300
}
}
|
mit
|
0d6030ba77c792f7d587f99985b29317
| 23.461538 | 45 | 0.672956 | 4.676471 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Rocket.Chat/Controllers/Preferences/ChangeAppIcon/ChangeAppIconCell.swift
|
1
|
1378
|
//
// ChangeAppIconCell.swift
// Rocket.Chat
//
// Created by Artur Rymarz on 08.02.2018.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import UIKit
final class ChangeAppIconCell: UICollectionViewCell {
@IBOutlet private weak var iconImageView: UIImageView! {
didSet {
iconImageView.isAccessibilityElement = true
}
}
@IBOutlet private weak var checkImageView: UIImageView!
@IBOutlet private weak var checkImageViewBackground: UIView!
func setIcon(name: (String, String), selected: Bool) {
iconImageView.image = UIImage(named: name.0)
iconImageView.accessibilityLabel = VOLocalizedString(name.1)
if selected {
iconImageView.layer.borderColor = UIColor.RCBlue().cgColor
iconImageView.layer.borderWidth = 3
iconImageView.accessibilityTraits = .selected
checkImageView.image = checkImageView.image?.imageWithTint(UIColor.RCBlue())
checkImageView.isHidden = false
checkImageViewBackground.isHidden = false
} else {
iconImageView.layer.borderColor = UIColor.RCLightGray().cgColor
iconImageView.layer.borderWidth = 1
iconImageView.accessibilityTraits = .none
checkImageView.isHidden = true
checkImageViewBackground.isHidden = true
}
}
}
|
mit
|
e46eef6e44080d2d0c8be9077a780975
| 31.023256 | 88 | 0.668119 | 5.007273 | false | false | false | false |
parkera/swift
|
test/refactoring/ConvertAsync/async_attribute_added.swift
|
1
|
2281
|
// REQUIRES: concurrency
// RUN: %empty-directory(%t)
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 -enable-experimental-concurrency | %FileCheck -check-prefix=SIMPLE %s
func simple(completion: @escaping (String) -> Void) { }
// SIMPLE: async_attribute_added.swift [[# @LINE-1]]:1 -> [[# @LINE-1]]:1
// SIMPLE-NEXT: @available(*, renamed: "simple()")
// SIMPLE-EMPTY:
// SIMPLE-NEXT: async_attribute_added.swift [[# @LINE-4]]:53 -> [[# @LINE-4]]:56
// SIMPLE-NEXT: {
// SIMPLE-NEXT: Task {
// SIMPLE-NEXT: let result = await simple()
// SIMPLE-NEXT: completion(result)
// SIMPLE-NEXT: }
// SIMPLE-NEXT: }
// SIMPLE-EMPTY:
// SIMPLE-NEXT: async_attribute_added.swift [[# @LINE-12]]:56 -> [[# @LINE-12]]:56
// SIMPLE-EMPTY:
// SIMPLE-EMPTY:
// SIMPLE-EMPTY:
// SIMPLE-NEXT: async_attribute_added.swift [[# @LINE-16]]:56 -> [[# @LINE-16]]:56
// SIMPLE-NEXT: func simple() async -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):5 -enable-experimental-concurrency | %FileCheck -check-prefix=OTHER-ARGS %s
func otherArgs(first: Int, second: String, completion: @escaping (String) -> Void) { }
// OTHER-ARGS: @available(*, renamed: "otherArgs(first:second:)")
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):5 -enable-experimental-concurrency | %FileCheck -check-prefix=EMPTY-NAMES %s
func emptyNames(first: Int, _ second: String, completion: @escaping (String) -> Void) { }
// EMPTY-NAMES: @available(*, renamed: "emptyNames(first:_:)")
// Not a completion handler named parameter, but should still be converted
// during function conversion since it has been attributed
@available(*, renamed: "otherName()")
func otherName(notHandlerName: @escaping (String) -> (Void)) {}
func otherName() async -> String {}
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):5 -enable-experimental-concurrency | %FileCheck -check-prefix=OTHER-CONVERTED %s
func otherStillConverted() {
otherName { str in
print(str)
}
}
// OTHER-CONVERTED: func otherStillConverted() async {
// OTHER-CONVERTED-NEXT: let str = await otherName()
// OTHER-CONVERTED-NEXT: print(str)
|
apache-2.0
|
846fb9665614d5e6a197711fb911ff4a
| 47.531915 | 178 | 0.69224 | 3.369276 | false | false | false | false |
A-Kod/vkrypt
|
Pods/SwiftyVK/Library/Sources/Sessions/Management/SessionsHolder.swift
|
2
|
4088
|
import Foundation
/// Storage of VK user sessions
public protocol SessionsHolder: class {
/// Default VK user session
var `default`: Session { get }
// For now SwiftyVK does not support multisession
// Probably, in the future it will be done
// If you want to use more than one session, let me know about it
// Maybe, you make PR to SwiftyVK ;)
// func make(config: SessionConfig) -> Session
// var all: [Session] { get }
// func destroy(session: Session) throws
// func markAsDefault(session: Session) throws
}
protocol SessionSaver: class {
func saveState()
}
public final class SessionsHolderImpl: SessionsHolder, SessionSaver {
private let sessionMaker: SessionMaker
private let sessionsStorage: SessionsStorage
private var sessions = NSHashTable<AnyObject>(options: .strongMemory)
public var `default`: Session {
get {
if storedDefault.state == .destroyed {
sessions.remove(storedDefault)
storedDefault = self.sessionMaker.session(
id: .random(20),
config: storedDefault.config,
sessionSaver: self
)
sessions.add(storedDefault)
}
return storedDefault
}
set {
storedDefault = newValue
}
}
lazy private var storedDefault: Session = {
self.sessionMaker.session(
id: .random(20),
config: .default,
sessionSaver: self
)
}()
public var all: [Session] {
return sessions.allObjects.flatMap { $0 as? Session }
}
init(
sessionMaker: SessionMaker,
sessionsStorage: SessionsStorage
) {
self.sessionMaker = sessionMaker
self.sessionsStorage = sessionsStorage
restoreState()
self.sessions.add(`default`)
saveState()
}
func make() -> Session {
return make(config: .default)
}
public func make(config: SessionConfig) -> Session {
let session = sessionMaker.session(
id: .random(20),
config: config,
sessionSaver: self
)
sessions.add(session)
saveState()
return session
}
public func destroy(session: Session) throws {
if session.state == .destroyed {
throw VKError.sessionAlreadyDestroyed(session)
}
(session as? DestroyableSession)?.destroy()
sessions.remove(session)
}
public func markAsDefault(session: Session) throws {
if session.state == .destroyed {
throw VKError.sessionAlreadyDestroyed(session)
}
self.default = session
}
func saveState() {
let encodedSessions = self.all.map {
EncodedSession(isDefault: $0 == self.`default`, id: $0.id, config: $0.config)
}
do {
try self.sessionsStorage.save(sessions: encodedSessions)
}
catch let error {
print("Sessions not saved with error: \(error)")
}
}
private func restoreState() {
do {
let decodedSessions = try sessionsStorage.restore()
.filter { !$0.id.isEmpty }
decodedSessions
.filter { !$0.isDefault }
.map { sessionMaker.session(id: $0.id, config: $0.config, sessionSaver: self) }
.forEach { sessions.add($0) }
if let defaultSession = decodedSessions
.first(where: { $0.isDefault })
.map({ sessionMaker.session(id: $0.id, config: $0.config, sessionSaver: self) }) {
sessions.add(defaultSession)
`default` = defaultSession
}
}
catch let error {
print("Restore sessions failed with error: \(error)")
}
}
}
|
apache-2.0
|
bad183170ba7c393f8b92805dfd590fb
| 27.992908 | 98 | 0.542319 | 4.901679 | false | true | false | false |
4dot/MatchMatch
|
MatchMatch/Model/MatchCard.swift
|
1
|
817
|
//
// MatchCard.swift
// MatchMatch
//
// Created by Park, Chanick on 5/23/17.
// Copyright © 2017 Chanick Park. All rights reserved.
//
import Foundation
import UIKit
import SwiftyJSON
/**
@desc Card Data Model Class
*/
class MatchCard : NSObject {
var id: String = ""
var title: String = ""
var placeHolderURL: String = ""
var frontImageURL: String = ""
// MARK: - Init
/**
@desc Init Movie data with id and name
*/
init(_ id: String, _ title: String) {
self.id = id
self.title = title
}
/**
@desc Init Movie data with SwiftyJON
*/
init(with json: JSON) {
self.id = json["id"].string ?? ""
self.title = json["title"].string ?? ""
self.frontImageURL = json["url_n"].string ?? ""
}
}
|
mit
|
8ad304be558db465ef92180174728d1f
| 18.902439 | 55 | 0.552696 | 3.709091 | false | false | false | false |
kitasuke/Cardio
|
Cardio/Cardio.swift
|
1
|
13769
|
//
// Cardio.swift
// Cardio
//
// Created by Yusuke Kita on 10/4/15.
// Copyright © 2015 kitasuke. All rights reserved.
//
import Foundation
import HealthKit
import Result
final public class Cardio: NSObject {
public var isAuthorized: Bool {
let shareTypes = context.shareIdentifiers.flatMap { HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: $0)) } + [HKWorkoutType.workoutType()]
return shareTypes.contains {
switch healthStore.authorizationStatus(for: $0) {
case .sharingAuthorized: return true
default: return false
}
}
}
fileprivate let context: ContextType
fileprivate let healthStore = HKHealthStore()
fileprivate let workoutConfiguration = HKWorkoutConfiguration()
#if os(watchOS)
public var distanceHandler: ((_ addedValue: Double, _ totalValue: Double) -> Void)?
public var activeEnergyHandler: ((_ addedValue: Double, _ totalValue: Double) -> Void)?
public var heartRateHandler: ((_ addedValue: Double, _ averageValue: Double) -> Void)?
public fileprivate(set) var workoutState: HKWorkoutSessionState = .notStarted
fileprivate var workoutSession: HKWorkoutSession?
fileprivate var startHandler: ((Result<(HKWorkoutSession, Date), CardioError>) -> Void)?
fileprivate var endHandler: ((Result<(HKWorkoutSession, Date), CardioError>) -> Void)?
fileprivate var startDate = Date()
fileprivate var endDate = Date()
fileprivate var pauseDate = Date()
fileprivate var pauseDuration: TimeInterval = 0
fileprivate lazy var queries = [HKQuery]()
fileprivate lazy var distanceQuantities = [HKQuantitySample]()
fileprivate lazy var activeEnergyQuantities = [HKQuantitySample]()
fileprivate lazy var heartRateQuantities = [HKQuantitySample]()
@available(*, unavailable, message: "Please use `workoutState` instead")
public fileprivate(set) var state: State = .notStarted
public enum State {
case notStarted
case running
case paused
case ended
}
#endif
// MARK: - Initializer
public init (context: ContextType) throws {
self.context = context
self.workoutConfiguration.activityType = context.activityType
self.workoutConfiguration.locationType = context.locationType
#if os(watchOS)
try self.workoutSession = HKWorkoutSession(configuration: self.workoutConfiguration)
#endif
super.init()
#if os(watchOS)
self.workoutSession!.delegate = self
#endif
}
// MARK: - Public
public func authorize(_ handler: @escaping (Result<(), CardioError>) -> Void = { r in }) {
guard HKHealthStore.isHealthDataAvailable() else {
handler(.failure(.unsupportedDeviceError))
return
}
let shareIdentifiers = context.shareIdentifiers.flatMap { HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: $0)) }
let shareTypes = Set([HKWorkoutType.workoutType()] as [HKSampleType] + shareIdentifiers as [HKSampleType])
let readTypes = Set(context.readIdentifiers.flatMap { HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: $0)) })
HKHealthStore().requestAuthorization(toShare: shareTypes, read: readTypes) { (success, error) -> Void in
let result: Result<(), CardioError>
if success {
result = .success()
} else {
result = .failure(.authorizationError(error))
}
DispatchQueue.main.async(execute: { () -> Void in
handler(result)
})
}
}
#if os(watchOS)
public func start(_ handler: @escaping (Result<(HKWorkoutSession, Date), CardioError>) -> Void = { r in }) {
startHandler = handler
defer {
healthStore.start(workoutSession!)
}
guard workoutSession == nil else { return }
do {
workoutSession = try HKWorkoutSession(configuration: workoutConfiguration)
} catch let error {
handler(.failure(.unexpectedWorkoutConfigurationError(error as NSError)))
}
workoutSession!.delegate = self
}
public func end(_ handler: @escaping (Result<(HKWorkoutSession, Date), CardioError>) -> Void = { r in }) {
guard let workoutSession = self.workoutSession else { return }
endHandler = handler
healthStore.end(workoutSession)
}
public func pause() {
guard let workoutSession = self.workoutSession else { return }
healthStore.pause(workoutSession)
}
public func resume() {
guard let workoutSession = self.workoutSession else { return }
healthStore.resumeWorkoutSession(workoutSession)
}
public func save(_ metadata: [String: AnyObject] = [:], handler: @escaping (Result<HKWorkout, CardioError>) -> Void = { r in }) {
guard case .orderedDescending = endDate.compare(startDate) else {
handler(.failure(.invalidDurationError))
return
}
let quantities = distanceQuantities + activeEnergyQuantities + heartRateQuantities
let samples = quantities.map { $0 as HKSample }
guard samples.count > 0 else {
handler(.failure(.noValidSavedDataError))
return
}
var metadata = metadata
heartRateMetadata().forEach { key, value in
metadata[key] = value
}
// values to save
let totalDistance = totalValue(context.distanceUnit)
let totalActiveEnergy = totalValue(context.activeEnergyUnit)
// workout data with metadata
let workout = HKWorkout(activityType: context.activityType, start: startDate, end: endDate, duration: endDate.timeIntervalSince(startDate) - pauseDuration, totalEnergyBurned: HKQuantity(unit: context.activeEnergyUnit, doubleValue: totalActiveEnergy), totalDistance: HKQuantity(unit: context.distanceUnit, doubleValue: totalDistance), metadata: metadata)
// save workout
healthStore.save(workout, withCompletion: { [weak self] (success, error) in
guard success else {
DispatchQueue.main.async(execute: { () -> Void in
handler(.failure(.workoutSaveFailedError(error)))
})
return
}
// save distance, active energy and heart rate themselves
self?.healthStore.add(samples, to: workout, completion: { (success, error) -> Void in
let result: Result<HKWorkout, CardioError>
if success {
result = .success(workout)
} else {
result = .failure(.dataSaveFailedError(error))
}
DispatchQueue.main.async(execute: { () -> Void in
handler(result)
})
})
})
}
// MARK: - Private
fileprivate func startWorkout(_ workoutSession: HKWorkoutSession, date: Date) {
startDate = date
startQuery(startDate)
startHandler?(.success(workoutSession, date))
}
fileprivate func pauseWorkout(_ workoutSession: HKWorkoutSession, date: Date) {
pauseDate = date
stopQuery()
}
fileprivate func resumeWorkout(_ workoutSesion: HKWorkoutSession, date: Date) {
let resumeDate = Date()
pauseDuration = resumeDate.timeIntervalSince(pauseDate)
startQuery(resumeDate)
}
fileprivate func endWorkout(_ workoutSession: HKWorkoutSession, date: Date) {
endDate = date
stopQuery()
self.workoutSession = nil
endHandler?(.success(workoutSession, date))
}
// MARK: - Query
fileprivate func startQuery(_ date: Date) {
queries.append(createStreamingQueries(context.distanceType, date: date))
queries.append(createStreamingQueries(context.activeEnergyType, date: date))
queries.append(createStreamingQueries(context.heartRateType, date: date))
queries.forEach { healthStore.execute($0) }
}
fileprivate func stopQuery() {
queries.forEach { healthStore.stop($0) }
queries.removeAll(keepingCapacity: true)
}
fileprivate func createStreamingQueries<T: HKQuantityType>(_ type: T, date: Date) -> HKQuery {
let predicate = HKQuery.predicateForSamples(withStart: date, end: nil, options: HKQueryOptions())
let query = HKAnchoredObjectQuery(type: type, predicate: predicate, anchor: nil, limit: Int(HKObjectQueryNoLimit)) { (query, samples, deletedObjects, anchor, error) -> Void in
self.addSamples(type, samples: samples)
}
query.updateHandler = { (query, samples, deletedObjects, anchor, error) -> Void in
self.addSamples(type, samples: samples)
}
return query
}
fileprivate func addSamples(_ type: HKQuantityType, samples: [HKSample]?) {
guard let samples = samples as? [HKQuantitySample] else { return }
guard let quantity = samples.last?.quantity else { return }
let unit: HKUnit
switch type {
case context.distanceType:
distanceQuantities.append(contentsOf: samples)
unit = context.distanceUnit
DispatchQueue.main.async(execute: { () -> Void in
self.distanceHandler?(quantity.doubleValue(for: unit), self.totalValue(unit))
})
case context.activeEnergyType:
activeEnergyQuantities.append(contentsOf: samples)
unit = context.activeEnergyUnit
DispatchQueue.main.async(execute: { () -> Void in
self.activeEnergyHandler?(quantity.doubleValue(for: unit), self.totalValue(unit))
})
case context.heartRateType:
heartRateQuantities.append(contentsOf: samples)
unit = context.heartRateUnit
DispatchQueue.main.async(execute: { () -> Void in
self.heartRateHandler?(quantity.doubleValue(for: unit), self.averageHeartRate())
})
default: return
}
}
// MARK: - Calculator
fileprivate func totalValue(_ unit: HKUnit) -> Double {
let quantities: [HKQuantitySample]
switch unit {
case context.distanceUnit:
quantities = distanceQuantities
case context.activeEnergyUnit:
quantities = activeEnergyQuantities
case context.heartRateUnit:
quantities = heartRateQuantities
default:
quantities = [HKQuantitySample]()
}
return quantities.reduce(0.0) { (value: Double, sample: HKQuantitySample) in
return value + sample.quantity.doubleValue(for: unit)
}
}
fileprivate func averageHeartRate() -> Double {
let totalHeartRate = totalValue(context.heartRateUnit)
guard totalHeartRate > 0 else { return 0.0 }
let averageHeartRate = totalHeartRate / Double(heartRateQuantities.count)
return averageHeartRate
}
// MARK: - Metadata
fileprivate func heartRateMetadata() -> [String: AnyObject] {
var metadata = [String: AnyObject]()
guard context.heartRateMetadata.count > 0 else { return metadata }
if context.heartRateMetadata.contains(.Average) {
let averageHeartRate = Int(self.averageHeartRate())
if averageHeartRate > 0 {
metadata[MetadataHeartRate.Average.rawValue] = averageHeartRate as AnyObject?
}
}
let heartRates = heartRateQuantities.map { $0.quantity.doubleValue(for: context.heartRateUnit) }
if context.heartRateMetadata.contains(.Max), let maxHeartRate = heartRates.max() {
metadata[MetadataHeartRate.Max.rawValue] = maxHeartRate as AnyObject?
}
if context.heartRateMetadata.contains(.Min), let minHeartRate = heartRates.min() {
metadata[MetadataHeartRate.Min.rawValue] = minHeartRate as AnyObject?
}
return metadata
}
#endif
}
#if os(watchOS)
extension Cardio: HKWorkoutSessionDelegate {
// MARK: - HKWorkoutSessionDelegate
public func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) {
workoutState = workoutSession.state
switch (fromState, toState) {
case (.running, .paused):
pauseWorkout(workoutSession, date: date)
case (.paused, .running):
resumeWorkout(workoutSession, date: date)
case (_, .running):
startWorkout(workoutSession, date: date)
case (_, .ended):
endWorkout(workoutSession, date: date)
default: break
}
}
public func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) {
switch workoutSession.state {
case .notStarted:
endHandler?(.failure(.noCurrentSessionError(error)))
case .running:
startHandler?(.failure(.sessionAlreadyRunningError(error)))
case .ended:
startHandler?(.failure(.cannotBeRestartedError(error)))
default: break
}
}
}
#endif
|
mit
|
bc527b05b607c2937f573038876c760f
| 36.720548 | 361 | 0.619988 | 5.238965 | false | false | false | false |
LongXiangGuo/CompressImage
|
Source/CompressImage.swift
|
1
|
4691
|
//
// CompressImage.swift
// testImage
//
// Created by longxiang on 2017/4/30.
// Copyright © 2017年 longxiang. All rights reserved.
//
import UIKit
extension UIImage {
func compress(threadhold:Int = 200 * 1024) -> (image:UIImage?,imageBase64:String?,imageData:Data?)? {
guard let orginImage = self.copy() as? UIImage else {
return nil
}
let adaptImage = self.adaptImageResolutionIfNeeded(orginImage)
guard var originImageData = UIImageJPEGRepresentation(adaptImage, 1.0) else {
return nil
}
var actualThreadhold = compressConfing.minCompressThreshold
if threadhold >= compressConfing.minCompressThreshold && threadhold <= compressConfing.maxCompressThreshold {
actualThreadhold = threadhold
}
var imageBase64 = originImageData.base64EncodedString()
var image:UIImage? = adaptImage
let originBytes = originImageData.count
let detaBytes = originBytes - actualThreadhold
if detaBytes <= 0 {
return (image:image,imageBase64:imageBase64,imageData:originImageData)
}
var notReachJPGCompressLimit = true
var needContinuteJPGCompress = true
var compressDefaultRatio = compressConfing.compressDefaultRatio
let compressStepRatio = compressConfing.compressStepRatio
while notReachJPGCompressLimit && needContinuteJPGCompress {
guard let compressImageData = UIImageJPEGRepresentation(adaptImage, compressDefaultRatio) else {
return nil
}
compressDefaultRatio = compressDefaultRatio - compressStepRatio
notReachJPGCompressLimit = (compressDefaultRatio > 0.2)
needContinuteJPGCompress = compressImageData.count > actualThreadhold
originImageData = compressImageData
}
imageBase64 = originImageData.base64EncodedString()
image = UIImage(data: originImageData)
if notReachJPGCompressLimit {
return (image:image,imageBase64:imageBase64,imageData:originImageData)
}
guard let compressImage = image else {
return nil
}
guard let sacleImage = compressImage.drawImage(size: compressImage.size, sacle: 0.95) else {
return nil
}
return sacleImage.compress(threadhold: actualThreadhold)
}
func adaptImageResolutionIfNeeded(_ image:UIImage) -> UIImage {
guard let cgImage = image.cgImage else {
return image
}
let aspectRatio = Float(cgImage.width * cgImage.height) / Float(compressConfing.resolution)
if aspectRatio < 1.0 {
return image
}
let sacleRatio = Float(sqrt(aspectRatio))
let width = Int(Float(cgImage.width) / sacleRatio )
let height = Int(Float(cgImage.height) / sacleRatio)
let bitesPerComponent = compressConfing.bitesPerComponent
let bytesPerRow = cgImage.width * compressConfing.bytesPerPixel
let pixelbufferLength = cgImage.height * bytesPerRow
let colorsapce = CGColorSpaceCreateDeviceRGB()
let bitmapData = malloc(pixelbufferLength)
let bitmapContext = CGContext(data: bitmapData,width: width,height: height,bitsPerComponent: bitesPerComponent,bytesPerRow: bytesPerRow,space: colorsapce,bitmapInfo: CGBitmapInfo.byteOrder32Big.rawValue|CGImageAlphaInfo.premultipliedLast.rawValue)
let drawRect = CGRect.init(x: 0, y: 0, width: width, height:height)
bitmapContext?.draw(cgImage, in: drawRect)
guard let newCgImage = bitmapContext?.makeImage() else {
return image
}
bitmapData?.deallocate(bytes: pixelbufferLength, alignedTo: 0)
return UIImage(cgImage: newCgImage)
}
func drawImage(size:CGSize,sacle:CGFloat = 1.0) -> UIImage? {
let actualSize = CGSize.init(width: size.width * scale, height: size.height * scale)
UIGraphicsBeginImageContext(actualSize)
self.draw(in: CGRect.init(x: 0, y: 0, width: actualSize.width, height: actualSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
return newImage
}
var compressConfing : (
bitesPerPixel:Int,
bitesPerComponent:Int,
bytesPerPixel:Int,
resolution:Int,
minCompressThreshold:Int,
maxCompressThreshold:Int,
compressDefaultRatio:CGFloat,
compressStepRatio:CGFloat
) {
return (32,8,4,1242 * 2208,200*1024,500*1024,0.99,0.01)
}
}
|
mit
|
209532fadb0cbaf0f182ee0cc20088b4
| 42.813084 | 259 | 0.655077 | 4.614173 | false | false | false | false |
steverab/WWDC-2015
|
Stephan Rabanser/AppDelegate.swift
|
1
|
1329
|
//
// AppDelegate.swift
// Stephan Rabanser
//
// Created by Stephan Rabanser on 17/04/15.
// Copyright (c) 2015 Stephan Rabanser. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// MARK: - Application lifecycle
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
NSUserDefaults.standardUserDefaults().setFloat(Float(window!.frame.size.width), forKey: "screenWidth")
return true
}
// MARK: - WatchKit request
func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]!) -> Void)!) {
if let userInfo = userInfo {
if let request = userInfo["request"] as? String {
if request == "loadEntries" {
reply(["entriesData": NSKeyedArchiver.archivedDataWithRootObject(DataLoader.loadTimelineEntries())])
return
} else if request == "loadMe" {
reply(["meData": NSKeyedArchiver.archivedDataWithRootObject(DataLoader.loadMe())])
return
}
}
}
reply([:])
}
}
|
mit
|
d720c08e00d10db51cf68c13f654d22f
| 32.225 | 161 | 0.622272 | 5.294821 | false | false | false | false |
resmio/SignificantSpices
|
SignificantSpices/Sources/SwiftExtensions/Functions/shortPrint.swift
|
1
|
1442
|
//
// shortPrint.swift
// SignificantSpices
//
// Created by Jan Nash (resmio) on 08.08.19.
// Copyright © 2019 resmio. All rights reserved.
//
import Foundation
// MARK: // Public
// MARK: Function Declarations
public func shortPrint(_ inst: Any?) {
print(shortDescription(of: inst))
}
public func shortDescription(of v: Any?) -> String {
guard let inst: Any = v else {
return "nil"
}
let additionalDesc: String = {
guard let add: String = (inst as? CustomShortStringConvertible)?.additionalShortDescription() else { return "" }
return "(" + add + ")"
}()
let typ: Any.Type = type(of: inst)
guard typ is AnyClass else {
return "\(typ)\(inst)\(additionalDesc)"
}
let object: AnyObject = inst as AnyObject
let identifierString: String = ObjectIdentifier(object).debugDescription
let prefixRemoved: String = identifierString.replacingOccurrences(of: "ObjectIdentifier(0x", with: "")
let identityString: String = prefixRemoved.replacingOccurrences(of: ")", with: "")
let range: NSRange = NSMakeRange(0, identityString.count)
let regex: NSRegularExpression = try! NSRegularExpression(pattern: "^0*", options: .caseInsensitive)
let stringWithPurgedLeadingZeroes: String = regex.stringByReplacingMatches(in: identityString, range: range, withTemplate: "")
return "<\(typ): \(stringWithPurgedLeadingZeroes)>\(additionalDesc)"
}
|
mit
|
e678e7abee8fa36a77d8b9c273315589
| 33.309524 | 130 | 0.681471 | 4.353474 | false | false | false | false |
psharanda/vmc2
|
4. MVVM/MVVM/MainViewController.swift
|
1
|
2406
|
//
// Created by Pavel Sharanda on 17.11.16.
// Copyright © 2016 psharanda. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
fileprivate lazy var button = UIButton(type: .system)
fileprivate lazy var label = UILabel()
fileprivate lazy var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
let viewModel: MainViewModelProtocol
init(viewModel: MainViewModelProtocol) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
@objc private func doneClicked() {
viewModel.detailsClicked()
}
@objc private func buttonClicked() {
viewModel.loadButtonClicked()
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
override func viewDidLoad() {
super.viewDidLoad()
title = "MVVM"
view.backgroundColor = .white
view.addSubview(activityIndicator)
button.setTitle("Load", for: .normal)
button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
view.addSubview(button)
label.numberOfLines = 0
view.addSubview(label)
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Details", style: .plain, target: self, action: #selector(doneClicked))
navigationItem.rightBarButtonItem?.isEnabled = false
loadingWasChanged(viewModel: viewModel)
textWasChanged(viewModel: viewModel)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
activityIndicator.frame = view.bounds
label.frame = UIEdgeInsetsInsetRect(view.bounds, UIEdgeInsets(top: 80, left: 20, bottom: 80, right: 20))
button.frame = CGRect(x: 20, y: view.bounds.height - 60, width: view.bounds.width - 40, height: 40)
}
}
extension MainViewController: MainViewModelDelegate {
func loadingWasChanged(viewModel: MainViewModelProtocol) {
if viewModel.loading {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
}
func textWasChanged(viewModel: MainViewModelProtocol) {
label.text = viewModel.text
navigationItem.rightBarButtonItem?.isEnabled = (viewModel.text != nil)
}
}
|
mit
|
cd5e8a01b6558a00d40e35b33a0859f8
| 28.691358 | 138 | 0.645322 | 5.172043 | false | false | false | false |
Bartlebys/Bartleby
|
Bartlebys.playground/Pages/Connected.xcplaygroundpage/Contents.swift
|
1
|
2122
|
//: [Previous](@previous)
import Alamofire
import BartlebyKit
import XCPlayground
// Prepare Bartleby
Bartleby.sharedInstance.configureWith(PlaygroundsConfiguration.self)
// Set up a BartlebyDocument
let document=BartlebyDocument()
document.configureSchema()
Bartleby.sharedInstance.declare(document)
print(document.UID)
////////////////////////////////////////////////
// We run this demo on the Dockerized Instance.
// yd.local must be setup in hosts.
////////////////////////////////////////////////
HTTPManager.apiIsReachable(document.baseURL, successHandler: {
print ("\(document.baseURL) is Reachable")
let user=document.newObject() as User
document.metadata.currentUser=user
user.creatorUID=user.UID
//////////////////////////////////
// Create the user on the server
//////////////////////////////////
CreateUser.execute(user, inDocumentWithUID: document.UID, sucessHandler: { (success) in
print("User \(user.UID) created in \(document.UID)")
user.firstname="Zorro"
///////////////
// Login
///////////////
user.login(sucessHandler: {
print("Successful login of \(user.UID) in \(document.UID)")
user.verificationMethod=User.VerificationMethod.byEmail
UpdateUser.execute(user, inDocumentWithUID: document.UID, sucessHandler: { (r) in
print("Updated User \(user.UID) created in \(document.UID) \(r.httpStatusCode ?? 0 )")
}, failureHandler: { (failure) in
print("User Update failed \(user.UID) in \(document.UID) \(failure.httpStatusCode ?? 0 )")
})
}, failureHandler: { (failure) in
print("User Login failure \(user.UID) in \(document.UID) \(failure.httpStatusCode ?? 0 ) \(failure)")
})
}) { (failure) in
print("User Creation failure \(user.UID) in \(document.UID) \(failure.httpStatusCode ?? 0 ) \(failure)")
}
}) { (context) in
print ("\(context)")
}
// Wait indefintely
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [Nex
|
apache-2.0
|
e33cc5a5d9e7a665c447ef31d23f1556
| 28.068493 | 118 | 0.586711 | 4.663736 | false | false | false | false |
erusso1/ERNiftyFoundation
|
ERNiftyFoundation/Source/Classes/ERDateIntervalFormatter.swift
|
1
|
1293
|
//
// ERDateIntervalFormatter.swift
//
// Created by Ephraim Russo on 10/24/17.
//
import Foundation
import Unbox
public enum ERDateIntervalFormatterType {
case milliseconds
case seconds
}
public struct ERDateIntervalFormatter {
public static var formatterType: ERDateIntervalFormatterType = .milliseconds
public init() {
}
}
extension ERDateIntervalFormatter: UnboxFormatter {
public typealias UnboxRawValue = TimeInterval
public typealias UnboxFormattedType = Date
public func format(unboxedValue: TimeInterval) -> Date? {
let interval: TimeInterval
switch ERDateIntervalFormatter.formatterType {
case .milliseconds: interval = (unboxedValue / 1000.0)
case .seconds: interval = unboxedValue
}
return Date(timeIntervalSince1970: interval)
}
}
extension UnboxFormatter {
public static var milliseconds: ERDateIntervalFormatter {
ERDateIntervalFormatter.formatterType = .milliseconds
return ERDateIntervalFormatter()
}
public static var seconds: ERDateIntervalFormatter {
ERDateIntervalFormatter.formatterType = .seconds
return ERDateIntervalFormatter()
}
}
|
mit
|
a3cdd194290ab243dd3c2d272ad64ce1
| 20.55 | 80 | 0.672854 | 5.365145 | false | false | false | false |
rajeshmud/CLChart
|
CLApp/LineViewController.swift
|
1
|
17483
|
//
// LineViewController.swift
// TestApp
//
// Created by Rajesh Mudaliyar on 02/10/15.
// Copyright © 2015 Rajesh Mudaliyar. All rights reserved.
//
import UIKit
import CLCharts
class LineViewController: UIViewController {
private var chart: Chart?
let sideSelectorHeight: CGFloat = 50
var mbMml:Bool = true
var fileName:String = "json"
var breakedLinesArray = NSMutableArray(capacity: 1)
private let useViewsLayer = true
var chartBubblePoints: [CLPointBubble] = [CLPointBubble(point: (ChartPoint(x: CLAxisValue(scalar: 0),y: CLAxisValue(scalar: 0))))]
@IBOutlet weak var line: UIView!
override func viewDidLoad() {
super.viewDidLoad()
DrawLine("json")
if let _ = self.chart {
let sideSelector = DirSelector(frame: CGRectMake(90, 80, 100, self.sideSelectorHeight), controller: self,title1: "D1",title2: "D2")
let sideSelector1 = DirSelector(frame: CGRectMake(160, 80, self.view.frame.size.width, self.sideSelectorHeight), controller: self,title1: "D3",title2: "D4")
let sideSelector2 = DirSelector(frame: CGRectMake(225, 80, self.view.frame.size.width, self.sideSelectorHeight), controller: self,title1: "D5",title2: "D6")
let sideSelector3 = DirSelector(frame: CGRectMake(290, 80, self.view.frame.size.width, self.sideSelectorHeight), controller: self,title1: "D7",title2: "D8")
sideSelector.fileName1 = "json"
sideSelector.fileName2 = "xyjson"
sideSelector1.fileName1 = "json1"
sideSelector1.fileName2 = "xyjson1"
sideSelector2.fileName1 = "json96points1"
sideSelector2.fileName2 = "json96points2"
sideSelector3.fileName1 = "jsondis"
sideSelector3.fileName2 = "xyjsondis"
let pointSelector = PointSelector(frame: CGRectMake(0, 80, 130, self.sideSelectorHeight), controller: self)
self.view.addSubview(pointSelector)
self.view.addSubview(sideSelector)
self.view.addSubview(sideSelector1)
self.view.addSubview(sideSelector2)
self.view.addSubview(sideSelector3)
}
}
internal class AB {
var a:Int = 0
var b:Int = 0
internal init(a:Int,b:Int) {
self.a = a
self.b = b
}
}
func DrawLine(jsonFile:String) {
let labelSettings = CLLabelSettings(font: CLDefaults.labelFont)
var chartPoints = json(jsonFile)
var factor:CGFloat = 1.0
var yTitle:String = "Unit1"
var lineFactor:Float = 1.0
if !mbMml {
factor = 18
yTitle = "Unit2"
lineFactor = 0.2
}
let xValues = 0.stride(through: 24, by: 2).map {CLAxisValueInt($0, labelSettings: labelSettings)}
let yValues = CLAxisValuesGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 7, maxSegmentCount: Double(350/factor), multiple: Double(50/factor), axisValueGenerator: {CLAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false)
let xModel = CLAxisModel(axisValues: xValues, axisTitleLabel: CLAxisLabel(text: "24 hours chart", settings: labelSettings))
let yModel = CLAxisModel(axisValues: yValues, axisTitleLabel: CLAxisLabel(text:yTitle, settings: labelSettings.defaultVertical()))
let chartFrame = CLDefaults.chartFrame(self.view.bounds)
let coordsSpace = CLCoordsSpaceLeftBottomSingleAxis(chartSettings: CLDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let borderP1 = ChartPoint(x: CLAxisValueInt(24, labelSettings: labelSettings), y: CLAxisValueDouble(Double(0/factor)))
let borderP2 = ChartPoint(x: CLAxisValueInt(24, labelSettings: labelSettings), y: CLAxisValueDouble(Double(350/factor)))
let borderLine = [borderP1,borderP2]
var TargetBand:[ChartPoint] = [ChartPoint(x: CLAxisValueDouble(0, labelSettings: labelSettings), y: CLAxisValueDouble(Double(100/factor))),ChartPoint(x: CLAxisValueInt(24, labelSettings: labelSettings), y: CLAxisValueDouble(Double(100/factor)))]
for var index = Float(103/factor); index < Float(140/factor); index = index + lineFactor{
TargetBand.append(ChartPoint(x: CLAxisValueDouble(0, labelSettings: labelSettings), y: CLAxisValueDouble(Double(index))))
TargetBand.append(ChartPoint(x: CLAxisValueInt(24, labelSettings: labelSettings), y: CLAxisValueDouble(Double(index))))
}
let lineLowTargetModel = CLLineModel(chartPoints:TargetBand, lineColor: UIColor(red:0.5,green:0.5, blue:0.5, alpha:0.5), lineWidth: 4, animDuration: 0, animDelay: 0)
let lineLowTargetLineLayer = CLPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineLowTargetModel])//, pathGenerator: CubicLinePathGenerator())
let borderModel = CLLineModel(chartPoints:borderLine, lineColor: UIColor.blackColor(), lineWidth: 0.7, animDuration: 0, animDelay: 0)
let borderModelLineLayer = CLPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [borderModel])//, pathGenerator: CubicLinePathGenerator())
chartPoints = breakedLinesArray.objectAtIndex(0) as! [ChartPoint]
var chartPoints2 = chartPoints
let lineModel = CLLineModel(chartPoints: chartPoints, lineColor: UIColor.purpleColor(), lineWidth: 2, animDuration: 1, animDelay: 0)
let chartPointsLineLayer = CLPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel], pathGenerator: CubicLinePathGenerator())
var lineModel1 = lineModel
var chartPointsLineLayer2 = chartPointsLineLayer
if breakedLinesArray.count > 1 {
chartPoints2.removeAll()
chartPoints2 = breakedLinesArray.objectAtIndex(1) as! [ChartPoint]
lineModel1 = CLLineModel(chartPoints: chartPoints2, lineColor: UIColor.purpleColor(), lineWidth: 2, animDuration: 1, animDelay: 0)
chartPointsLineLayer2 = CLPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel1], pathGenerator: CubicLinePathGenerator())
}
let bubbleLayer = self.bubblesLayer(xAxis: xAxis, yAxis: yAxis, chartInnerFrame: innerFrame, chartPoints: chartBubblePoints)
let trackerLayerSettings = CLPointsLineTrackerLayerSettings(thumbSize: Env.iPad ? 30 : 15, thumbCornerRadius: Env.iPad ? 8 : 4, thumbBorderWidth: Env.iPad ? 4 : 2, infoViewFont: CLDefaults.fontWithSize(Env.iPad ? 26 : 16), infoViewSize: CGSizeMake(Env.iPad ? 400 : 230, Env.iPad ? 70 : 20), infoViewCornerRadius: Env.iPad ? 30 : 15)
let chartPointsTrackerLayer = CLPointsLineTrackerLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, lineColor: UIColor.blackColor(), animDuration: 1, animDelay: 2, settings: trackerLayerSettings)
let settings = CLGuideLinesDottedLayerSettings(linesColor: UIColor.blackColor(), linesWidth: CLDefaults.guidelinesWidth)
let guidelinesLayer = CLGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings)
let chart = Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
lineLowTargetLineLayer,
guidelinesLayer,
borderModelLineLayer,
chartPointsLineLayer,
bubbleLayer,
chartPointsLineLayer2,
chartPointsTrackerLayer
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
private func bubblesLayer(xAxis xAxis: CLAxisLayer, yAxis: CLAxisLayer, chartInnerFrame: CGRect, chartPoints: [CLPointBubble]) -> CLLayer {
let _: Double = 30, _: Double = 2
if self.useViewsLayer == true {
let (_, _): (Double, Double) = chartPoints.reduce((min: 0, max: 0)) {tuple, chartPoint in
(min: min(tuple.min, chartPoint.diameterScalar), max: max(tuple.max, chartPoint.diameterScalar))
}
return CLPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: chartInnerFrame, chartPoints: chartPoints, viewGenerator: {(chartPointModel, layer, chart) -> UIView? in
let diameter = CGFloat(10)//CGFloat(chartPointModel.chartPoint.diameterScalar * diameterFactor)
let circleView = CLPointEllipseView(center: chartPointModel.screenLoc, diameter: diameter)
circleView.fillColor = chartPointModel.chartPoint.bgColor
circleView.borderColor = UIColor.blackColor().colorWithAlphaComponent(0.6)
circleView.borderWidth = 1
circleView.animDelay = Float(chartPointModel.index) * 0.2
circleView.animDuration = 1.2
circleView.animDamping = 0.4
circleView.animInitSpringVelocity = 0.5
return circleView
})
} else {
return CLPointsBubbleLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: chartInnerFrame, chartPoints: chartPoints)
}
}
func json(fileName:String)->[ChartPoint] {
let labelSettings = CLLabelSettings(font: CLDefaults.labelFont)
let p1 = ChartPoint(x: CLAxisValueInt(0, labelSettings: labelSettings), y: CLAxisValueInt(0))
var points:[ChartPoint] = [p1]
var noOfArray = -1
var newline = true
chartBubblePoints.removeAll()
breakedLinesArray.removeAllObjects()
var jsonResult:NSArray! = NSArray()
do{
let path = NSBundle.mainBundle().pathForResource(fileName, ofType: "json")
let jsonData = NSData(contentsOfFile: path!)
jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonData! , options: NSJSONReadingOptions.MutableContainers) as! NSArray
chartBubblePoints.removeAll()
for i in 0...jsonResult.count - 1
{
var factor:CGFloat = 1.0
if !mbMml {factor = 18}
let x = CGFloat(((jsonResult[i].valueForKey("time"))?.floatValue)!)
let y = CGFloat(((jsonResult[i].valueForKey("gValue"))?.floatValue)!)/factor
if y == -1/factor {
newline = true
points.removeAll()
} else {
if newline {
points.removeAll()
noOfArray++
newline = false
breakedLinesArray.addObject(points)
}
let point = ChartPoint(x: CLAxisValueFloat(x, labelSettings: labelSettings), y: CLAxisValueFloat(y))
var arr = breakedLinesArray.objectAtIndex(noOfArray) as! [ChartPoint]
arr.append(point)
points.append(point)
breakedLinesArray.replaceObjectAtIndex(noOfArray, withObject: points)
if y < 75/factor {
chartBubblePoints.append(CLPointBubble(point: point,diameterScalar: 20,bgColor: UIColor(red: 0.8, green: 0.0, blue: 0.0, alpha: 0.7)))
} else if y > 200/factor {
chartBubblePoints.append(CLPointBubble(point: point,diameterScalar: 20,bgColor: UIColor(red: 0.8, green: 0.5, blue: 0.0, alpha: 0.7)))
}
}
}
} catch let error as NSError {
print(error)
}
return points
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
class DirSelector: UIView {
let dataSet1: UIButton
let dataSet2: UIButton
var title1: String = "but1"
var title2: String = "but2"
var fileName1: String = "1"
var fileName2: String = "2"
weak var controller: LineViewController?
private let buttonDirs: [UIButton : Bool]
init(frame: CGRect, controller: LineViewController,title1: String,title2: String) {
self.controller = controller
self.dataSet1 = UIButton()
self.dataSet1.setTitle(title1, forState: .Normal)
self.dataSet2 = UIButton()
self.dataSet2.setTitle(title2, forState: .Normal)
self.buttonDirs = [self.dataSet1 : true, self.dataSet2 : false]
super.init(frame: frame)
self.addSubview(self.dataSet1)
self.addSubview(self.dataSet2)
for button in [self.dataSet1, self.dataSet2] {
button.titleLabel?.font = CLDefaults.fontWithSize(14)
button.setTitleColor(UIColor.blueColor(), forState: .Normal)
button.addTarget(self, action: "buttonTapped:", forControlEvents: .TouchUpInside)
}
}
func buttonTapped(sender: UIButton) {
controller?.chart!.clearView()
if (sender == self.dataSet1) {
controller!.fileName = fileName1
}else {
controller!.fileName = fileName2
}
controller!.DrawLine(controller!.fileName)
}
override func didMoveToSuperview() {
let views = [self.dataSet1, self.dataSet2]
for v in views {
v.translatesAutoresizingMaskIntoConstraints = false
}
let namedViews = views.enumerate().map{index, view in
("v\(index)", view)
}
let viewsDict = namedViews.reduce(Dictionary<String, UIView>()) {(var u, tuple) in
u[tuple.0] = tuple.1
return u
}
let buttonsSpace: CGFloat = Env.iPad ? 20 : 4
let hConstraintStr = namedViews.reduce("H:|") {str, tuple in
"\(str)-(\(buttonsSpace))-[\(tuple.0)]"
}
let vConstraits = namedViews.flatMap {NSLayoutConstraint.constraintsWithVisualFormat("V:|[\($0.0)]", options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict)}
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(hConstraintStr, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict)
+ vConstraits)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class PointSelector: UIView {
let mmo: UIButton
let mml: UIButton
weak var controller: LineViewController?
private let buttonDirs: [UIButton : Bool]
init(frame: CGRect, controller: LineViewController) {
self.controller = controller
self.mmo = UIButton()
self.mmo.setTitle("Unit2", forState: .Normal)
self.mml = UIButton()
self.mml.setTitle("Unit1", forState: .Normal)
self.buttonDirs = [self.mmo : true, self.mml : false]
super.init(frame: frame)
self.addSubview(self.mmo)
self.addSubview(self.mml)
for button in [self.mmo, self.mml] {
button.titleLabel?.font = CLDefaults.fontWithSize(14)
button.setTitleColor(UIColor.blueColor(), forState: .Normal)
button.addTarget(self, action: "buttonTapped:", forControlEvents: .TouchUpInside)
}
}
func buttonTapped(sender: UIButton) {
controller?.chart!.clearView()
if (sender == self.mmo) {
controller!.mbMml = false
self.mmo.setTitle("Unit2", forState: .Normal)
self.mml.setTitle("Unit1", forState: .Normal)
}else {
controller!.mbMml = true
self.mml.setTitle("Unit1", forState: .Normal)
self.mmo.setTitle("Unit2", forState: .Normal)
}
controller!.DrawLine(controller!.fileName)
}
override func didMoveToSuperview() {
let views = [self.mmo, self.mml]
for v in views {
v.translatesAutoresizingMaskIntoConstraints = false
}
let namedViews = views.enumerate().map{index, view in
("v\(index)", view)
}
let viewsDict = namedViews.reduce(Dictionary<String, UIView>()) {(var u, tuple) in
u[tuple.0] = tuple.1
return u
}
let buttonsSpace: CGFloat = Env.iPad ? 20 : 10
let hConstraintStr = namedViews.reduce("H:|") {str, tuple in
"\(str)-(\(buttonsSpace))-[\(tuple.0)]"
}
let vConstraits = namedViews.flatMap {NSLayoutConstraint.constraintsWithVisualFormat("V:|[\($0.0)]", options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict)}
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(hConstraintStr, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict)
+ vConstraits)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
|
mit
|
d6adf00aaeb91ba0c34136d399f176e0
| 49.235632 | 340 | 0.62041 | 4.626092 | false | false | false | false |
flypaper0/ethereum-wallet
|
ethereum-wallet/Classes/PresentationLayer/Wallet/TabBar/Module/TabBarModule.swift
|
1
|
1195
|
// Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import UIKit
class TabBarModule {
class func create(app: Application, isSecureMode: Bool) -> TabBarModuleInput {
let router = TabBarRouter()
let presenter = TabBarPresenter()
let interactor = TabBarInteractor()
let viewController = R.storyboard.tabBar.tabBarViewController()!
let core = Ethereum.core
if isSecureMode {
let keystore = KeystoreService()
let syncCoordinator = LesSyncCoordinator(context: core.context, keystore: keystore)
core.syncCoordinator = syncCoordinator
interactor.ethereumService = core
} else {
let syncCoordinator = StandardSyncCoordinator()
core.syncCoordinator = syncCoordinator
interactor.ethereumService = core
}
interactor.output = presenter
interactor.walletDataStoreService = WalletDataStoreService()
interactor.transactionsDataStoreServise = TransactionsDataStoreService()
viewController.output = presenter
presenter.view = viewController
presenter.router = router
presenter.interactor = interactor
router.app = app
return presenter
}
}
|
gpl-3.0
|
afd356187763d6b9ea75c9b42ebffc26
| 27.428571 | 89 | 0.721943 | 5.168831 | false | false | false | false |
Loannes/Swift3-OperationQueue
|
Swift3-OperationQueue/ViewController.swift
|
1
|
2877
|
//
// ViewController.swift
// Swift3-OperationQueue
//
// Created by dev_sinu on 2016. 12. 26..
// Copyright © 2016년 dev_sinu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var label3: UILabel!
@IBOutlet weak var label4: UILabel!
@IBOutlet weak var label5: UILabel!
var num = 0
let queue = CustomQueue()
let container: UIView = UIView()
// MARK: 블럭 사용 operationQueue 함수
@IBAction func startOP(_ sender: Any) {
for _ in 1...5 {
queue.addTask(task: task)
}
}
@IBAction func resetLable(_ sender: Any) {
self.label1.text = "작업 대기중..."
self.label2.text = "작업 대기중..."
self.label3.text = "작업 대기중..."
self.label4.text = "작업 대기중..."
self.label5.text = "작업 대기중..."
num = 0
}
func task() {
num += 1
if num == 1 {
DispatchQueue.main.async(execute: {
self.label1.text = "작업중..."
})
Thread.sleep(forTimeInterval: 1.0)
DispatchQueue.main.async(execute: {
self.label1.text = "작업 완료"
})
}else if num == 2 {
DispatchQueue.main.async(execute: {
self.label2.text = "작업중..."
})
Thread.sleep(forTimeInterval: 1.0)
DispatchQueue.main.async(execute: {
self.label2.text = "작업 완료"
})
}else if num == 3 {
DispatchQueue.main.async(execute: {
self.label3.text = "작업중..."
})
Thread.sleep(forTimeInterval: 5.0)
DispatchQueue.main.async(execute: {
self.label3.text = "작업 완료"
})
}else if num == 4 {
DispatchQueue.main.async(execute: {
self.label4.text = "작업중..."
})
Thread.sleep(forTimeInterval: 1.0)
DispatchQueue.main.async(execute: {
self.label4.text = "작업 완료"
})
}else if num == 5 {
DispatchQueue.main.async(execute: {
self.label5.text = "작업중..."
})
Thread.sleep(forTimeInterval: 1.0)
DispatchQueue.main.async(execute: {
self.label5.text = "작업 완료"
})
}
}
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
|
06e7eab93d66f4dbd8272b8f8f14abcd
| 27.863158 | 80 | 0.513494 | 3.751026 | false | false | false | false |
xwu/swift
|
stdlib/public/core/UnsafePointer.swift
|
4
|
42401
|
//===--- UnsafePointer.swift ----------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A pointer for accessing data of a
/// specific type.
///
/// You use instances of the `UnsafePointer` type to access data of a
/// specific type in memory. The type of data that a pointer can access is the
/// pointer's `Pointee` type. `UnsafePointer` provides no automated
/// memory management or alignment guarantees. You are responsible for
/// handling the life cycle of any memory you work with through unsafe
/// pointers to avoid leaks or undefined behavior.
///
/// Memory that you manually manage can be either *untyped* or *bound* to a
/// specific type. You use the `UnsafePointer` type to access and
/// manage memory that has been bound to a specific type.
///
/// Understanding a Pointer's Memory State
/// ======================================
///
/// The memory referenced by an `UnsafePointer` instance can be in
/// one of several states. Many pointer operations must only be applied to
/// pointers with memory in a specific state---you must keep track of the
/// state of the memory you are working with and understand the changes to
/// that state that different operations perform. Memory can be untyped and
/// uninitialized, bound to a type and uninitialized, or bound to a type and
/// initialized to a value. Finally, memory that was allocated previously may
/// have been deallocated, leaving existing pointers referencing unallocated
/// memory.
///
/// Uninitialized Memory
/// --------------------
///
/// Memory that has just been allocated through a typed pointer or has been
/// deinitialized is in an *uninitialized* state. Uninitialized memory must be
/// initialized before it can be accessed for reading.
///
/// Initialized Memory
/// ------------------
///
/// *Initialized* memory has a value that can be read using a pointer's
/// `pointee` property or through subscript notation. In the following
/// example, `ptr` is a pointer to memory initialized with a value of `23`:
///
/// let ptr: UnsafePointer<Int> = ...
/// // ptr.pointee == 23
/// // ptr[0] == 23
///
/// Accessing a Pointer's Memory as a Different Type
/// ================================================
///
/// When you access memory through an `UnsafePointer` instance, the
/// `Pointee` type must be consistent with the bound type of the memory. If
/// you do need to access memory that is bound to one type as a different
/// type, Swift's pointer types provide type-safe ways to temporarily or
/// permanently change the bound type of the memory, or to load typed
/// instances directly from raw memory.
///
/// An `UnsafePointer<UInt8>` instance allocated with eight bytes of
/// memory, `uint8Pointer`, will be used for the examples below.
///
/// let uint8Pointer: UnsafePointer<UInt8> = fetchEightBytes()
///
/// When you only need to temporarily access a pointer's memory as a different
/// type, use the `withMemoryRebound(to:capacity:)` method. For example, you
/// can use this method to call an API that expects a pointer to a different
/// type that is layout compatible with your pointer's `Pointee`. The following
/// code temporarily rebinds the memory that `uint8Pointer` references from
/// `UInt8` to `Int8` to call the imported C `strlen` function.
///
/// // Imported from C
/// func strlen(_ __s: UnsafePointer<Int8>!) -> UInt
///
/// let length = uint8Pointer.withMemoryRebound(to: Int8.self, capacity: 8) {
/// return strlen($0)
/// }
/// // length == 7
///
/// When you need to permanently rebind memory to a different type, first
/// obtain a raw pointer to the memory and then call the
/// `bindMemory(to:capacity:)` method on the raw pointer. The following
/// example binds the memory referenced by `uint8Pointer` to one instance of
/// the `UInt64` type:
///
/// let uint64Pointer = UnsafeRawPointer(uint8Pointer)
/// .bindMemory(to: UInt64.self, capacity: 1)
///
/// After rebinding the memory referenced by `uint8Pointer` to `UInt64`,
/// accessing that pointer's referenced memory as a `UInt8` instance is
/// undefined.
///
/// var fullInteger = uint64Pointer.pointee // OK
/// var firstByte = uint8Pointer.pointee // undefined
///
/// Alternatively, you can access the same memory as a different type without
/// rebinding through untyped memory access, so long as the bound type and the
/// destination type are trivial types. Convert your pointer to an
/// `UnsafeRawPointer` instance and then use the raw pointer's
/// `load(fromByteOffset:as:)` method to read values.
///
/// let rawPointer = UnsafeRawPointer(uint64Pointer)
/// let fullInteger = rawPointer.load(as: UInt64.self) // OK
/// let firstByte = rawPointer.load(as: UInt8.self) // OK
///
/// Performing Typed Pointer Arithmetic
/// ===================================
///
/// Pointer arithmetic with a typed pointer is counted in strides of the
/// pointer's `Pointee` type. When you add to or subtract from an `UnsafePointer`
/// instance, the result is a new pointer of the same type, offset by that
/// number of instances of the `Pointee` type.
///
/// // 'intPointer' points to memory initialized with [10, 20, 30, 40]
/// let intPointer: UnsafePointer<Int> = ...
///
/// // Load the first value in memory
/// let x = intPointer.pointee
/// // x == 10
///
/// // Load the third value in memory
/// let offsetPointer = intPointer + 2
/// let y = offsetPointer.pointee
/// // y == 30
///
/// You can also use subscript notation to access the value in memory at a
/// specific offset.
///
/// let z = intPointer[2]
/// // z == 30
///
/// Implicit Casting and Bridging
/// =============================
///
/// When calling a function or method with an `UnsafePointer` parameter, you can pass
/// an instance of that specific pointer type, pass an instance of a
/// compatible pointer type, or use Swift's implicit bridging to pass a
/// compatible pointer.
///
/// For example, the `printInt(atAddress:)` function in the following code
/// sample expects an `UnsafePointer<Int>` instance as its first parameter:
///
/// func printInt(atAddress p: UnsafePointer<Int>) {
/// print(p.pointee)
/// }
///
/// As is typical in Swift, you can call the `printInt(atAddress:)` function
/// with an `UnsafePointer` instance. This example passes `intPointer`, a pointer to
/// an `Int` value, to `print(address:)`.
///
/// printInt(atAddress: intPointer)
/// // Prints "42"
///
/// Because a mutable typed pointer can be implicitly cast to an immutable
/// pointer with the same `Pointee` type when passed as a parameter, you can
/// also call `printInt(atAddress:)` with an `UnsafeMutablePointer` instance.
///
/// let mutableIntPointer = UnsafeMutablePointer(mutating: intPointer)
/// printInt(atAddress: mutableIntPointer)
/// // Prints "42"
///
/// Alternatively, you can use Swift's *implicit bridging* to pass a pointer to
/// an instance or to the elements of an array. The following example passes a
/// pointer to the `value` variable by using inout syntax:
///
/// var value: Int = 23
/// printInt(atAddress: &value)
/// // Prints "23"
///
/// An immutable pointer to the elements of an array is implicitly created when
/// you pass the array as an argument. This example uses implicit bridging to
/// pass a pointer to the elements of `numbers` when calling
/// `printInt(atAddress:)`.
///
/// let numbers = [5, 10, 15, 20]
/// printInt(atAddress: numbers)
/// // Prints "5"
///
/// You can also use inout syntax to pass a mutable pointer to the elements of
/// an array. Because `printInt(atAddress:)` requires an immutable pointer,
/// although this is syntactically valid, it isn't necessary.
///
/// var mutableNumbers = numbers
/// printInt(atAddress: &mutableNumbers)
///
/// No matter which way you call `printInt(atAddress:)`, Swift's type safety
/// guarantees that you can only pass a pointer to the type required by the
/// function---in this case, a pointer to an `Int`.
///
/// - Important: The pointer created through implicit bridging of an instance
/// or of an array's elements is only valid during the execution of the
/// called function. Escaping the pointer to use after the execution of the
/// function is undefined behavior. In particular, do not use implicit
/// bridging when calling an `UnsafePointer` initializer.
///
/// var number = 5
/// let numberPointer = UnsafePointer<Int>(&number)
/// // Accessing 'numberPointer' is undefined behavior.
@frozen // unsafe-performance
public struct UnsafePointer<Pointee>: _Pointer, Sendable {
/// A type that represents the distance between two pointers.
public typealias Distance = Int
/// The underlying raw (untyped) pointer.
public let _rawValue: Builtin.RawPointer
/// Creates an `UnsafePointer` from a builtin raw pointer.
@_transparent
public init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Deallocates the memory block previously allocated at this pointer.
///
/// This pointer must be a pointer to the start of a previously allocated memory
/// block. The memory must not be initialized or `Pointee` must be a trivial type.
@inlinable
public func deallocate() {
// Passing zero alignment to the runtime forces "aligned
// deallocation". Since allocation via `UnsafeMutable[Raw][Buffer]Pointer`
// always uses the "aligned allocation" path, this ensures that the
// runtime's allocation and deallocation paths are compatible.
Builtin.deallocRaw(_rawValue, (-1)._builtinWordValue, (0)._builtinWordValue)
}
/// Accesses the instance referenced by this pointer.
///
/// When reading from the `pointee` property, the instance referenced by
/// this pointer must already be initialized.
@inlinable // unsafe-performance
public var pointee: Pointee {
@_transparent unsafeAddress {
return self
}
}
/// Executes the given closure while temporarily binding the specified number
/// of instances to the given type.
///
/// Use this method when you have a pointer to memory bound to one type and
/// you need to access that memory as instances of another type. Accessing
/// memory as a type `T` requires that the memory be bound to that type. A
/// memory location may only be bound to one type at a time, so accessing
/// the same memory as an unrelated type without first rebinding the memory
/// is undefined.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized.
///
/// The following example temporarily rebinds the memory of a `UInt64`
/// pointer to `Int64`, then accesses a property on the signed integer.
///
/// let uint64Pointer: UnsafePointer<UInt64> = fetchValue()
/// let isNegative = uint64Pointer.withMemoryRebound(to: Int64.self, capacity: 1) { ptr in
/// return ptr.pointee < 0
/// }
///
/// Because this pointer's memory is no longer bound to its `Pointee` type
/// while the `body` closure executes, do not access memory using the
/// original pointer from within `body`. Instead, use the `body` closure's
/// pointer argument to access the values in memory as instances of type
/// `T`.
///
/// After executing `body`, this method rebinds memory back to the original
/// `Pointee` type.
///
/// - Note: Only use this method to rebind the pointer's memory to a type
/// with the same size and stride as the currently bound `Pointee` type.
/// To bind a region of memory to a type that is a different size, convert
/// the pointer to a raw pointer and use the `bindMemory(to:capacity:)`
/// method.
///
/// - Parameters:
/// - type: The type to temporarily bind the memory referenced by this
/// pointer. The type `T` must be the same size and be layout compatible
/// with the pointer's `Pointee` type.
/// - count: The number of instances of `Pointee` to bind to `type`.
/// - body: A closure that takes a typed pointer to the
/// same memory as this pointer, only bound to type `T`. The closure's
/// pointer argument is valid only for the duration of the closure's
/// execution. If `body` has a return value, that value is also used as
/// the return value for the `withMemoryRebound(to:capacity:_:)` method.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public func withMemoryRebound<T, Result>(to type: T.Type, capacity count: Int,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result {
Builtin.bindMemory(_rawValue, count._builtinWordValue, T.self)
defer {
Builtin.bindMemory(_rawValue, count._builtinWordValue, Pointee.self)
}
return try body(UnsafePointer<T>(_rawValue))
}
/// Accesses the pointee at the specified offset from this pointer.
///
///
/// For a pointer `p`, the memory at `p + i` must be initialized.
///
/// - Parameter i: The offset from this pointer at which to access an
/// instance, measured in strides of the pointer's `Pointee` type.
@inlinable
public subscript(i: Int) -> Pointee {
@_transparent
unsafeAddress {
return self + i
}
}
@inlinable // unsafe-performance
internal static var _max: UnsafePointer {
return UnsafePointer(
bitPattern: 0 as Int &- MemoryLayout<Pointee>.stride
)._unsafelyUnwrappedUnchecked
}
}
/// A pointer for accessing and manipulating data of a
/// specific type.
///
/// You use instances of the `UnsafeMutablePointer` type to access data of a
/// specific type in memory. The type of data that a pointer can access is the
/// pointer's `Pointee` type. `UnsafeMutablePointer` provides no automated
/// memory management or alignment guarantees. You are responsible for
/// handling the life cycle of any memory you work with through unsafe
/// pointers to avoid leaks or undefined behavior.
///
/// Memory that you manually manage can be either *untyped* or *bound* to a
/// specific type. You use the `UnsafeMutablePointer` type to access and
/// manage memory that has been bound to a specific type.
///
/// Understanding a Pointer's Memory State
/// ======================================
///
/// The memory referenced by an `UnsafeMutablePointer` instance can be in
/// one of several states. Many pointer operations must only be applied to
/// pointers with memory in a specific state---you must keep track of the
/// state of the memory you are working with and understand the changes to
/// that state that different operations perform. Memory can be untyped and
/// uninitialized, bound to a type and uninitialized, or bound to a type and
/// initialized to a value. Finally, memory that was allocated previously may
/// have been deallocated, leaving existing pointers referencing unallocated
/// memory.
///
/// Uninitialized Memory
/// --------------------
///
/// Memory that has just been allocated through a typed pointer or has been
/// deinitialized is in an *uninitialized* state. Uninitialized memory must be
/// initialized before it can be accessed for reading.
///
/// You can use methods like `initialize(repeating:count:)`, `initialize(from:count:)`,
/// and `moveInitialize(from:count:)` to initialize the memory referenced by a
/// pointer with a value or series of values.
///
/// Initialized Memory
/// ------------------
///
/// *Initialized* memory has a value that can be read using a pointer's
/// `pointee` property or through subscript notation. In the following
/// example, `ptr` is a pointer to memory initialized with a value of `23`:
///
/// let ptr: UnsafeMutablePointer<Int> = ...
/// // ptr.pointee == 23
/// // ptr[0] == 23
///
/// Accessing a Pointer's Memory as a Different Type
/// ================================================
///
/// When you access memory through an `UnsafeMutablePointer` instance, the
/// `Pointee` type must be consistent with the bound type of the memory. If
/// you do need to access memory that is bound to one type as a different
/// type, Swift's pointer types provide type-safe ways to temporarily or
/// permanently change the bound type of the memory, or to load typed
/// instances directly from raw memory.
///
/// An `UnsafeMutablePointer<UInt8>` instance allocated with eight bytes of
/// memory, `uint8Pointer`, will be used for the examples below.
///
/// var bytes: [UInt8] = [39, 77, 111, 111, 102, 33, 39, 0]
/// let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 8)
/// uint8Pointer.initialize(from: &bytes, count: 8)
///
/// When you only need to temporarily access a pointer's memory as a different
/// type, use the `withMemoryRebound(to:capacity:)` method. For example, you
/// can use this method to call an API that expects a pointer to a different
/// type that is layout compatible with your pointer's `Pointee`. The following
/// code temporarily rebinds the memory that `uint8Pointer` references from
/// `UInt8` to `Int8` to call the imported C `strlen` function.
///
/// // Imported from C
/// func strlen(_ __s: UnsafePointer<Int8>!) -> UInt
///
/// let length = uint8Pointer.withMemoryRebound(to: Int8.self, capacity: 8) {
/// return strlen($0)
/// }
/// // length == 7
///
/// When you need to permanently rebind memory to a different type, first
/// obtain a raw pointer to the memory and then call the
/// `bindMemory(to:capacity:)` method on the raw pointer. The following
/// example binds the memory referenced by `uint8Pointer` to one instance of
/// the `UInt64` type:
///
/// let uint64Pointer = UnsafeMutableRawPointer(uint8Pointer)
/// .bindMemory(to: UInt64.self, capacity: 1)
///
/// After rebinding the memory referenced by `uint8Pointer` to `UInt64`,
/// accessing that pointer's referenced memory as a `UInt8` instance is
/// undefined.
///
/// var fullInteger = uint64Pointer.pointee // OK
/// var firstByte = uint8Pointer.pointee // undefined
///
/// Alternatively, you can access the same memory as a different type without
/// rebinding through untyped memory access, so long as the bound type and the
/// destination type are trivial types. Convert your pointer to an
/// `UnsafeMutableRawPointer` instance and then use the raw pointer's
/// `load(fromByteOffset:as:)` and `storeBytes(of:toByteOffset:as:)` methods
/// to read and write values.
///
/// let rawPointer = UnsafeMutableRawPointer(uint64Pointer)
/// let fullInteger = rawPointer.load(as: UInt64.self) // OK
/// let firstByte = rawPointer.load(as: UInt8.self) // OK
///
/// Performing Typed Pointer Arithmetic
/// ===================================
///
/// Pointer arithmetic with a typed pointer is counted in strides of the
/// pointer's `Pointee` type. When you add to or subtract from an `UnsafeMutablePointer`
/// instance, the result is a new pointer of the same type, offset by that
/// number of instances of the `Pointee` type.
///
/// // 'intPointer' points to memory initialized with [10, 20, 30, 40]
/// let intPointer: UnsafeMutablePointer<Int> = ...
///
/// // Load the first value in memory
/// let x = intPointer.pointee
/// // x == 10
///
/// // Load the third value in memory
/// let offsetPointer = intPointer + 2
/// let y = offsetPointer.pointee
/// // y == 30
///
/// You can also use subscript notation to access the value in memory at a
/// specific offset.
///
/// let z = intPointer[2]
/// // z == 30
///
/// Implicit Casting and Bridging
/// =============================
///
/// When calling a function or method with an `UnsafeMutablePointer` parameter, you can pass
/// an instance of that specific pointer type or use Swift's implicit bridging
/// to pass a compatible pointer.
///
/// For example, the `printInt(atAddress:)` function in the following code
/// sample expects an `UnsafeMutablePointer<Int>` instance as its first parameter:
///
/// func printInt(atAddress p: UnsafeMutablePointer<Int>) {
/// print(p.pointee)
/// }
///
/// As is typical in Swift, you can call the `printInt(atAddress:)` function
/// with an `UnsafeMutablePointer` instance. This example passes `intPointer`, a mutable
/// pointer to an `Int` value, to `print(address:)`.
///
/// printInt(atAddress: intPointer)
/// // Prints "42"
///
/// Alternatively, you can use Swift's *implicit bridging* to pass a pointer to
/// an instance or to the elements of an array. The following example passes a
/// pointer to the `value` variable by using inout syntax:
///
/// var value: Int = 23
/// printInt(atAddress: &value)
/// // Prints "23"
///
/// A mutable pointer to the elements of an array is implicitly created when
/// you pass the array using inout syntax. This example uses implicit bridging
/// to pass a pointer to the elements of `numbers` when calling
/// `printInt(atAddress:)`.
///
/// var numbers = [5, 10, 15, 20]
/// printInt(atAddress: &numbers)
/// // Prints "5"
///
/// No matter which way you call `printInt(atAddress:)`, Swift's type safety
/// guarantees that you can only pass a pointer to the type required by the
/// function---in this case, a pointer to an `Int`.
///
/// - Important: The pointer created through implicit bridging of an instance
/// or of an array's elements is only valid during the execution of the
/// called function. Escaping the pointer to use after the execution of the
/// function is undefined behavior. In particular, do not use implicit
/// bridging when calling an `UnsafeMutablePointer` initializer.
///
/// var number = 5
/// let numberPointer = UnsafeMutablePointer<Int>(&number)
/// // Accessing 'numberPointer' is undefined behavior.
@frozen // unsafe-performance
public struct UnsafeMutablePointer<Pointee>: _Pointer, Sendable {
/// A type that represents the distance between two pointers.
public typealias Distance = Int
/// The underlying raw (untyped) pointer.
public let _rawValue: Builtin.RawPointer
/// Creates an `UnsafeMutablePointer` from a builtin raw pointer.
@_transparent
public init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Creates a mutable typed pointer referencing the same memory as the given
/// immutable pointer.
///
/// - Parameter other: The immutable pointer to convert.
@_transparent
public init(@_nonEphemeral mutating other: UnsafePointer<Pointee>) {
self._rawValue = other._rawValue
}
/// Creates a mutable typed pointer referencing the same memory as the given
/// immutable pointer.
///
/// - Parameter other: The immutable pointer to convert. If `other` is `nil`,
/// the result is `nil`.
@_transparent
public init?(@_nonEphemeral mutating other: UnsafePointer<Pointee>?) {
guard let unwrapped = other else { return nil }
self.init(mutating: unwrapped)
}
/// Creates an immutable typed pointer referencing the same memory as the
/// given mutable pointer.
///
/// - Parameter other: The pointer to convert.
@_transparent
public init(@_nonEphemeral _ other: UnsafeMutablePointer<Pointee>) {
self._rawValue = other._rawValue
}
/// Creates an immutable typed pointer referencing the same memory as the
/// given mutable pointer.
///
/// - Parameter other: The pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?(@_nonEphemeral _ other: UnsafeMutablePointer<Pointee>?) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
/// Allocates uninitialized memory for the specified number of instances of
/// type `Pointee`.
///
/// The resulting pointer references a region of memory that is bound to
/// `Pointee` and is `count * MemoryLayout<Pointee>.stride` bytes in size.
///
/// The following example allocates enough new memory to store four `Int`
/// instances and then initializes that memory with the elements of a range.
///
/// let intPointer = UnsafeMutablePointer<Int>.allocate(capacity: 4)
/// for i in 0..<4 {
/// (intPointer + i).initialize(to: i)
/// }
/// print(intPointer.pointee)
/// // Prints "0"
///
/// When you allocate memory, always remember to deallocate once you're
/// finished.
///
/// intPointer.deallocate()
///
/// - Parameter count: The amount of memory to allocate, counted in instances
/// of `Pointee`.
@inlinable
public static func allocate(capacity count: Int)
-> UnsafeMutablePointer<Pointee> {
let size = MemoryLayout<Pointee>.stride * count
// For any alignment <= _minAllocationAlignment, force alignment = 0.
// This forces the runtime's "aligned" allocation path so that
// deallocation does not require the original alignment.
//
// The runtime guarantees:
//
// align == 0 || align > _minAllocationAlignment:
// Runtime uses "aligned allocation".
//
// 0 < align <= _minAllocationAlignment:
// Runtime may use either malloc or "aligned allocation".
var align = Builtin.alignof(Pointee.self)
if Int(align) <= _minAllocationAlignment() {
align = (0)._builtinWordValue
}
let rawPtr = Builtin.allocRaw(size._builtinWordValue, align)
Builtin.bindMemory(rawPtr, count._builtinWordValue, Pointee.self)
return UnsafeMutablePointer(rawPtr)
}
/// Deallocates the memory block previously allocated at this pointer.
///
/// This pointer must be a pointer to the start of a previously allocated memory
/// block. The memory must not be initialized or `Pointee` must be a trivial type.
@inlinable
public func deallocate() {
// Passing zero alignment to the runtime forces "aligned
// deallocation". Since allocation via `UnsafeMutable[Raw][Buffer]Pointer`
// always uses the "aligned allocation" path, this ensures that the
// runtime's allocation and deallocation paths are compatible.
Builtin.deallocRaw(_rawValue, (-1)._builtinWordValue, (0)._builtinWordValue)
}
/// Accesses the instance referenced by this pointer.
///
/// When reading from the `pointee` property, the instance referenced by this
/// pointer must already be initialized. When `pointee` is used as the left
/// side of an assignment, the instance must be initialized or this
/// pointer's `Pointee` type must be a trivial type.
///
/// Do not assign an instance of a nontrivial type through `pointee` to
/// uninitialized memory. Instead, use an initializing method, such as
/// `initialize(repeating:count:)`.
@inlinable // unsafe-performance
public var pointee: Pointee {
@_transparent unsafeAddress {
return UnsafePointer(self)
}
@_transparent nonmutating unsafeMutableAddress {
return self
}
}
/// Initializes this pointer's memory with the specified number of
/// consecutive copies of the given value.
///
/// The destination memory must be uninitialized or the pointer's `Pointee`
/// must be a trivial type. After a call to `initialize(repeating:count:)`, the
/// memory referenced by this pointer is initialized.
///
/// - Parameters:
/// - repeatedValue: The instance to initialize this pointer's memory with.
/// - count: The number of consecutive copies of `newValue` to initialize.
/// `count` must not be negative.
@inlinable
public func initialize(repeating repeatedValue: Pointee, count: Int) {
// FIXME: add tests (since the `count` has been added)
_debugPrecondition(count >= 0,
"UnsafeMutablePointer.initialize(repeating:count:): negative count")
// Must not use `initializeFrom` with a `Collection` as that will introduce
// a cycle.
for offset in 0..<count {
Builtin.initialize(repeatedValue, (self + offset)._rawValue)
}
}
/// Initializes this pointer's memory with a single instance of the given value.
///
/// The destination memory must be uninitialized or the pointer's `Pointee`
/// must be a trivial type. After a call to `initialize(to:)`, the
/// memory referenced by this pointer is initialized. Calling this method is
/// roughly equivalent to calling `initialize(repeating:count:)` with a
/// `count` of 1.
///
/// - Parameters:
/// - value: The instance to initialize this pointer's pointee to.
@inlinable
public func initialize(to value: Pointee) {
Builtin.initialize(value, self._rawValue)
}
/// Retrieves and returns the referenced instance, returning the pointer's
/// memory to an uninitialized state.
///
/// Calling the `move()` method on a pointer `p` that references memory of
/// type `T` is equivalent to the following code, aside from any cost and
/// incidental side effects of copying and destroying the value:
///
/// let value: T = {
/// defer { p.deinitialize(count: 1) }
/// return p.pointee
/// }()
///
/// The memory referenced by this pointer must be initialized. After calling
/// `move()`, the memory is uninitialized.
///
/// - Returns: The instance referenced by this pointer.
@inlinable
public func move() -> Pointee {
return Builtin.take(_rawValue)
}
/// Replaces this pointer's memory with the specified number of
/// consecutive copies of the given value.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized or
/// `Pointee` must be a trivial type. After calling
/// `assign(repeating:count:)`, the region is initialized.
///
/// - Parameters:
/// - repeatedValue: The instance to assign this pointer's memory to.
/// - count: The number of consecutive copies of `newValue` to assign.
/// `count` must not be negative.
@inlinable
public func assign(repeating repeatedValue: Pointee, count: Int) {
_debugPrecondition(count >= 0, "UnsafeMutablePointer.assign(repeating:count:) with negative count")
for i in 0..<count {
self[i] = repeatedValue
}
}
/// Replaces this pointer's initialized memory with the specified number of
/// instances from the given pointer's memory.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized or
/// `Pointee` must be a trivial type. After calling
/// `assign(from:count:)`, the region is initialized.
///
/// - Note: Returns without performing work if `self` and `source` are equal.
///
/// - Parameters:
/// - source: A pointer to at least `count` initialized instances of type
/// `Pointee`. The memory regions referenced by `source` and this
/// pointer may overlap.
/// - count: The number of instances to copy from the memory referenced by
/// `source` to this pointer's memory. `count` must not be negative.
@inlinable
public func assign(from source: UnsafePointer<Pointee>, count: Int) {
_debugPrecondition(
count >= 0, "UnsafeMutablePointer.assign with negative count")
if UnsafePointer(self) < source || UnsafePointer(self) >= source + count {
// assign forward from a disjoint or following overlapping range.
Builtin.assignCopyArrayFrontToBack(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// self[i] = source[i]
// }
}
else if UnsafePointer(self) != source {
// assign backward from a non-following overlapping range.
Builtin.assignCopyArrayBackToFront(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// var i = count-1
// while i >= 0 {
// self[i] = source[i]
// i -= 1
// }
}
}
/// Moves instances from initialized source memory into the uninitialized
/// memory referenced by this pointer, leaving the source memory
/// uninitialized and the memory referenced by this pointer initialized.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be uninitialized or
/// `Pointee` must be a trivial type. After calling
/// `moveInitialize(from:count:)`, the region is initialized and the memory
/// region `source..<(source + count)` is uninitialized.
///
/// - Parameters:
/// - source: A pointer to the values to copy. The memory region
/// `source..<(source + count)` must be initialized. The memory regions
/// referenced by `source` and this pointer may overlap.
/// - count: The number of instances to move from `source` to this
/// pointer's memory. `count` must not be negative.
@inlinable
public func moveInitialize(
@_nonEphemeral from source: UnsafeMutablePointer, count: Int
) {
_debugPrecondition(
count >= 0, "UnsafeMutablePointer.moveInitialize with negative count")
if self < source || self >= source + count {
// initialize forward from a disjoint or following overlapping range.
Builtin.takeArrayFrontToBack(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// (self + i).initialize(to: (source + i).move())
// }
}
else {
// initialize backward from a non-following overlapping range.
Builtin.takeArrayBackToFront(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// var src = source + count
// var dst = self + count
// while dst != self {
// (--dst).initialize(to: (--src).move())
// }
}
}
/// Initializes the memory referenced by this pointer with the values
/// starting at the given pointer.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be uninitialized or
/// `Pointee` must be a trivial type. After calling
/// `initialize(from:count:)`, the region is initialized.
///
/// - Parameters:
/// - source: A pointer to the values to copy. The memory region
/// `source..<(source + count)` must be initialized. The memory regions
/// referenced by `source` and this pointer must not overlap.
/// - count: The number of instances to move from `source` to this
/// pointer's memory. `count` must not be negative.
@inlinable
public func initialize(from source: UnsafePointer<Pointee>, count: Int) {
_debugPrecondition(
count >= 0, "UnsafeMutablePointer.initialize with negative count")
_debugPrecondition(
UnsafePointer(self) + count <= source ||
source + count <= UnsafePointer(self),
"UnsafeMutablePointer.initialize overlapping range")
Builtin.copyArray(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// (self + i).initialize(to: source[i])
// }
}
/// Replaces the memory referenced by this pointer with the values
/// starting at the given pointer, leaving the source memory uninitialized.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized or
/// `Pointee` must be a trivial type. After calling
/// `moveAssign(from:count:)`, the region is initialized and the memory
/// region `source..<(source + count)` is uninitialized.
///
/// - Parameters:
/// - source: A pointer to the values to copy. The memory region
/// `source..<(source + count)` must be initialized. The memory regions
/// referenced by `source` and this pointer must not overlap.
/// - count: The number of instances to move from `source` to this
/// pointer's memory. `count` must not be negative.
@inlinable
public func moveAssign(
@_nonEphemeral from source: UnsafeMutablePointer, count: Int
) {
_debugPrecondition(
count >= 0, "UnsafeMutablePointer.moveAssign(from:) with negative count")
_debugPrecondition(
self + count <= source || source + count <= self,
"moveAssign overlapping range")
Builtin.assignTakeArray(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// These builtins are equivalent to:
// for i in 0..<count {
// self[i] = (source + i).move()
// }
}
/// Deinitializes the specified number of values starting at this pointer.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized. After
/// calling `deinitialize(count:)`, the memory is uninitialized, but still
/// bound to the `Pointee` type.
///
/// - Parameter count: The number of instances to deinitialize. `count` must
/// not be negative.
/// - Returns: A raw pointer to the same address as this pointer. The memory
/// referenced by the returned raw pointer is still bound to `Pointee`.
@inlinable
@discardableResult
public func deinitialize(count: Int) -> UnsafeMutableRawPointer {
_debugPrecondition(count >= 0, "UnsafeMutablePointer.deinitialize with negative count")
// FIXME: optimization should be implemented, where if the `count` value
// is 1, the `Builtin.destroy(Pointee.self, _rawValue)` gets called.
Builtin.destroyArray(Pointee.self, _rawValue, count._builtinWordValue)
return UnsafeMutableRawPointer(self)
}
/// Executes the given closure while temporarily binding the specified number
/// of instances to the given type.
///
/// Use this method when you have a pointer to memory bound to one type and
/// you need to access that memory as instances of another type. Accessing
/// memory as a type `T` requires that the memory be bound to that type. A
/// memory location may only be bound to one type at a time, so accessing
/// the same memory as an unrelated type without first rebinding the memory
/// is undefined.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized.
///
/// The following example temporarily rebinds the memory of a `UInt64`
/// pointer to `Int64`, then accesses a property on the signed integer.
///
/// let uint64Pointer: UnsafeMutablePointer<UInt64> = fetchValue()
/// let isNegative = uint64Pointer.withMemoryRebound(to: Int64.self, capacity: 1) { ptr in
/// return ptr.pointee < 0
/// }
///
/// Because this pointer's memory is no longer bound to its `Pointee` type
/// while the `body` closure executes, do not access memory using the
/// original pointer from within `body`. Instead, use the `body` closure's
/// pointer argument to access the values in memory as instances of type
/// `T`.
///
/// After executing `body`, this method rebinds memory back to the original
/// `Pointee` type.
///
/// - Note: Only use this method to rebind the pointer's memory to a type
/// with the same size and stride as the currently bound `Pointee` type.
/// To bind a region of memory to a type that is a different size, convert
/// the pointer to a raw pointer and use the `bindMemory(to:capacity:)`
/// method.
///
/// - Parameters:
/// - type: The type to temporarily bind the memory referenced by this
/// pointer. The type `T` must be the same size and be layout compatible
/// with the pointer's `Pointee` type.
/// - count: The number of instances of `Pointee` to bind to `type`.
/// - body: A closure that takes a mutable typed pointer to the
/// same memory as this pointer, only bound to type `T`. The closure's
/// pointer argument is valid only for the duration of the closure's
/// execution. If `body` has a return value, that value is also used as
/// the return value for the `withMemoryRebound(to:capacity:_:)` method.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public func withMemoryRebound<T, Result>(to type: T.Type, capacity count: Int,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result {
Builtin.bindMemory(_rawValue, count._builtinWordValue, T.self)
defer {
Builtin.bindMemory(_rawValue, count._builtinWordValue, Pointee.self)
}
return try body(UnsafeMutablePointer<T>(_rawValue))
}
/// Accesses the pointee at the specified offset from this pointer.
///
/// For a pointer `p`, the memory at `p + i` must be initialized when reading
/// the value by using the subscript. When the subscript is used as the left
/// side of an assignment, the memory at `p + i` must be initialized or
/// the pointer's `Pointee` type must be a trivial type.
///
/// Do not assign an instance of a nontrivial type through the subscript to
/// uninitialized memory. Instead, use an initializing method, such as
/// `initialize(repeating:count:)`.
///
/// - Parameter i: The offset from this pointer at which to access an
/// instance, measured in strides of the pointer's `Pointee` type.
@inlinable
public subscript(i: Int) -> Pointee {
@_transparent
unsafeAddress {
return UnsafePointer(self + i)
}
@_transparent
nonmutating unsafeMutableAddress {
return self + i
}
}
@inlinable // unsafe-performance
internal static var _max: UnsafeMutablePointer {
return UnsafeMutablePointer(
bitPattern: 0 as Int &- MemoryLayout<Pointee>.stride
)._unsafelyUnwrappedUnchecked
}
}
|
apache-2.0
|
73eb68160cd877ff52e51a770a96fe69
| 42.003043 | 103 | 0.674442 | 4.405756 | false | false | false | false |
sugar2010/arcgis-runtime-samples-ios
|
GeometrySample/swift/GeometrySample/Controllers/DensifyViewController.swift
|
4
|
6645
|
//
// Copyright 2014 ESRI
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
//
// See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm
//
import UIKit
import ArcGIS
class DensifyViewController: UIViewController, AGSMapViewLayerDelegate {
@IBOutlet weak var toolbar:UIToolbar!
@IBOutlet weak var mapView:AGSMapView!
@IBOutlet weak var geometryControl:UISegmentedControl!
@IBOutlet weak var resetButton:UIBarButtonItem!
@IBOutlet weak var slider:UISlider!
@IBOutlet weak var distance:UIBarButtonItem!
@IBOutlet weak var userInstructions:UILabel!
var resultGraphicsLayer:AGSGraphicsLayer!
var sketchGeometries:[AGSGeometry]!
var densifyDistance:Double!
var sketchLayer:AGSSketchGraphicsLayer!
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.showMagnifierOnTapAndHold = true
self.mapView.enableWrapAround()
self.mapView.layerDelegate = self
// Load a tiled map service
let mapUrl = NSURL(string: "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer")
let tiledLyr = AGSTiledMapServiceLayer(URL: mapUrl)
self.mapView.addMapLayer(tiledLyr, withName:"Tiled Layer")
let lineSymbol = AGSSimpleLineSymbol()
lineSymbol.color = UIColor.yellowColor()
lineSymbol.width = 4
let pointSymbol = AGSSimpleMarkerSymbol()
pointSymbol.color = UIColor.redColor()
pointSymbol.style = .Circle
pointSymbol.size = CGSizeMake(5, 5)
// A composite symbol for lines and polygons
let compositeSymbol = AGSCompositeSymbol()
compositeSymbol.addSymbol(lineSymbol)
compositeSymbol.addSymbol(pointSymbol)
// A renderer for the graphics layer
let simpleRenderer = AGSSimpleRenderer(symbol: compositeSymbol)
// Create a graphics layer and add it to the map.
// This layer will contain the results of densify operation
self.resultGraphicsLayer = AGSGraphicsLayer()
self.resultGraphicsLayer.renderer = simpleRenderer
self.mapView.addMapLayer(self.resultGraphicsLayer, withName:"Results Layer")
// Set the limits and current value of the slider
// Represents the amount by which we want to densify geometries
self.slider.minimumValue = 1
self.slider.maximumValue = 5000
self.slider.value = 3000
let value = Double(self.slider.value)
self.densifyDistance = value
self.distance.title = "\(Int(value))m"
// Create an envelope and zoom the map to it
let sr = AGSSpatialReference(WKID: 102100)
let envelope = AGSEnvelope(xmin: -8139237.214629, ymin:5016257.541842, xmax: -8090341.387563, ymax:5077377.325675, spatialReference:sr)
self.mapView.zoomToEnvelope(envelope, animated:true)
self.userInstructions.text = "Sketch a geometry and tap the densify button to see the result"
self.sketchGeometries = [AGSGeometry]()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - AGSMapView delegate
func mapViewDidLoad(mapView: AGSMapView!) {
// Create a sketch layer and add it to the map
self.sketchLayer = AGSSketchGraphicsLayer()
self.sketchLayer.geometry = AGSMutablePolyline(spatialReference: self.mapView.spatialReference)
self.mapView.addMapLayer(self.sketchLayer, withName:"Sketch layer")
self.mapView.touchDelegate = self.sketchLayer
}
@IBAction func sliderValueChanged(slider:UISlider) {
// Get the value of the slider
// and densify the geometries using the new value
let value = Double(slider.value)
self.densifyDistance = value
self.distance.title = "\(Int(value))m"
self.resultGraphicsLayer.removeAllGraphics()
var newGraphics = [AGSGraphic]()
// Densify the geometries using the geometry engine
for geometry in self.sketchGeometries as [AGSGeometry] {
let geometryEngine = AGSGeometryEngine()
let newGeometry = geometryEngine.densifyGeometry(geometry, withMaxSegmentLength:self.densifyDistance)
let graphic = AGSGraphic(geometry: newGeometry, symbol:nil, attributes:nil)
newGraphics.append(graphic)
}
self.resultGraphicsLayer.addGraphics(newGraphics)
}
@IBAction func selectGeometry(geomControl:UISegmentedControl) {
// Set the geometry of the sketch layer to match
// the selected geometry type (polygon or polyline)
switch (geomControl.selectedSegmentIndex) {
case 0:
self.sketchLayer.geometry = AGSMutablePolyline(spatialReference: self.mapView.spatialReference)
case 1:
self.sketchLayer.geometry = AGSMutablePolygon(spatialReference: self.mapView.spatialReference)
default:
break
}
self.sketchLayer.clear()
}
@IBAction func reset() {
self.userInstructions.text = "Sketch a geometry and tap the densify button to see the result";
self.sketchGeometries = [AGSGeometry]()
self.resultGraphicsLayer.removeAllGraphics()
self.sketchLayer.clear()
}
@IBAction func densify() {
self.userInstructions.text = "Adjust slider to see changes, tap reset to start over "
// Get the sketch layer's geometry
let sketchGeometry = self.sketchLayer.geometry.copy() as! AGSGeometry
// Keep the original geometries to densify again later
self.sketchGeometries.append(sketchGeometry)
let geometryEngine = AGSGeometryEngine()
// Densify the geometry and create a graphic to add to the result graphics layer
let newGeometry = geometryEngine.densifyGeometry(sketchGeometry, withMaxSegmentLength:self.densifyDistance)
let graphic = AGSGraphic(geometry: newGeometry, symbol:nil, attributes:nil)
self.resultGraphicsLayer.addGraphic(graphic)
self.sketchLayer.clear()
}
}
|
apache-2.0
|
9e711de6de8cb5350e8941f99a34f113
| 38.319527 | 143 | 0.67374 | 4.914941 | false | false | false | false |
KeepGoing2016/Swift-
|
DUZB_XMJ/DUZB_XMJ/Classes/Home/View/AdView.swift
|
1
|
4509
|
//
// AdView.swift
// DUZB_XMJ
//
// Created by user on 16/12/28.
// Copyright © 2016年 XMJ. All rights reserved.
//
import UIKit
fileprivate let kAdCollectionViewCellId = "kAdCollectionViewCellId"
fileprivate let pageW:CGFloat = 100
fileprivate let pageH:CGFloat = 30
class AdView: UIView {
fileprivate lazy var adCollectionView:UICollectionView = {[weak self] in
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width: kScreenW, height: (self?.bounds.height)!)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
let collectionV = UICollectionView(frame: (self?.bounds)!, collectionViewLayout: layout)
collectionV.isPagingEnabled = true
collectionV.showsHorizontalScrollIndicator = false
collectionV.showsVerticalScrollIndicator = false
collectionV.backgroundColor = UIColor.white
collectionV.dataSource = self
collectionV.delegate = self
collectionV.bounces = false
collectionV.register(UINib(nibName: "AdCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: kAdCollectionViewCellId)
return collectionV
}()
fileprivate lazy var pageControll:UIPageControl = {[weak self] in
let pageControll = UIPageControl()
pageControll.currentPage = 0
pageControll.currentPageIndicatorTintColor = UIColor.orange
pageControll.pageIndicatorTintColor = UIColor.gray
pageControll.frame = CGRect(x: kScreenW-pageW, y:(self?.bounds.height)!-pageH, width: pageW, height: pageH)
pageControll.backgroundColor = UIColor.clear
return pageControll
}()
var adModelsArr:[AdsModel]?{
didSet{
adCollectionView.reloadData()
pageControll.numberOfPages = (adModelsArr?.count)!
let indexP = IndexPath(item: (adModelsArr?.count)!*300, section: 0)
adCollectionView.scrollToItem(at: indexP, at: .left, animated: false)
stopCircle()
startCircle()
}
}
fileprivate var adTimer:Timer?
override init(frame: CGRect) {
super.init(frame:frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK:-设置UI
extension AdView{
fileprivate func setupUI(){
addSubview(adCollectionView)
addSubview(pageControll)
}
}
//定时器
extension AdView{
fileprivate func startCircle(){
adTimer = Timer(timeInterval: 2, target: self, selector: #selector(scrollToNext), userInfo: nil, repeats: true)
RunLoop.current.add(adTimer!, forMode: .commonModes)
}
fileprivate func stopCircle(){
adTimer?.invalidate()
adTimer = nil
}
@objc fileprivate func scrollToNext(){
// UIView.animate(withDuration: 1) {
// self.adCollectionView.contentOffset.x = self.adCollectionView.contentOffset.x + self.adCollectionView.bounds.width
// }
let offsetX = self.adCollectionView.contentOffset.x + self.adCollectionView.bounds.width
self.adCollectionView.setContentOffset(CGPoint(x:offsetX,y:0), animated: true)
}
}
extension AdView:UICollectionViewDataSource{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (self.adModelsArr?.count ?? 0)*1000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kAdCollectionViewCellId, for: indexPath) as! AdCollectionViewCell
cell.adModel = adModelsArr?[indexPath.item%(self.adModelsArr?.count)!]
return cell
}
}
extension AdView:UICollectionViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControll.currentPage = Int(scrollView.contentOffset.x/scrollView.bounds.width+0.5)%(adModelsArr?.count)!
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
stopCircle()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
startCircle()
}
}
|
apache-2.0
|
4d9e37524a1bf52270f26ebcf6d42ba7
| 32.552239 | 140 | 0.672153 | 4.995556 | false | false | false | false |
jongwonwoo/CodeSamples
|
StackView/StackViewInScrollView/AppStore/AppStore/AppListViewController.swift
|
1
|
2614
|
//
// AppListViewController.swift
// AppStore
//
// Created by Jongwon Woo on 25/06/2017.
// Copyright © 2017 WooJongwon. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class AppListViewController: UICollectionViewController {
var searchResults: [AppInfo] = []
let queryService = AppListQueryService()
override func viewDidLoad() {
super.viewDidLoad()
queryService.getSearchResults { results in
self.searchResults = results
self.collectionView?.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
self.collectionView?.collectionViewLayout.invalidateLayout()
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowDetail" {
guard let detailVC = segue.destination as? AppDetailViewController,
let indexPath = self.collectionView?.indexPathsForSelectedItems?.last
else { return }
detailVC.appInfo = searchResults[indexPath.item]
}
}
}
// MARK: UICollectionViewDataSource
extension AppListViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return searchResults.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! AppCell
let appInfo = searchResults[indexPath.item]
cell.nameLabel.text = appInfo.name
cell.sellerLabel.text = appInfo.sellerName
cell.iconView.loadImage(url: appInfo.iconUrl)
return cell
}
}
extension AppListViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = CGFloat(95.0)
return CGSize(width: collectionView.bounds.width, height: height)
}}
|
mit
|
4e0b773ed5e8f2a2ee69aa8095679ed2
| 32.075949 | 160 | 0.697283 | 5.619355 | false | false | false | false |
abdullah-chhatra/iLayout
|
Example/Example/ExampleViews/RelativeDimensionView.swift
|
1
|
2470
|
//
// RelativeDimensionView.swift
// Example
//
// Created by Abdulmunaf Chhatra on 6/7/15.
// Copyright (c) 2015 Abdulmunaf Chhatra. All rights reserved.
//
import Foundation
import iLayout
class RelativeDimensionView : AutoLayoutView {
var label1 = UILabel.createWithText(text: "Label 1 250px X 50px")
var sameWidth = UILabel.createWithText(text: "Same width")
var sameHeight = UILabel.createWithText(text: "Same height")
var sameSize = UILabel.createWithText(text: "Same size")
var halfWidth = UILabel.createWithText(text: "Half width")
var halfHeight = UILabel.createWithText(text: "Half height")
var doubleWidth = UILabel.createWithText(text: "Double width")
var doubleHeight = UILabel.createWithText(text: "Double height")
override func initializeView() {
super.initializeView()
backgroundColor = UIColor.white
addSubview(label1)
addSubview(sameWidth)
addSubview(sameHeight)
addSubview(sameSize)
addSubview(halfWidth)
addSubview(halfHeight)
addSubview(doubleWidth)
addSubview(doubleHeight)
}
override func addConstraints(_ layout: Layout) {
layout.horizontallyAlignWithSuperview(subviews)
layout.pinToTopMarginOfSuperview(label1, offset: 10)
layout.placeView(sameWidth, below: label1, spacing: 5)
layout.placeView(sameHeight, below: sameWidth, spacing: 5)
layout.placeView(sameSize, below: sameHeight, spacing: 5)
layout.placeView(halfWidth, below: sameSize, spacing: 5)
layout.placeView(halfHeight, below: halfWidth, spacing: 5)
layout.placeView(doubleWidth, below: halfHeight, spacing: 5)
layout.placeView(doubleHeight, below: doubleWidth, spacing: 5)
layout.setForView(label1, width: 250, height: 50)
layout.makeWidthOfView(sameWidth, equalTo: label1)
layout.makeHeightOfView(sameHeight, equalTo: label1)
layout.makeSizeOfView(sameSize, equalTo: label1)
layout.makeWidthOfView(halfWidth, relativeTo: label1, multiplier: 0.5)
layout.makeHeightOfView(halfHeight, relativeTo: label1, multiplier: 0.5)
layout.makeWidthOfView(doubleWidth, relativeTo: label1, multiplier: 2)
layout.makeHeightOfView(doubleHeight, relativeTo: label1, multiplier: 2)
}
}
|
mit
|
ee3ed48fce0f83ad953d06c3e46d8662
| 33.788732 | 80 | 0.669231 | 4.273356 | false | false | false | false |
cotkjaer/Silverback
|
Silverback/Set.swift
|
1
|
4276
|
//
// Set.swift
// SilverbackFramework
//
// Created by Christian Otkjær on 20/04/15.
// Copyright (c) 2015 Christian Otkjær. All rights reserved.
//
import Foundation
public func + <T:Hashable>(lhs: Set<T>?, rhs: T) -> Set<T>
{
return Set(rhs).union(lhs)
}
public func + <T:Hashable>(lhs: T, rhs: Set<T>?) -> Set<T>
{
return rhs + lhs
}
public func - <T:Hashable, S : SequenceType where S.Generator.Element == T>(lhs: Set<T>, rhs: S?) -> Set<T>
{
if let r = rhs
{
return lhs.subtract(r)
}
return lhs
}
public func - <T:Hashable>(lhs: Set<T>, rhs: T?) -> Set<T>
{
return lhs - Set(rhs)
}
// MARK: - Optionals
public extension Set
{
/**
Initializes a set from the non-nil elements in `elements`
- parameter elements: list of optional members for the set
*/
init(_ elements: Element?...)
{
self.init(elements)
}
init(_ optionalMembers: [Element?])
{
self.init(optionalMembers.flatMap{ $0 })
}
init(_ optionalArray: [Element]?)
{
self.init(optionalArray ?? [])
}
init(_ optionalArrayOfOptionalMembers: [Element?]?)
{
self.init(optionalArrayOfOptionalMembers ?? [])
}
/**
Picks a random member from the set
- returns: A random member, or nil if set is empty
*/
@warn_unused_result
public func random() -> Element?
{
return Array(self).random()
}
@warn_unused_result
func union<S : SequenceType where S.Generator.Element == Element>(sequence: S?) -> Set<Element>
{
if let s = sequence
{
return union(s)
}
return self
}
mutating func unionInPlace<S : SequenceType where S.Generator.Element == Element>(sequence: S?)
{
if let s = sequence
{
unionInPlace(s)
}
}
/// Insert an optional element into the set
/// - returns: **true** if the element was inserted, **false** otherwise
@warn_unused_result
mutating func insert(optionalElement: Element?) -> Bool
{
if let element = optionalElement
{
if !contains(element)
{
insert(element)
return true
}
}
return false
}
/// Return a `Set` contisting of the non-nil results of applying `transform` to each member of `self`
@warn_unused_result
func map<U:Hashable>(@noescape transform: Element -> U?) -> Set<U>
{
return Set<U>(flatMap(transform))
}
///Remove all members in `self` that are accepted by the predicate
mutating func remove(@noescape predicate: Element -> Bool)
{
subtractInPlace(filter(predicate))
}
/// Return a `Set` contisting of the members of `self`, that satisfy the predicate `includeMember`.
@warn_unused_result
func sift(@noescape includeMember: Element throws -> Bool) rethrows -> Set<Element>
{
return try Set(filter(includeMember))
}
/// Return a `Set` contisting of the members of `self`, that are `T`s
@warn_unused_result
func cast<T:Hashable>(type: T.Type) -> Set<T>
{
return map{ $0 as? T }
}
/// Returns **true** `optionalMember` is non-nil and contained in `self`, **flase** otherwise.
@warn_unused_result
func contains(optionalMember: Element?) -> Bool
{
return optionalMember?.containedIn(self) == true
}
}
// MARK: - Subsets
public extension Set
{
/// Returns **all** the subsets of this set. That might be quite a lot!
@warn_unused_result
func subsets() -> Set<Set<Element>>
{
var subsets = Set<Set<Element>>()
if count > 1
{
if let element = first
{
subsets.insert(Set<Element>(element))
let rest = self - element
subsets.insert(rest)
for set in rest.subsets()
{
subsets.insert(set)
subsets.insert(set + element)
}
}
}
return subsets
}
}
|
mit
|
4324c322435ae2d242542b2d1362818f
| 22.228261 | 107 | 0.543519 | 4.109615 | false | false | false | false |
milseman/swift
|
test/stdlib/Filter.swift
|
14
|
2155
|
//===--- Filter.swift - tests for lazy filtering --------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
let FilterTests = TestSuite("Filter")
// Check that the generic parameter is called 'Base'.
protocol TestProtocol1 {}
extension LazyFilterIterator where Base : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension LazyFilterSequence where Base : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension LazyFilterCollection where Base : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
FilterTests.test("filtering collections") {
let f0 = LazyFilterCollection(_base: 0..<30) { $0 % 7 == 0 }
expectEqualSequence([0, 7, 14, 21, 28], f0)
let f1 = LazyFilterCollection(_base: 1..<30) { $0 % 7 == 0 }
expectEqualSequence([7, 14, 21, 28], f1)
}
FilterTests.test("filtering sequences") {
let f0 = (0..<30).makeIterator().lazy.filter { $0 % 7 == 0 }
expectEqualSequence([0, 7, 14, 21, 28], f0)
let f1 = (1..<30).makeIterator().lazy.filter { $0 % 7 == 0 }
expectEqualSequence([7, 14, 21, 28], f1)
}
FilterTests.test("single-count") {
// Check that we're only calling a lazy filter's predicate one time for
// each element in a sequence or collection.
var count = 0
let mod7AndCount: (Int) -> Bool = {
count += 1
return $0 % 7 == 0
}
let f0 = (0..<30).makeIterator().lazy.filter(mod7AndCount)
let a0 = Array(f0)
expectEqual(30, count)
count = 0
let f1 = LazyFilterCollection(_base: 0..<30, mod7AndCount)
let a1 = Array(f1)
expectEqual(30, count)
}
runAllTests()
|
apache-2.0
|
1c3614341e06dbdaddb57fca39827b2e
| 27.355263 | 80 | 0.646868 | 3.827709 | false | true | false | false |
gegeburu3308119/ZCweb
|
ZCwebo/ZCwebo/Classes/View/NewFeature/WBNewFeatureView.swift
|
1
|
3439
|
//
// WBNewFeatureView.swift
// 传智微博
//
// Created by apple on 16/7/3.
// Copyright © 2016年 itcast. All rights reserved.
//
import UIKit
import pop
/// 新特性视图
class WBNewFeatureView: UIView {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var enterButton: UIButton!
@IBOutlet weak var pageControl: UIPageControl!
/// 进入微博
@IBAction func enterStatus() {
// 1> 创建动画
let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
anim.fromValue = 1
anim.toValue = 0
anim.duration = 0.5
// 2> 添加到视图
pop_add(anim, forKey: nil)
// 3> 添加完成监听方法
anim.completionBlock = { _, _ in
self.removeFromSuperview()
}
}
class func newFeatureView() -> WBNewFeatureView {
let nib = UINib(nibName: "WBNewFeatureView", bundle: nil)
let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewFeatureView
// 从 XIB 加载的视图,默认是 600 * 600 的
v.frame = UIScreen.main.bounds
return v
}
override func awakeFromNib() {
// 如果使用自动布局设置的界面,从 XIB 加载默认是 600 * 600 大小
// 添加 4 个图像视图
let count = 4
let rect = UIScreen.main.bounds
for i in 0..<count {
let imageName = "new_feature_\(i + 1)"
let iv = UIImageView(image: UIImage(named: imageName))
// 设置大小
iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
scrollView.addSubview(iv)
}
// 指定 scrollView 的属性
scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
scrollView.bounces = false
scrollView.isPagingEnabled = true
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.delegate = self
// 隐藏按钮
enterButton.isHidden = true
}
}
extension WBNewFeatureView: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
// 1. 滚动到最后一屏,让视图删除
let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
// 2. 判断是否最后一页
if page == scrollView.subviews.count {
print("欢迎欢迎,热泪欢迎!!!")
removeFromSuperview()
}
// 3. 如果是倒数第2页,显示按钮
enterButton.isHidden = (page != scrollView.subviews.count - 1)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 0. 一旦滚动隐藏按钮
enterButton.isHidden = true
// 1. 计算当前的偏移量
let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
// 2. 设置分页控件
pageControl.currentPage = page
// 3. 分页控件的隐藏
pageControl.isHidden = (page == scrollView.subviews.count)
}
}
|
apache-2.0
|
dfc00b32054f51c279f77e9f9b018604
| 24.590164 | 100 | 0.542281 | 4.597938 | false | false | false | false |
xedin/swift
|
test/stdlib/SwiftObjectNSObject.swift
|
5
|
2185
|
//===--- SwiftObjectNSObject.swift - Test SwiftObject's NSObject interop --===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %empty-directory(%t)
//
// RUN: %target-clang %S/Inputs/SwiftObjectNSObject/SwiftObjectNSObject.m -c -o %t/SwiftObjectNSObject.o -g
// RUN: %target-build-swift %s -I %S/Inputs/SwiftObjectNSObject/ -Xlinker %t/SwiftObjectNSObject.o -o %t/SwiftObjectNSObject
// RUN: %target-codesign %t/SwiftObjectNSObject
// RUN: %target-run %t/SwiftObjectNSObject 2> %t/log.txt
// RUN: %FileCheck %s < %t/log.txt
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
class C {
@objc func cInstanceMethod() -> Int { return 1 }
@objc class func cClassMethod() -> Int { return 2 }
@objc func cInstanceOverride() -> Int { return 3 }
@objc class func cClassOverride() -> Int { return 4 }
}
class D : C {
@objc func dInstanceMethod() -> Int { return 5 }
@objc class func dClassMethod() -> Int { return 6 }
@objc override func cInstanceOverride() -> Int { return 7 }
@objc override class func cClassOverride() -> Int { return 8 }
}
@_silgen_name("TestSwiftObjectNSObject")
func TestSwiftObjectNSObject(_ c: C, _ d: D)
// This check is for NSLog() output from TestSwiftObjectNSObject().
// CHECK: c ##SwiftObjectNSObject.C##
// CHECK-NEXT: d ##SwiftObjectNSObject.D##
// CHECK-NEXT: S ##{{(Swift._)?}}SwiftObject##
// Temporarily disable this test on older OSes until we have time to
// look into why it's failing there. rdar://problem/47870743
if #available(OSX 10.12, iOS 10.0, *) {
TestSwiftObjectNSObject(C(), D())
// does not return
} else {
// Horrible hack to satisfy FileCheck
fputs("c ##SwiftObjectNSObject.C##\n", stderr)
fputs("d ##SwiftObjectNSObject.D##\n", stderr)
fputs("S ##Swift._SwiftObject##\n", stderr)
}
|
apache-2.0
|
304089ce64c50ca211465cafb8ed2d6e
| 37.333333 | 124 | 0.672769 | 3.715986 | false | true | false | false |
O--Sher/KnightsTour
|
KnightsTour/Shared sources/Extensions/UIView+Embeding.swift
|
1
|
785
|
//
// UIView+Embeding.swift
// MedUX Agent
//
// Created by Oleg Sher on 27.02.17.
// Copyright © 2017 MedUX. All rights reserved.
//
import UIKit
extension UIView {
func embed(onView containerView: UIView, offset: CGFloat = 0) {
self.translatesAutoresizingMaskIntoConstraints = false
self.centerXAnchor.constraint(equalTo: containerView.centerXAnchor, constant: offset).isActive = true
self.centerYAnchor.constraint(equalTo: containerView.centerYAnchor, constant: offset).isActive = true
self.heightAnchor.constraint(equalTo: containerView.heightAnchor, constant: offset).isActive = true
self.widthAnchor.constraint(equalTo: containerView.widthAnchor, constant: offset).isActive = true
containerView.layoutIfNeeded()
}
}
|
mit
|
281d6abeaf1c0d1305bf091e87e183fe
| 38.2 | 109 | 0.737245 | 4.639053 | false | false | false | false |
LawrenceHan/ActionStageSwift
|
ActionStageSwift/TestButton.swift
|
1
|
944
|
//
// TestButton.swift
// ActionStageSwift
//
// Created by Hanguang on 07/04/2017.
// Copyright © 2017 Hanguang. All rights reserved.
//
import UIKit
class TestButton: UIButton {
var extendedEdgeInsets: UIEdgeInsets?
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if !isHidden && alpha > CGFloat.ulpOfOne {
if let extendedEdgeInsets = extendedEdgeInsets {
var bounds = self.bounds
bounds.origin.x -= extendedEdgeInsets.left
bounds.size.width += extendedEdgeInsets.left + extendedEdgeInsets.right
bounds.origin.y -= extendedEdgeInsets.top
bounds.size.height += extendedEdgeInsets.top + extendedEdgeInsets.bottom
if bounds.contains(point) {
return self
}
}
}
return super.hitTest(point, with: event)
}
}
|
mit
|
8b005a81ab9e91c4be831859c41e03be
| 30.433333 | 88 | 0.592789 | 4.811224 | false | true | false | false |
moonagic/MagicOcean
|
MagicOcean/ViewControllers/Droplets/DropletsViewController.swift
|
1
|
8852
|
//
// ViewController.swift
// MagicOcean
//
// Created by Wu Hengmin on 16/6/8.
// Copyright © 2016年 Wu Hengmin. All rights reserved.
//
import UIKit
import Alamofire
import MJRefresh
import DZNEmptyDataSet
import SwiftyJSON
class DropletsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, DropletDelegate, AddDropletDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
@IBOutlet weak var tableView: UITableView!
var dropletsData: [DropletTemplate] = Array<DropletTemplate>()
var needReload:Bool = true
var page:Int = 1
override func viewDidLoad() {
super.viewDidLoad()
setStatusBarAndNavigationBar(navigation: self.navigationController!)
tableView.delegate = self
tableView.dataSource = self
tableView.emptyDataSetSource = self
tableView.emptyDataSetDelegate = self
tableView.tableFooterView = UIView.init(frame: CGRect.zero)
tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
setupMJRefresh()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Account.sharedInstance.loadUser()
if Account.sharedInstance.Access_Token != "" {
if needReload {
self.tableView.mj_header.beginRefreshing()
needReload = false
}
} else {
DispatchQueue.main.async {
self.performSegue(withIdentifier: "gotologin", sender: nil)
}
}
// DispatchQueue.main.async { [weak self] in
// guard let `self` = self else { return }
// self.dismiss(animated: true, completion: {
//
// })
// }
}
func setupMJRefresh() {
let header = MJRefreshNormalHeader(refreshingBlock: {
self.loadDroplets(page: 1, per_page:100)
})
header?.lastUpdatedTimeLabel.isHidden = true
header?.isAutomaticallyChangeAlpha = true
self.tableView.mj_header = header
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dropletsData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier:String = "dropletscell"
let cell:DropletsCell = tableView.dequeueReusableCell(withIdentifier: identifier) as! DropletsCell
let d = dropletsData[indexPath.row]
cell.titleLabel.text = d.name
cell.infoLabel.text = "\(d.image.distribution) - \(d.size.vcpus)vCPU - \(d.size.memory)MB - \(d.size.disk)GB"
cell.locationLabel.text = d.region.slug
cell.IPLabel.text = "Public IP: \(d.ip)"
if d.status == "active" {
cell.statusView.backgroundColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
} else {
cell.statusView.backgroundColor = #colorLiteral(red: 0.3333333433, green: 0.3333333433, blue: 0.3333333433, alpha: 1)
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let viewController:DropletDetail = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "dropletdetail") as! DropletDetail
viewController.dropletData = dropletsData[indexPath.row]
self.navigationController?.pushViewController(viewController, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "adddroplet" {
let nv:UINavigationController = segue.destination as! UINavigationController
let and:AddNewDroplet = nv.topViewController as! AddNewDroplet
and.delegate = self
}
}
// MARK: DropletDelegate
func didSeleteDroplet() {
self.tableView.mj_header.beginRefreshing()
}
// MARK: AddDropletDelegate
func didAddDroplet() {
self.tableView.mj_header.beginRefreshing()
}
func loadDroplets(page: Int, per_page: Int) {
let Headers = [
"Content-Type": "application/json",
"Authorization": "Bearer "+Account.sharedInstance.Access_Token
]
weak var weakSelf = self
Alamofire.request(BASE_URL+URL_DROPLETS+"?page=\(page)&per_page=\(per_page)", method: .get, parameters: nil, encoding: URLEncoding.default, headers: Headers).responseJSON { response in
guard let strongSelf = weakSelf else {
return
}
guard let JSONObj = response.result.value else {
makeTextToast(message: "JSON ERROR", view: strongSelf.view)
return
}
let dic = JSONObj as! NSDictionary
let jsonString = dictionary2JsonString(dic: dic as! Dictionary<String, Any>)
print(jsonString)
guard let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) else {
makeTextToast(message: "JSON ERROR", view: strongSelf.view)
return
}
guard let json = try? JSON(data: dataFromString) else {
makeTextToast(message: "JSON ERROR", view: strongSelf.view)
return
}
guard let droplets = json["droplets"].array else {
DispatchQueue.main.async {
strongSelf.tableView.mj_header.endRefreshing()
strongSelf.tableView.reloadData()
}
return
}
strongSelf.dropletsData.removeAll()
for d in droplets {
let image = ImageTeplete(name: d["image"]["distribution"].string ?? "-", slug: d["image"]["slug"].string ?? "", distribution: d["image"]["distribution"].string ?? "")
let region = RegionTeplete(name: d["region"]["name"].string ?? "", slug: d["region"]["slug"].string ?? "")
let size = SizeTeplete(memory: d["size"]["memory"].int ?? 0, price: d["size"]["price_monthly"].int ?? 0, disk: d["size"]["disk"].int ?? 0, transfer: d["size"]["transfer"].int ?? 0, vcpus: d["size"]["vcpus"].int ?? 0, slug: d["size"]["slug"].string ?? "-")
strongSelf.dropletsData.append(DropletTemplate(id: d["id"].int ?? 0, name: d["name"].string ?? "-", ip: d["networks"]["v4"][0]["ip_address"].string ?? "-", status: d["status"].string ?? "", image: image, region: region, size: size))
}
DispatchQueue.main.async {
strongSelf.tableView.mj_header.endRefreshing()
strongSelf.tableView.reloadData()
}
}
}
// MARK: DZNEmptyDataSetSource
func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
let attributes = [
NSAttributedString.Key.foregroundColor: UIColor.darkGray
]
let attrString:NSAttributedString = NSAttributedString(string: "You have no droplets.", attributes: attributes)
return attrString
}
func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
let attributes = [
NSAttributedString.Key.foregroundColor: UIColor.gray
]
let attrString:NSAttributedString = NSAttributedString(string: "You can create your first droplet.", attributes: attributes)
return attrString
}
func buttonTitle(forEmptyDataSet scrollView: UIScrollView!, for state: UIControl.State) -> NSAttributedString! {
let attributes = [
NSAttributedString.Key.foregroundColor: #colorLiteral(red: 0.19, green: 0.56, blue: 0.91, alpha: 1)
]
let attrString:NSAttributedString = NSAttributedString(string: "Create Droplet", attributes: attributes)
return attrString
}
func backgroundColor(forEmptyDataSet scrollView: UIScrollView!) -> UIColor! {
return UIColor.white
}
func emptyDataSetDidTapButton(_ scrollView: UIScrollView!) {
self.performSegue(withIdentifier: "adddroplet", sender: nil)
}
// MARK: DZNEmptyDataSetDelegate
func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
return true
}
@IBAction func addPressed(sender: AnyObject) {
// pressed the add button
}
}
|
mit
|
ec9bfbb94275e630e8bdbbb87ed80546
| 37.811404 | 271 | 0.613855 | 4.996612 | false | false | false | false |
FindGF/_BiliBili
|
WTBilibili/Home-首页/Live-直播/View/WTEntranceIconButton.swift
|
1
|
1439
|
//
// WTEntranceIconButton.swift
// WTBilibili
//
// Created by 无头骑士 GJ on 16/5/8.
// Copyright © 2016年 无头骑士 GJ. All rights reserved.
//
import UIKit
/// 按钮图片的宽度、高度
let EntranceIconButtonImageWH: CGFloat = 40
/// 按钮标题的宽度
let EntranceIconButtonTitleW: CGFloat = 50
/// 按钮标题的高度
let EntranceIconButtonTitleH: CGFloat = 12
class WTEntranceIconButton: UIButton
{
// MARK: - 系统回调函数
override init(frame: CGRect)
{
super.init(frame: frame)
setTitleColor(UIColor.blackColor(), forState: .Normal)
titleLabel?.font = UIFont.systemFontOfSize(12)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: 重新调整图片的位置
override func imageRectForContentRect(contentRect: CGRect) -> CGRect
{
let x = (self.frame.width - EntranceIconButtonImageWH) * 0.5
return CGRect(x: x, y: 20, width: EntranceIconButtonImageWH, height: EntranceIconButtonImageWH)
}
// MARK: 重新调整标题的位置
override func titleRectForContentRect(contentRect: CGRect) -> CGRect
{
let x = (self.frame.width - EntranceIconButtonTitleW) * 0.5
return CGRect(x: x, y: CGRectGetMaxY(imageView!.frame) + 5, width: EntranceIconButtonTitleW, height: EntranceIconButtonTitleH)
}
}
|
apache-2.0
|
2b50630bd4b91e2e317228d366e2e3f8
| 26.020408 | 134 | 0.669184 | 3.82659 | false | false | false | false |
lquigley/Game
|
Game/Game/SpriteKit/Nodes/SKYPlane.swift
|
1
|
907
|
//
// SKYPlane.swift
// Sky High
//
// Created by Luke Quigley on 2/20/15.
// Copyright (c) 2015 VOKAL. All rights reserved.
//
import SpriteKit
class SKYPlane: SKYBaddie {
convenience init () {
//Random image of the two planes
let diceRoll = Int(arc4random_uniform(2)) + 1
let imageName = NSString.localizedStringWithFormat("Plane %d", diceRoll)
let texture:SKTexture = SKTexture(imageNamed: imageName)
self.init(texture: texture, color: SKColor.whiteColor(), size: texture.size())
if direction == SKYBaddieDirection.Left {
self.physicsBody?.velocity = CGVectorMake(velocity, 20)
} else {
self.xScale = -1
self.physicsBody?.velocity = CGVectorMake(-1 * velocity, 20)
}
}
override var velocity:CGFloat {
get {
return 400.0
}
}
}
|
mit
|
4360b839cae527e2f28694047cc8d64a
| 25.676471 | 86 | 0.590959 | 4.298578 | false | false | false | false |
volodg/iAsync.social
|
Pods/iAsync.utils/iAsync.utils/NSObject/NSObject+Ownerships.swift
|
1
|
1533
|
//
// NSObject+OnDeallocBlock.swift
// JUtils
//
// Created by Vladimir Gorbenko on 10.06.14.
// Copyright (c) 2014 EmbeddedSources. All rights reserved.
//
import Foundation
private var sharedObserversKey: Void?
public extension NSObject {
//do not autorelease returned value !
private func lazyOwnerships() -> NSMutableArray {
if let result = objc_getAssociatedObject(self, &sharedObserversKey) as? NSMutableArray {
return result
}
let result = NSMutableArray()
objc_setAssociatedObject(self,
&sharedObserversKey,
result,
UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return result
}
private func ownerships() -> NSMutableArray? {
let result = objc_getAssociatedObject(self, &sharedObserversKey) as? NSMutableArray
return result
}
public func addOwnedObject(object: AnyObject) {
autoreleasepool {
self.lazyOwnerships().addObject(object)
}
}
func removeOwnedObject(object: AnyObject) {
autoreleasepool {
if let ownerships = self.ownerships() {
ownerships.removeObject(object)
}
}
}
func firstOwnedObjectMatch(predicate: (AnyObject) -> Bool) -> AnyObject? {
if let ownerships = self.ownerships()?.copy() as? [AnyObject] {
return firstMatch(ownerships, predicate)
}
return nil
}
}
|
mit
|
1514a459b0ef3c3fbdf6de784814ddec
| 24.983051 | 96 | 0.59426 | 5.042763 | false | false | false | false |
swiftmi/swiftmi-app
|
swiftmi/swiftmi/Utility.swift
|
2
|
3148
|
//
// Utility.swift
// swiftmi
//
// Created by yangyin on 15/4/21.
// Copyright (c) 2015年 swiftmi. All rights reserved.
//
import UIKit
class Utility: NSObject {
class func GetViewController<T>(_ controllerName:String)->T {
let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let toViewController = mainStoryboard.instantiateViewController(withIdentifier: controllerName) as! T
return toViewController
}
class func formatDate(_ date:Date)->String {
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
let dateString = fmt.string(from: date)
return dateString
}
class func showMessage(_ msg:String) {
let alert = UIAlertView(title: "提醒", message: msg, delegate: nil, cancelButtonTitle: "确定")
alert.show()
}
//SDKShare Show
final class func share(_ title:String,desc:String,imgUrl:String?,linkUrl:String) {
var img = imgUrl
if img == nil {
img = "https://imgs.swiftmi.com/swiftmi180icon.png"
}
var text = desc;
if text == "" {
text = title;
}
let textWithUrl = "\(title) \(linkUrl)"
let shareParams = NSMutableDictionary();
shareParams.ssdkSetupShareParams(byText: text, images: [img!], url: URL(string: linkUrl), title: title, type: SSDKContentType.auto)
shareParams.ssdkSetupWeChatParams(byText: text, title: title, url: URL(string:linkUrl), thumbImage: img, image: img, musicFileURL: nil, extInfo: nil, fileData: nil, emoticonData: nil, type: SSDKContentType.image, forPlatformSubType: SSDKPlatformType.typeWechat)
shareParams.ssdkSetupCopyParams(byText: textWithUrl, images: nil, url: URL(string: img!), type: SSDKContentType.text)
shareParams.ssdkSetupSinaWeiboShareParams(byText: textWithUrl, title: textWithUrl, image:nil, url: URL(string:linkUrl), latitude: 0.0, longitude: 0.0, objectID: "", type: SSDKContentType.text)
shareParams.ssdkSetupSMSParams(byText: textWithUrl, title: textWithUrl, images: nil, attachments: nil, recipients: nil, type: SSDKContentType.text)
let items = [SSDKPlatformType.typeSinaWeibo.rawValue,SSDKPlatformType.typeWechat.rawValue,SSDKPlatformType.typeSMS.rawValue,SSDKPlatformType.typeCopy.rawValue];
ShareSDK.showShareActionSheet(nil, items: items, shareParams: shareParams) { (state, type, userData, contentEntity, error, end:Bool) -> Void in
switch(state) {
case SSDKResponseState.success:
let alert = UIAlertView(title: "提示", message:"分享成功", delegate:self, cancelButtonTitle: "ok")
alert.show()
case SSDKResponseState.fail:
let alert = UIAlertView(title: "提示", message:"分享失败:\(error)", delegate:self, cancelButtonTitle: "ok")
alert.show()
default:
break;
}
}
}
}
|
mit
|
ab6ee44ce8287fe694873ef3931f1d8a
| 36.95122 | 269 | 0.622108 | 4.464849 | false | false | false | false |
zhenghuadong11/firstGitHub
|
旅游app_useSwift/旅游app_useSwift/MYTurntableViewController.swift
|
1
|
3335
|
//
// MYTurntableViewController.swift
// 旅游app_useSwift
//
// Created by zhenghuadong on 16/4/23.
// Copyright © 2016年 zhenghuadong. All rights reserved.
//
import UIKit
class MYTurntableViewController: UIViewController {
@IBOutlet weak var turntableImageView: UIImageView!
weak var _indeicatorView:MYIndicatorView?
lazy var _lukeyModels:Array<MYLuckeyScenic> = {
let path = NSBundle.mainBundle().pathForResource("lukeyScenic", ofType: "plist")
let array = NSArray.init(contentsOfFile: path!) as? Array<[String:AnyObject]>
if array == nil
{
return Array<MYLuckeyScenic>()
}
var mArray = Array<MYLuckeyScenic>()
for var dict in array!
{
mArray.append(MYLuckeyScenic.luckeyScenicModelWithDict(dict))
}
return mArray
}()
override func viewDidLoad() {
super.viewDidLoad()
let r = turntableImageView.frame.width/3
let view = MYIndicatorView()
view.backgroundColor = UIColor.clearColor()
view.frame = CGRectMake(0,0,r, 10)
self.view.addSubview(view)
view.layer.anchorPoint = CGPointMake(1,0.5)
view.layer.position = turntableImageView.center
_indeicatorView = view
if _lukeyModels.count == 0
{
return
}
let angle = CGFloat((360.0/Double(_lukeyModels.count))/180*3.145)
for i1 in 0..<_lukeyModels.count
{
let turnView = MYOneTurnView()
turnView.image = UIImage.init(named: _lukeyModels[i1].picture!)
turnView.name = _lukeyModels[i1].name!
turnView.backgroundColor = UIColor.clearColor()
turnView.frame = turntableImageView.bounds
turnView.startAngle = CGFloat(i1)*angle
turnView.endAngle = CGFloat(i1+1)*angle
turnView.oneAngle = angle
turntableImageView.addSubview(turnView)
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let oneAngle = 179
let angle = rand()%1080+1080
let miao = 10.0/Double(angle)
let cishu = Int(angle/179)
let shengyu = Int(angle%179)
viewRotat(cishu, lastAngle: shengyu, miao: miao)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func viewRotat(cishu:Int,lastAngle:Int,miao:Double) -> Void {
if(cishu == 0)
{ return
}
if(cishu == 1)
{
UIView.animateWithDuration(miao*Double(lastAngle), animations: {
self._indeicatorView?.layer.transform = CATransform3DRotate((self._indeicatorView?.layer.transform)!,CGFloat(Float(lastAngle)/180*3.145),0, 0, 1)
})
return
}
UIView.animateWithDuration(miao*179) {
self._indeicatorView?.layer.transform = CATransform3DRotate((self._indeicatorView?.layer.transform)!,CGFloat(Float(179)/180*3.145),0, 0, 1)
self.viewRotat(cishu-1, lastAngle: lastAngle, miao: miao)
}
}
}
|
apache-2.0
|
a74dc9eb16855572aa6500315d2f1de1
| 28.714286 | 161 | 0.584736 | 4.053593 | false | false | false | false |
StevenDXC/SwiftDemo
|
Carthage/Checkouts/Kingfisher/Demo/Kingfisher-Demo/ViewController.swift
|
3
|
4256
|
//
// ViewController.swift
// Kingfisher-Demo
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Kingfisher
class ViewController: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
title = "Kingfisher"
if #available(iOS 10.0, tvOS 10.0, *) {
collectionView?.prefetchDataSource = self
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func clearCache(sender: AnyObject) {
KingfisherManager.shared.cache.clearMemoryCache()
KingfisherManager.shared.cache.clearDiskCache()
}
@IBAction func reload(sender: AnyObject) {
collectionView?.reloadData()
}
}
extension ViewController {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
// This will cancel all unfinished downloading task when the cell disappearing.
(cell as! CollectionViewCell).cellImageView.kf.cancelDownloadTask()
}
override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let url = URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-\(indexPath.row + 1).jpg")!
_ = (cell as! CollectionViewCell).cellImageView.kf.setImage(with: url,
placeholder: nil,
options: [.transition(ImageTransition.fade(1))],
progressBlock: { receivedSize, totalSize in
print("\(indexPath.row + 1): \(receivedSize)/\(totalSize)")
},
completionHandler: { image, error, cacheType, imageURL in
print("\(indexPath.row + 1): Finished")
})
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! CollectionViewCell
cell.cellImageView.kf.indicatorType = .activity
return cell
}
}
extension ViewController: UICollectionViewDataSourcePrefetching {
func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
let urls = indexPaths.flatMap {
URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-\($0.row + 1).jpg")
}
ImagePrefetcher(urls: urls).start()
}
}
|
mit
|
70fc3d6f64851c2e8715f763d733377d
| 41.56 | 155 | 0.662594 | 5.340025 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial
|
v2.x/Showcase/SciChartShowcase/SciChartShowcaseDemo/TraderChartsExample/Controller/TraderExampleViewController.swift
|
1
|
20022
|
//
// TraderExampleViewController.swift
// SciChartShowcaseDemo
//
// Created by Hrybeniuk Mykola on 7/13/17.
// Copyright © 2017 SciChart Ltd. All rights reserved.
//
import Foundation
struct AxisIds {
static let volumeYAxisId = "volumeYAxis"
}
struct ContextMenu {
static let upItemId = "upItemId"
static let downItemId = "downItemId"
static let lineItemId = "lineItemId"
static let textItemId = "textItemId"
static let themeItemId = "themeItemId"
}
class TraderExampleViewController : BaseViewController, GNAMenuItemDelegate {
//MARK: Filter Buttons
@IBOutlet weak var stockTypeButton: UIButton!
@IBOutlet weak var timePeriodButton: UIButton!
@IBOutlet weak var timeScaleButton: UIButton!
@IBOutlet weak var filterPanelView: UIView!
//MARK: Chart Surfaces
@IBOutlet weak var mainPaneChartSurface: SCIChartSurface!
@IBOutlet weak var subPaneRsiChartSurface: SCIChartSurface!
@IBOutlet weak var subPaneMcadChartSurface: SCIChartSurface!
//MARK: Resize Dividers
@IBOutlet weak var topSeparatorView: DividerView!
@IBOutlet weak var bottomSeparatorView: DividerView!
@IBOutlet weak var noInternetConnectionLabel: UILabel!
// MARK: Constraints for no internet connection message showing and hiding
@IBOutlet weak var filterPanelHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var noInternetConnectionLeftConstraint: NSLayoutConstraint!
// MARK: Panels Constraints
@IBOutlet var mainPanelToMcadPanelConstraint: NSLayoutConstraint! // Default is not active
@IBOutlet var mainPanelToRsiPanelConstraint: NSLayoutConstraint!
@IBOutlet var rsiPanelToMcadPanelConstraint: NSLayoutConstraint!
@IBOutlet var rsiPanelHeightConstraint: NSLayoutConstraint!
@IBOutlet var macdPanelHeightConstraint: NSLayoutConstraint!
// MARK: Ivar
private var temporaryGesture: UIPanGestureRecognizer!
private var lastLineAnnotation: SCILineAnnotation!
private var surfacesConfigurator: TraderChartSurfacesConfigurator!
private var menuView : GNAMenuView!
private var defaultFrameView = CGRect()
private var traderModel: TraderViewModel! {
didSet {
surfacesConfigurator.setupSurfacesWithTraderModel(with: self.traderModel)
stockTypeButton.setTitle(self.traderModel.stockType.description, for: .normal)
timeScaleButton.setTitle(self.traderModel.timeScale.description, for: .normal)
timePeriodButton.setTitle(self.traderModel.timePeriod.description, for: .normal)
}
}
// MARK: Overrided methods
override func viewDidLoad() {
super.viewDidLoad()
surfacesConfigurator = TraderChartSurfacesConfigurator(with: mainPaneChartSurface, subPaneRsiChartSurface, subPaneMcadChartSurface)
surfacesConfigurator.textAnnotationsKeyboardEventsHandler = {[unowned self] (notification, textView) -> () in
if notification.name == NSNotification.Name.UIKeyboardWillShow {
self.defaultFrameView = self.view.frame
let windowFrame = self.view.frame
let finalkeyboardFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect
let visibleRect = CGRect(x: 0.0, y: 0.0, width: windowFrame.size.width, height: (finalkeyboardFrame?.origin.y)!)
let rectInWindow = textView.superview?.convert(textView.frame, to: self.view)
if visibleRect.contains(rectInWindow!) {
print("Text View is visible")
}
else {
print("Text View is hidden")
let difference = (finalkeyboardFrame?.origin.y)! - ((rectInWindow?.origin.y)!+(rectInWindow?.height)!)
UIView.animate(withDuration: 0.25, animations: {
self.view.frame = CGRect(x: 0.0, y: difference, width: self.view.frame.size.width, height: self.view.frame.size.height)
})
}
}
else {
UIView.animate(withDuration: 0.25, animations: {
if let windowFrame = self.view.window?.frame {
self.view.frame = CGRect(x: 0.0, y: windowFrame.size.height - self.view.frame.size.height,
width: self.view.frame.size.width, height: self.view.frame.size.height)
}
})
}
}
NotificationCenter.default.addObserver(self, selector: #selector(internetConnectionStatusChanged), name: .flagsChanged, object: Network.reachability)
createMenuItem()
}
override func viewWillAppear(_ animated: Bool) {
loadTradeModel()
navigationController?.navigationBar.isHidden = false
topSeparatorView.superview?.bringSubview(toFront: topSeparatorView)
bottomSeparatorView.superview?.bringSubview(toFront: bottomSeparatorView)
updateInternetConnectionInfo(false)
let barButton = UIBarButtonItem(title: "Surface List", style: .plain, target: self, action: #selector(addSurfaceClick))
navigationItem.setRightBarButton(barButton, animated: true)
if !UserDefaults.isInstructedTraderExample() {
let guideViewNib = Bundle.main.loadNibNamed("TraderGuideView", owner: nil, options: nil)
if let guideView = guideViewNib?.first as? UIView {
guideView.frame = view.bounds
guideView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleGuideTap)))
view.addSubview(guideView)
}
}
else {
view.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress)))
}
}
// MARK: Private Methods
@objc private func handleGuideTap(_ sender: UITapGestureRecognizer) {
UserDefaults.setInstructedTraderExample()
sender.view?.removeFromSuperview()
view.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress)))
}
private func createMenuItem() {
let item1 = GNAMenuItem(icon: UIImage(named: "upContextMenu")!, activeIcon: UIImage(named: "upContextMenu"), title: "Up", frame: CGRect(x: 0.0, y: 0.0, width: 50, height: 50))
item1.defaultLabelMargin = 20
item1.itemId = ContextMenu.upItemId
let item2 = GNAMenuItem(icon: UIImage(named: "downContextMenu")!, activeIcon: UIImage(named: "downContextMenu"), title: "Down", frame: CGRect(x: 0.0, y: 0.0, width: 50, height: 50))
item2.defaultLabelMargin = 20
item2.itemId = ContextMenu.downItemId
let item3 = GNAMenuItem(icon: UIImage(named: "contextText")!, activeIcon: UIImage(named: "contextText"), title: "Text", frame: CGRect(x: 0.0, y: 0.0, width: 50, height: 50))
item3.defaultLabelMargin = 20
item3.itemId = ContextMenu.textItemId
let item4 = GNAMenuItem(icon: UIImage(named: "contextLine")!, activeIcon: UIImage(named: "contextLine"), title: "Line", frame: CGRect(x: 0.0, y: 0.0, width: 50, height: 50))
item4.defaultLabelMargin = 20
item4.itemId = ContextMenu.lineItemId
let item5 = GNAMenuItem(icon: UIImage(named: "contextBrush")!, activeIcon: UIImage(named: "contextBrush"), title: "Change Theme", frame: CGRect(x: 0.0, y: 0.0, width: 50, height: 50))
item5.defaultLabelMargin = 20
item5.itemId = ContextMenu.themeItemId
menuView = GNAMenuView(touchPointSize: CGSize(width: 160, height: 160),
touchImage: nil,
menuItems:[item1, item2, item3, item4, item5])
menuView.delegate = self
}
private func loadTradeModel(_ stockType: StockIndex = .Apple, _ timeScale: TimeScale = .day, _ timePeriod: TimePeriod = .year) {
startLoading()
DataManager.getPrices(with: timeScale, timePeriod, stockType, handler: { (viewModel, errorMessage) in
if self.traderModel != nil {
let previousIndicators = self.traderModel.traderIndicators
var updatedViewModel = viewModel
updatedViewModel.traderIndicators = previousIndicators
self.traderModel = updatedViewModel
self.surfacesConfigurator.tryToSetLastVisibleRange()
}
else {
self.traderModel = viewModel
}
if let errorMessage = errorMessage {
self.setupErrorMessageWith(errorMessage)
self.showNoInternetConnection(true)
}
else {
self.hideNoInternetConnection(true)
}
self.stopLoading()
})
}
private func showAlertController(_ alert: UIAlertController, _ senderFrame: CGRect) {
if let controller = alert.popoverPresentationController {
controller.sourceView = view
controller.sourceRect = senderFrame
}
present(alert, animated: true, completion: nil)
}
private func setupErrorMessageWith(_ errorMessage: (title: String, description: String?)) {
let errorAttributed = NSMutableAttributedString(string: errorMessage.title,
attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 14),
NSAttributedStringKey.foregroundColor : UIColor.white])
if let description = errorMessage.description {
errorAttributed.append(NSAttributedString(string: "\n"))
errorAttributed.append(NSAttributedString(string: description, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 10),
NSAttributedStringKey.foregroundColor : UIColor.white]))
}
self.noInternetConnectionLabel.attributedText = errorAttributed
}
@objc private func internetConnectionStatusChanged() {
updateInternetConnectionInfo(true)
}
private func updateInternetConnectionInfo(_ animated: Bool = true) {
setupErrorMessageWith(NetworkDomainErrors.noInternetConnection)
guard let reachability = Network.reachability else {
showNoInternetConnection(animated)
return
}
if reachability.status == .wwan || reachability.status == .wifi || (!reachability.isRunningOnDevice && reachability.isConnectedToNetwork) {
hideNoInternetConnection(animated)
}
else {
showNoInternetConnection(animated)
}
}
private func showNoInternetConnection(_ animated: Bool = true) {
noInternetConnectionLeftConstraint.constant = view.frame.size.width
filterPanelHeightConstraint.constant = 30.0
noInternetConnectionLabel.layoutSubviews()
noInternetConnectionLabel.isHidden = false
noInternetConnectionLeftConstraint.constant = 0.0
filterPanelHeightConstraint.constant = 40.0
filterPanelView.isUserInteractionEnabled = false
if animated {
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}
else {
self.view.layoutIfNeeded()
}
}
private func hideNoInternetConnection(_ animated: Bool = true) {
noInternetConnectionLeftConstraint.constant = self.view.frame.size.width
filterPanelHeightConstraint.constant = 30.0
filterPanelView.isUserInteractionEnabled = true
if animated {
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
}) { (finished) in
if finished {
self.noInternetConnectionLabel.isHidden = true
}
}
}
else {
view.layoutIfNeeded()
noInternetConnectionLabel.isHidden = true
}
}
private func setupView(with indicators: [TraderIndicators]) {
let previuosState = traderModel.traderIndicators
traderModel.traderIndicators = indicators
if indicators.contains(.rsiPanel) && !previuosState.contains(.rsiPanel) ||
!indicators.contains(.rsiPanel) && previuosState.contains(.rsiPanel) ||
indicators.contains(.macdPanel) && !previuosState.contains(.macdPanel) ||
!indicators.contains(.macdPanel) && previuosState.contains(.macdPanel) {
redrawPanels(with: indicators)
}
surfacesConfigurator.setupOnlyIndicators(indicators)
}
private func redrawPanels(with indicators:[TraderIndicators]) {
if indicators.contains(.macdPanel) && indicators.contains(.rsiPanel) {
subPaneRsiChartSurface.isHidden = false
subPaneMcadChartSurface.isHidden = false
bottomSeparatorView.isHidden = false
rsiPanelHeightConstraint.isActive = false
macdPanelHeightConstraint.isActive = false
mainPanelToMcadPanelConstraint.isActive = false
mainPanelToRsiPanelConstraint.isActive = true
rsiPanelToMcadPanelConstraint.isActive = true
topSeparatorView.relationConstraint = mainPanelToRsiPanelConstraint
}
else if !indicators.contains(.macdPanel) && !indicators.contains(.rsiPanel) {
subPaneRsiChartSurface.isHidden = false
subPaneMcadChartSurface.isHidden = false
bottomSeparatorView.isHidden = false
topSeparatorView.isHidden = false
mainPanelToRsiPanelConstraint.isActive = false
mainPanelToMcadPanelConstraint.isActive = false
rsiPanelToMcadPanelConstraint.isActive = false
rsiPanelHeightConstraint.isActive = true
macdPanelHeightConstraint.isActive = true
}
else if indicators.contains(.rsiPanel) && !indicators.contains(.macdPanel) {
// Show rsi panel
topSeparatorView.relationConstraint = mainPanelToRsiPanelConstraint
rsiPanelHeightConstraint.isActive = false
subPaneRsiChartSurface.isHidden = false
mainPanelToRsiPanelConstraint.isActive = true
// Hide macd panel
rsiPanelToMcadPanelConstraint.isActive = false
macdPanelHeightConstraint.isActive = true
bottomSeparatorView.isHidden = true
subPaneMcadChartSurface.isHidden = true
}
else if !indicators.contains(.rsiPanel) && indicators.contains(.macdPanel) {
// Hide rsi panel
mainPanelToRsiPanelConstraint.isActive = false
subPaneRsiChartSurface.isHidden = true
bottomSeparatorView.isHidden = true
rsiPanelHeightConstraint.isActive = true
rsiPanelToMcadPanelConstraint.isActive = false
// Show macd panel
topSeparatorView.relationConstraint = mainPanelToMcadPanelConstraint
mainPanelToMcadPanelConstraint.isActive = true
subPaneMcadChartSurface.isHidden = false
macdPanelHeightConstraint.isActive = false
}
view.layoutIfNeeded()
}
// MARK: IBActions
@objc private func handleLongPress(gesture: UILongPressGestureRecognizer) {
let point = gesture.location(in: view)
if mainPaneChartSurface.frame.contains(point) ||
subPaneRsiChartSurface.frame.contains(point) ||
subPaneMcadChartSurface.frame.contains(point)
{
menuView.handleGesture(gesture, inView: view)
}
}
@objc private func addSurfaceClick(_ sender: UIBarButtonItem) {
let selectionController = MultipleSelectionViewController<TraderIndicators>(nibName: "MultipleSelectionViewController", bundle: nil)
selectionController.setupList(with: TraderIndicators.allValues, selected: traderModel.traderIndicators) { (selectedItems) in
self.setupView(with: selectedItems)
}.showWithCrossDissolveStyle(over: self)
}
@IBAction func stockTypeClick(_ sender: UIButton) {
let actionSheet = UIAlertController(title: "Choose Stock Index", message: "", preferredStyle: .actionSheet).fillActions(actions: StockIndex.allValues) { (stockType) in
if let stockTypeNonNil = stockType {
self.loadTradeModel(stockTypeNonNil, self.traderModel.timeScale, self.traderModel.timePeriod)
}
}
showAlertController(actionSheet, sender.frame)
}
@IBAction func timeScaleClick(_ sender: UIButton) {
surfacesConfigurator.saveCurrentVisibleRange()
let actionSheet = UIAlertController(title: "Choose Time Scale", message: "", preferredStyle: .actionSheet).fillActions(actions: TimeScale.allValues) { (timeScale) in
if let timeScaleNonNil = timeScale {
self.loadTradeModel(self.traderModel.stockType, timeScaleNonNil, self.traderModel.timePeriod)
}
}
showAlertController(actionSheet, sender.frame)
}
@IBAction func timePeriodClick(_ sender: UIButton) {
let actionSheet = UIAlertController(title: "Choose Time Period", message: "", preferredStyle: .actionSheet).fillActions(actions: TimePeriod.allValues) { (timePeriod) in
if let timePeriodNonNil = timePeriod {
self.loadTradeModel(self.traderModel.stockType, self.traderModel.timeScale, timePeriodNonNil)
}
}
showAlertController(actionSheet, sender.frame)
}
// MARK: GNAMenuItemDelegate
func menuItemWasPressed(_ menuItem: GNAMenuItem, info: [String : Any]?) {
if menuItem.itemId == ContextMenu.downItemId {
surfacesConfigurator.enableCreationDownAnnotation()
}
else if menuItem.itemId == ContextMenu.upItemId {
surfacesConfigurator.enableCreationUpAnnotation()
}
else if menuItem.itemId == ContextMenu.lineItemId {
surfacesConfigurator.enableCreationLineAnnotation()
}
else if menuItem.itemId == ContextMenu.textItemId {
surfacesConfigurator.enableCreationTextAnnotation()
}
else {
surfacesConfigurator.changeTheme()
}
applyTheme(with: surfacesConfigurator.currentTheme())
}
private func applyTheme(with themeKey: String) {
if themeKey == SCIChart_SciChartv4DarkStyleKey {
filterPanelView.backgroundColor = UIColor.filterTraderDarkColor()
timeScaleButton.setTitleColor(UIColor.filterTraderLightColor(), for: .normal)
timePeriodButton.setTitleColor(UIColor.filterTraderLightColor(), for: .normal)
stockTypeButton.setTitleColor(UIColor.filterTraderLightColor(), for: .normal)
view.backgroundColor = UIColor.traderDarkRootViewColor()
}
else {
filterPanelView.backgroundColor = UIColor.filterTraderLightColor()
timeScaleButton.setTitleColor(UIColor.filterTraderDarkColor(), for: .normal)
timePeriodButton.setTitleColor(UIColor.filterTraderDarkColor(), for: .normal)
stockTypeButton.setTitleColor(UIColor.filterTraderDarkColor(), for: .normal)
view.backgroundColor = UIColor.traderLightRootViewColor()
}
}
}
|
mit
|
bb69a13c352a90c8ed35e564f85c8bf6
| 42.905702 | 191 | 0.642226 | 5.066043 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceModel/Sources/EurofurenceModel/Public/Server Client/JSON/JSONAPI.swift
|
1
|
7790
|
import Foundation
// swiftlint:disable nesting
public struct JSONAPI: API {
// MARK: Properties
private let jsonSession: JSONSession
private let apiUrl: String
private let decoder: JSONDecoder
private let encoder: JSONEncoder
// MARK: Initialization
public init(jsonSession: JSONSession, apiUrl: APIURLProviding) {
self.jsonSession = jsonSession
self.apiUrl = {
var url = apiUrl.url
if url.hasSuffix("/") {
url.removeLast()
}
return url
}()
// TODO: Investigate why system ios8601 formatter fails to parse our dates
decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(Iso8601DateFormatter())
encoder = JSONEncoder()
}
// MARK: LoginAPI
public func performLogin(request: LoginRequest, completionHandler: @escaping (LoginResponse?) -> Void) {
let url = urlStringByAppending(pathComponent: "Tokens/RegSys")
let request = Request.Login(RegNo: request.regNo, Username: request.username, Password: request.password)
guard let jsonData = try? encoder.encode(request) else { return }
let jsonRequest = JSONRequest(url: url, body: jsonData)
jsonSession.post(jsonRequest) { (data, _) in
if let data = data, let response = try? self.decoder.decode(Response.Login.self, from: data) {
completionHandler(response.makeDomainLoginResponse())
} else {
completionHandler(nil)
}
}
}
// MARK: ImageAPI
public func fetchImage(identifier: String, contentHashSha1: String, completionHandler: @escaping (Data?) -> Void) {
let url = urlStringByAppending(pathComponent: "Images/\(identifier)/Content/with-hash:\(contentHashSha1)")
let request = JSONRequest(url: url)
jsonSession.get(request) { (data, _) in
completionHandler(data)
}
}
// MARK: PrivateMessagesAPI
public func loadPrivateMessages(
authorizationToken: String,
completionHandler: @escaping ([MessageCharacteristics]?) -> Void
) {
let url = urlStringByAppending(pathComponent: "Communication/PrivateMessages")
var request = JSONRequest(url: url)
request.headers = ["Authorization": "Bearer \(authorizationToken)"]
jsonSession.get(request) { (data, _) in
var messages: [MessageCharacteristics]?
defer { completionHandler(messages) }
guard let data = data else { return }
if let jsonMessages = try? self.decoder.decode([Response.Message].self, from: data) {
messages = jsonMessages.map({ $0.makeAppDomainMessage() })
}
}
}
public func markMessageWithIdentifierAsRead(_ identifier: String, authorizationToken: String) {
let url = urlStringByAppending(pathComponent: "Communication/PrivateMessages/\(identifier)/Read")
guard let messageContentsToSupportSwagger = "true".data(using: .utf8) else { fatalError() }
var request = JSONRequest(url: url, body: messageContentsToSupportSwagger)
request.headers = ["Authorization": "Bearer \(authorizationToken)"]
jsonSession.post(request, completionHandler: { (_, _) in })
}
// MARK: SyncAPI
public func fetchLatestData(lastSyncTime: Date?, completionHandler: @escaping (ModelCharacteristics?) -> Void) {
let sinceParameterPathComponent: String = {
if let lastSyncTime = lastSyncTime {
let formattedTime = Iso8601DateFormatter.instance.string(from: lastSyncTime)
return "?since=\(formattedTime)"
} else {
return ""
}
}()
let url = urlStringByAppending(pathComponent: "Sync\(sinceParameterPathComponent)")
let request = JSONRequest(url: url, body: Data())
jsonSession.get(request) { (data, _) in
var response: ModelCharacteristics?
defer { completionHandler(response) }
if let data = data {
do {
let decodedResponse = try self.decoder.decode(JSONSyncResponse.self, from: data)
response = decodedResponse.asAPIResponse()
} catch {
print(error)
}
}
}
}
public func submitEventFeedback(_ request: EventFeedbackRequest, completionHandler: @escaping (Bool) -> Void) {
let feedback = Request.EventFeedback(EventId: request.id, Rating: request.starRating, Message: request.feedback)
guard let data = try? encoder.encode(feedback) else { return }
let url = urlStringByAppending(pathComponent: "EventFeedback")
let jsonRequest = JSONRequest(url: url, body: data)
jsonSession.post(jsonRequest) { (_, error) in
let successful = error == nil
completionHandler(successful)
}
}
// MARK: Private
private func urlStringByAppending(pathComponent: String) -> String {
return "\(apiUrl)/\(pathComponent)"
}
private struct Request {
struct Login: Encodable {
var RegNo: Int
var Username: String
var Password: String
}
struct EventFeedback: Encodable {
var EventId: String
var Rating: Int
var Message: String
}
}
private struct Response {
struct Login: Decodable {
var Uid: String
var Username: String
var Token: String
var TokenValidUntil: Date
func makeDomainLoginResponse() -> LoginResponse {
return LoginResponse(
userIdentifier: Uid,
username: Username,
token: Token,
tokenValidUntil: TokenValidUntil
)
}
}
struct Message: Decodable {
var id: String
var authorName: String
var subject: String
var message: String
var receivedDateTime: Date
var readDateTime: Date?
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
authorName = try container.decode(String.self, forKey: .authorName)
subject = try container.decode(String.self, forKey: .subject)
message = try container.decode(String.self, forKey: .message)
receivedDateTime = try container.decode(Date.self, forKey: .receivedDateTime)
if let readTime = ((try? container.decodeIfPresent(Date.self, forKey: .readDateTime)) as Date??) {
readDateTime = readTime
}
}
private enum CodingKeys: String, CodingKey {
case id = "Id"
case authorName = "AuthorName"
case subject = "Subject"
case message = "Message"
case receivedDateTime = "ReceivedDateTimeUtc"
case readDateTime = "ReadDateTimeUtc"
}
func makeAppDomainMessage() -> EurofurenceModel.MessageCharacteristics {
return MessageCharacteristics(
identifier: id,
authorName: authorName,
receivedDateTime: receivedDateTime,
subject: subject,
contents: message,
isRead: readDateTime != nil
)
}
}
}
}
|
mit
|
a803ff5e6b920a3a86c2930e0d7467fc
| 34.248869 | 120 | 0.58267 | 5.339273 | false | false | false | false |
igerry/ProjectEulerInSwift
|
ProjectEulerInSwift/Euler/Problem10.swift
|
1
|
542
|
import Foundation
/*
Summation of primes
Problem 10
142913828922
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
*/
class Problem10 {
func solution() -> Int {
var sum:Int = 0
let primes:NSMutableArray = []
var nextPrime = 0
while nextPrime < 2000000 {
sum += nextPrime
nextPrime = DWCommon.getNextPrime(primes)
print("\(nextPrime)")
}
return sum
}
}
|
apache-2.0
|
ab5565a8a78c1326f70e239fe461f6e3
| 17.689655 | 54 | 0.5369 | 4.336 | false | false | false | false |
justin/Aspen
|
Aspen/LogLevel.swift
|
1
|
3311
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Justin Williams
//
// 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
@objc
public enum DefaultLogLevel: Int {
case verbose = 200
case info = 300
case warning = 400
case error = 500
}
public final class LogLevel {
public var level: DefaultLogLevel
public var name: String
public var label: String
internal static let VERBOSE_LEVEL = LogLevel.makeLevel(level: .verbose, name: "Verbose Level", label: "VERBOSE")
internal static let INFO_LEVEL = LogLevel.makeLevel(level: .info, name: "Info Level", label: "INFO")
internal static let WARNING_LEVEL = LogLevel.makeLevel(level: .warning, name: "Warning Level", label: "WARN")
internal static let ERROR_LEVEL = LogLevel.makeLevel(level: .error, name: "Error Level", label: "ERROR")
// MARK: Initialization
// ====================================
// Initialization
// ====================================
public init(level: DefaultLogLevel, name: String, label: String) {
self.level = level
self.name = name
self.label = label
}
public static func getLevel(_ level:DefaultLogLevel) -> LogLevel {
switch level {
case .verbose:
return VERBOSE_LEVEL
case .info:
return INFO_LEVEL
case .warning:
return WARNING_LEVEL
case .error:
return ERROR_LEVEL
}
}
public func emojiIdentifier() -> String {
switch level {
case .verbose:
return "🚧"
case .info:
return "☝️"
case .warning:
return "⚠️"
case .error:
return "🚨"
}
}
}
extension LogLevel: Equatable { }
public func ==(lhs: LogLevel, rhs: LogLevel) -> Bool {
return (lhs.level.rawValue == rhs.level.rawValue)
}
// MARK: Private / Convenience
// ====================================
// Private / Convenience
// ====================================
private extension LogLevel {
static func makeLevel(level: DefaultLogLevel, name: String, label: String) -> LogLevel {
return LogLevel(level:level, name: name, label: label)
}
}
|
mit
|
9881e15fd53b997cc8f2b14de2561742
| 34.074468 | 116 | 0.622687 | 4.528846 | false | false | false | false |
mmoaay/MBMotion
|
Example/MBMotion/MBMotionActionSheetDemoViewController.swift
|
1
|
1753
|
//
// MBMotionActionSheetDemoViewController.swift
// MBMotion
//
// Created by Perry on 15/12/7.
// Copyright © 2015年 MmoaaY. All rights reserved.
//
import UIKit
import MBMotion
class MBMotionActionSheetDemoViewController: UIViewController,MBMotionContentViewDelegate {
var actionSheet:MBMotionActionSheet?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let contentView = MBMotionContentView()
self.actionSheet = MBMotionActionSheet(containerView: self.navigationController?.view, contentView: contentView.getContentView())
contentView.delegate = self
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.actionSheet?.removeActionSheet()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func switchButtonPressed(_ status:MBMotionHamburgButtonStatus) {
if MBMotionHamburgButtonStatus.open == status {
self.actionSheet?.expandActionSheet()
} else {
self.actionSheet?.collapseActionSheet()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
9c52f00532529fb726221e454df2b5cc
| 29.172414 | 137 | 0.680571 | 5.208333 | false | false | false | false |
daltoniam/Jazz
|
Sources/LoadingView.swift
|
1
|
6468
|
//
// LoadingView.swift
//
// Created by Dalton Cherry on 3/11/15.
// Copyright (c) 2015 Vluxe. All rights reserved.
//
import UIKit
public struct Pose {
let speed: CFTimeInterval //the speed the animation (the first one in the poses array should be zero)
let rotationDegrees: CGFloat //set how many degrees the view should rotate by (normally the degrees increase with each pose)
let length: CGFloat //the length of the progress field to fill
public init(_ speed: CFTimeInterval, _ rotationDegrees: CGFloat, _ length: CGFloat) {
self.speed = speed
self.rotationDegrees = rotationDegrees
self.length = length
}
}
open class LoadingView : UIView, CAAnimationDelegate {
override open var layer: CAShapeLayer {
get {
return super.layer as! CAShapeLayer
}
}
open var poses = [Pose(0.0, 215, 0.3), Pose(0.9, 360, 0.8), Pose(0.5, 575, 0.3)] {
didSet {
needsRefresh = true
}
}
open var color = UIColor.black {
didSet {
doStrokeColor()
}
}
open var lineWidth: CGFloat = 3.0 {
didSet {
doLineWidth()
}
}
open var lineCap = kCALineCapRound {
didSet {
drawPath()
}
}
override open var frame: CGRect {
willSet {
layer.transform = CATransform3DIdentity
}
didSet {
if let last = poses.last, isRunning {
layer.transform = CATransform3DMakeRotation(Jazz.degreesToRadians(last.rotationDegrees), 0, 0, 1)
}
}
}
override open var isHidden: Bool {
get {
return super.isHidden
}
set(v) {
super.isHidden = v
if v {
stop()
}
}
}
//NOTE!!!
//The startPoint and progress properties should not be used at the same time as the start and stop methods. It just doesn't make sense.
open var startPoint: CGFloat = 270
//provide a value between 0 and 1
open var progress: CGFloat = 0 {
didSet {
poses = [Pose(0.0, startPoint, oldProgress), Pose(0.9, startPoint, progress)]
isRunning = true
doAnimation()
isRunning = false
oldProgress = progress
}
}
var oldProgress: CGFloat = 0
var isRunning = false
var needsRefresh = false
var didStop: (() -> Void)?
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
//setup the properties
func commonInit() {
isUserInteractionEnabled = false
backgroundColor = UIColor.clear
}
//start the animation
open func start() {
if isRunning {
return
}
isRunning = true
doAnimation()
}
//stop the animation
open func stop(_ completion: (() -> Void)? = nil) {
isRunning = false
didStop = completion
}
func doAnimation() {
if !needsRefresh && !isRunning {
isRunning = false
layer.removeAllAnimations()
return
}
needsRefresh = false
if poses.count == 0 {
return //no pose, no animation
}
var time: CFTimeInterval = 0
var times = [CFTimeInterval]()
var rotations = [CGFloat]()
var strokeEnds = [CGFloat]()
let totalSeconds = poses.reduce(0) { $0 + $1.speed }
for pose in poses {
time += pose.speed
times.append(time / totalSeconds)
rotations.append(Jazz.degreesToRadians(pose.rotationDegrees)) //pose.rotationStart * 2 * CGFloat(M_PI)
strokeEnds.append(pose.length)
}
animateKeyPath("strokeEnd", duration: totalSeconds, times: times, values: strokeEnds)
animateKeyPath("transform.rotation", duration: totalSeconds, times: times, values: rotations)
layer.strokeEnd = strokeEnds.last!
layer.transform = CATransform3DMakeRotation(rotations.last!, 0, 0, 1)
}
open func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if isRunning || needsRefresh {
doAnimation()
} else if let complete = didStop {
complete()
didStop = nil
}
}
func animateKeyPath(_ keyPath: String, duration: CFTimeInterval, times: [CFTimeInterval], values: [CGFloat]) {
let animation = CAKeyframeAnimation(keyPath: keyPath)
animation.keyTimes = times as [NSNumber]?
animation.values = values
animation.calculationMode = kCAAnimationLinear
animation.duration = duration
if keyPath == "strokeEnd" {
animation.delegate = self
}
layer.add(animation, forKey: animation.keyPath)
}
override open func layoutSubviews() {
super.layoutSubviews()
drawPath()
layer.path = UIBezierPath(ovalIn: bounds.insetBy(dx: layer.lineWidth / 2, dy: layer.lineWidth / 2)).cgPath
if let last = poses.last , isRunning {
layer.transform = CATransform3DMakeRotation(Jazz.degreesToRadians(last.rotationDegrees), 0, 0, 1)
}
}
func drawPath() {
layer.fillColor = nil
layer.strokeColor = color.cgColor
layer.lineWidth = lineWidth
layer.lineCap = lineCap
}
//do that fill color
func doStrokeColor() {
let animation = Jazz.createAnimation(key: "strokeColor")
animation.fromValue = layer.strokeColor
animation.toValue = color.cgColor
layer.add(animation, forKey: Jazz.oneShotKey())
layer.strokeColor = color.cgColor
}
func doLineWidth() {
let bWidth = Jazz.createAnimation(key: "lineWidth")
bWidth.fromValue = layer.lineWidth
bWidth.toValue = lineWidth
layer.add(bWidth, forKey: Jazz.oneShotKey())
layer.lineWidth = lineWidth
}
//set the layer of this view to be a shape
open override class var layerClass : AnyClass {
return CAShapeLayer.self
}
open override func removeFromSuperview() {
super.removeFromSuperview()
stop()
}
deinit {
stop()
}
}
|
apache-2.0
|
31b7c13ca0fc8f1fa002b1b7adfc34c9
| 28.534247 | 139 | 0.578695 | 4.784024 | false | false | false | false |
yangchenghu/actor-platform
|
actor-apps/app-ios/ActorApp/Controllers/Auth/AuthCountriesViewController.swift
|
10
|
5674
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
protocol AuthCountriesViewControllerDelegate : NSObjectProtocol {
func countriesController(countriesController: AuthCountriesViewController, didChangeCurrentIso currentIso: String)
}
class AuthCountriesViewController: AATableViewController {
// MARK: -
// MARK: Private vars
private let countryCellIdentifier = "countryCellIdentifier"
private var _countries: NSDictionary!
private var _letters: NSArray!
// MARK: -
// MARK: Public vars
weak var delegate: AuthCountriesViewControllerDelegate?
var currentIso: String = ""
// MARK: -
// MARK: Contructors
init() {
super.init(style: UITableViewStyle.Plain)
self.title = "Country" // TODO: Localize
let cancelButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("cancelButtonPressed")) // TODO: Localize
self.navigationItem.setLeftBarButtonItem(cancelButtonItem, animated: false)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(AuthCountryCell.self, forCellReuseIdentifier: countryCellIdentifier)
tableView.tableFooterView = UIView()
tableView.rowHeight = 44.0
tableView.sectionIndexBackgroundColor = UIColor.clearColor()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
MainAppTheme.navigation.applyStatusBar()
Actor.trackAuthCountryOpen()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
Actor.trackAuthCountryClosed()
}
// MARK: -
// MARK: Methods
func cancelButtonPressed() {
dismiss()
}
// MARK: -
// MARK: Getters
private func countries() -> NSDictionary {
if (_countries == nil) {
var countries = NSMutableDictionary()
for (index, iso) in ABPhoneField.sortedIsoCodes().enumerate() {
let countryName = ABPhoneField.countryNameByCountryCode()[iso as! String] as! String
let phoneCode = ABPhoneField.callingCodeByCountryCode()[iso as! String] as! String
// if (self.searchBar.text.length == 0 || [countryName rangeOfString:self.searchBar.text options:NSCaseInsensitiveSearch].location != NSNotFound)
let countryLetter = countryName.substringToIndex(countryName.startIndex.advancedBy(1))
if (countries[countryLetter] == nil) {
countries[countryLetter] = NSMutableArray()
}
countries[countryLetter]!.addObject([countryName, iso, phoneCode])
}
_countries = countries;
}
return _countries;
}
private func letters() -> NSArray {
if (_letters == nil) {
_letters = (countries().allKeys as NSArray).sortedArrayUsingSelector(Selector("compare:"))
}
return _letters;
}
// MARK: -
// MARK: UITableView Data Source
func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! {
return [UITableViewIndexSearch] + letters() as [AnyObject]
}
func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
if title == UITableViewIndexSearch {
return 0
}
return index - 1
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return letters().count;
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (countries()[letters()[section] as! String] as! NSArray).count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: AuthCountryCell = tableView.dequeueReusableCellWithIdentifier(countryCellIdentifier, forIndexPath: indexPath) as! AuthCountryCell
cell.setSearchMode(false) // TODO: Add search bar
let letter = letters()[indexPath.section] as! String
let countryData = (countries().objectForKey(letter) as! NSArray)[indexPath.row] as! [String]
cell.setTitle(countryData[0])
cell.setCode("+\(countryData[2])")
return cell
}
// MARK: -
// MARK: UITableView Delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if (delegate?.respondsToSelector(Selector("countriesController:didChangeCurrentIso:")) != nil) {
let letter = letters()[indexPath.section] as! String
let countryData = (countries().objectForKey(letter) as! NSArray)[indexPath.row] as! [String]
Actor.trackAuthCountryPickedWithCountry(countryData[1])
delegate!.countriesController(self, didChangeCurrentIso: countryData[1])
}
dismiss()
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 25.0
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let letter = letters()[section] as! String
return letter
}
}
|
mit
|
991306c4643501d169d82b96f5b47800
| 34.030864 | 172 | 0.640642 | 5.337723 | false | false | false | false |
steelwheels/Coconut
|
CoconutData/Source/Value/CNValueCaster.swift
|
1
|
695
|
/*
* @file CNValueCaster.swift
* @brief Define CNValueCaster class
* @par Copyright
* Copyright (C) 2022 Steel Wheels Project
*/
import Foundation
public func CNCastValue(from srcval: CNValue, to dsttyp: CNValueType) -> CNValue
{
let result: CNValue
switch srcval {
case .numberValue(let num):
switch dsttyp {
case .enumType(let etype):
if let eobj = etype.search(byValue: num.intValue) {
result = .enumValue(eobj)
} else {
CNLog(logLevel: .error, message: "Unexpected raw value \(num.intValue) for \(etype.typeName)", atFunction: #function, inFile: #file)
result = srcval
}
default:
result = srcval
}
default:
result = srcval
}
return result
}
|
lgpl-2.1
|
9b6e2cacce54f5e1824bd943bdee5b9d
| 21.419355 | 136 | 0.686331 | 3.102679 | false | false | false | false |
SuPair/firefox-ios
|
Providers/SyncStatusResolver.swift
|
8
|
4475
|
/* 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 Sync
import Shared
import Storage
public enum SyncDisplayState {
case inProgress
case good
case bad(message: String?)
case warning(message: String)
func asObject() -> [String: String]? {
switch self {
case .bad(let msg):
guard let message = msg else {
return ["state": "Error"]
}
return ["state": "Error",
"message": message]
case .warning(let message):
return ["state": "Warning",
"message": message]
default:
break
}
return nil
}
}
public func ==(a: SyncDisplayState, b: SyncDisplayState) -> Bool {
switch (a, b) {
case (.inProgress, .inProgress):
return true
case (.good, .good):
return true
case (.bad(let a), .bad(let b)) where a == b:
return true
case (.warning(let a), .warning(let b)) where a == b:
return true
default:
return false
}
}
/*
* Translates the fine-grained SyncStatuses of each sync engine into a more coarse-grained
* display-oriented state for displaying warnings/errors to the user.
*/
public struct SyncStatusResolver {
let engineResults: Maybe<EngineResults>
public func resolveResults() -> SyncDisplayState {
guard let results = engineResults.successValue else {
switch engineResults.failureValue {
case _ as BookmarksMergeError, _ as BufferInvalidError:
return SyncDisplayState.warning(message: String(format: Strings.FirefoxSyncPartialTitle, Strings.localizedStringForSyncComponent("bookmarks") ?? ""))
default:
return SyncDisplayState.bad(message: nil)
}
}
// Run through the engine results and produce a relevant display status for each one
let displayStates: [SyncDisplayState] = results.map { (engineIdentifier, syncStatus) in
print("Sync status for \(engineIdentifier): \(syncStatus)")
// Explicitly call out each of the enum cases to let us lean on the compiler when
// we add new error states
switch syncStatus {
case .notStarted(let reason):
switch reason {
case .offline:
return .bad(message: Strings.FirefoxSyncOfflineTitle)
case .noAccount:
return .warning(message: Strings.FirefoxSyncOfflineTitle)
case .backoff(_):
return .good
case .engineRemotelyNotEnabled(_):
return .good
case .engineFormatOutdated(_):
return .good
case .engineFormatTooNew(_):
return .good
case .storageFormatOutdated(_):
return .good
case .storageFormatTooNew(_):
return .good
case .stateMachineNotReady:
return .good
case .redLight:
return .good
case .unknown:
return .good
}
case .completed:
return .good
case .partial:
return .good
}
}
// TODO: Instead of finding the worst offender in a list of statuses, we should better surface
// what might have happened with a particular engine when syncing.
let aggregate: SyncDisplayState = displayStates.reduce(.good) { carried, displayState in
switch displayState {
case .bad(_):
return displayState
case .warning(_):
// If the state we're carrying is worse than the stale one, keep passing
// along the worst one
switch carried {
case .bad(_):
return carried
default:
return displayState
}
default:
// This one is good so just pass on what was being carried
return carried
}
}
print("Resolved sync display state: \(aggregate)")
return aggregate
}
}
|
mpl-2.0
|
11bfbbfdaafa7ee5cfc43fe37484707b
| 33.160305 | 165 | 0.544804 | 5.411125 | false | false | false | false |
swimmath27/GameOfGames
|
GameOfGames/extensions.swift
|
1
|
907
|
//
// Extensions.swift
// GameOfGames
//
// Created by Michael Lombardo on 5/31/16.
// Copyright © 2016 Michael Lombardo. All rights reserved.
//
import Foundation
extension MutableCollection where Indices.Iterator.Element == Index {
/// Shuffles the contents of this collection.
mutating func shuffle() {
let c = count
guard c > 1 else { return }
for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
guard d != 0 else { continue }
let i = index(firstUnshuffled, offsetBy: d)
swap(&self[firstUnshuffled], &self[i])
}
}
}
extension Sequence {
/// Returns an array with the contents of this sequence, shuffled.
func shuffled() -> [Iterator.Element] {
var result = Array(self)
result.shuffle()
return result
}
}
|
mit
|
68202761577a10e41190c6b0c6edd9c0
| 27.3125 | 93 | 0.669978 | 3.888412 | false | false | false | false |
visualitysoftware/swift-sdk
|
CloudBoost/SocketEngineSpec.swift
|
1
|
4218
|
//
// SocketEngineSpec.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 10/7/15.
//
// 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
@objc public protocol SocketEngineSpec {
weak var client: SocketEngineClient? { get set }
var closed: Bool { get }
var connected: Bool { get }
var connectParams: [String: AnyObject]? { get set }
var doubleEncodeUTF8: Bool { get }
var cookies: [NSHTTPCookie]? { get }
var extraHeaders: [String: String]? { get }
var fastUpgrade: Bool { get }
var forcePolling: Bool { get }
var forceWebsockets: Bool { get }
var parseQueue: dispatch_queue_t! { get }
var polling: Bool { get }
var probing: Bool { get }
var emitQueue: dispatch_queue_t! { get }
var handleQueue: dispatch_queue_t! { get }
var sid: String { get }
var socketPath: String { get }
var urlPolling: NSURL { get }
var urlWebSocket: NSURL { get }
var websocket: Bool { get }
init(client: SocketEngineClient, url: NSURL, options: NSDictionary?)
func connect()
func didError(error: String)
func disconnect(reason: String)
func doFastUpgrade()
func flushWaitingForPostToWebSocket()
func parseEngineData(data: NSData)
func parseEngineMessage(message: String, fromPolling: Bool)
func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData])
}
extension SocketEngineSpec {
var urlPollingWithSid: NSURL {
let com = NSURLComponents(URL: urlPolling, resolvingAgainstBaseURL: false)!
com.query = com.query! + "&sid=\(sid)"
return com.URL!
}
var urlWebSocketWithSid: NSURL {
let com = NSURLComponents(URL: urlWebSocket, resolvingAgainstBaseURL: false)!
com.query = com.query! + (sid == "" ? "" : "&sid=\(sid)")
return com.URL!
}
func createBinaryDataForSend(data: NSData) -> Either<NSData, String> {
if websocket {
var byteArray = [UInt8](count: 1, repeatedValue: 0x4)
let mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.appendData(data)
return .Left(mutData)
} else {
let str = "b4" + data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
return .Right(str)
}
}
func doubleEncodeUTF8(string: String) -> String {
if let latin1 = string.dataUsingEncoding(NSUTF8StringEncoding),
utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding) {
return utf8 as String
} else {
return string
}
}
func fixDoubleUTF8(string: String) -> String {
if let utf8 = string.dataUsingEncoding(NSISOLatin1StringEncoding),
latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding) {
return latin1 as String
} else {
return string
}
}
/// Send an engine message (4)
func send(msg: String, withData datas: [NSData]) {
write(msg, withType: .Message, withData: datas)
}
}
|
mit
|
134a7d77200718eb52e5dd337dafe500
| 36 | 106 | 0.651257 | 4.426023 | false | false | false | false |
glimpseio/ChannelZ
|
Sources/ChannelZ/Receivers.swift
|
1
|
9609
|
//
// Receptors.swift
// ChannelZ
//
// Created by Marc Prud'hommeaux <[email protected]>
// License: MIT (or whatever)
//
import Dispatch
import Foundation
// Atomic increment/decrement is deprecated and there is currently no replacement for Swift
//public typealias Counter = Int64
//
//@discardableResult
//func channelZIncrement64(_ value: UnsafeMutablePointer<Counter>) -> Int64 {
// return OSAtomicIncrement64(value)
//}
//
//@discardableResult
//func channelZDecrement64(_ value: UnsafeMutablePointer<Counter>) -> Int64 {
// return OSAtomicDecrement64(value)
//}
//
//public final class Counter : ExpressibleByIntegerLiteral {
// private var value: Int64 = 0
//
// public init(integerLiteral: Int) {
// self.value = Int64(integerLiteral)
// }
//
// public func set(_ v: Int64) {
// value = v
// }
//
// public func current() -> Int64 {
// return value
// }
//
// @discardableResult
// public func increment() -> Int64 {
// return OSAtomicIncrement64(&value)
// }
//
// @discardableResult
// public func decrement() -> Int64 {
// return OSAtomicDecrement64(&value)
// }
//}
public final class Counter : ExpressibleByIntegerLiteral {
private var value: Int64 = 0
private let queue = DispatchQueue(label: "ChannelZCounter")
public init(integerLiteral: Int) {
self.value = Int64(integerLiteral)
}
public func set(_ v: Int64) {
queue.sync {
value = v
}
}
private func change(_ offset: Int64) -> Int64 {
var v: Int64 = 0
queue.sync {
value += offset
v = value
}
return v
}
public func get() -> Int64 {
return change(0)
}
@discardableResult
public func increment() -> Int64 {
return change(+1)
}
@discardableResult
public func decrement() -> Int64 {
return change(-1)
}
}
/// An `Receipt` is the result of `receive`ing to a Observable or Channel
public protocol Receipt {
/// Whether the receipt is cancelled or not
var isCancelled: Bool { get }
/// Disconnects this receptor from the source
func cancel()
func makeIterator() -> CollectionOfOne<Receipt>.Iterator
}
public extension Receipt {
/// Creates an iterator of receipts
func makeIterator() -> CollectionOfOne<Receipt>.Iterator {
return CollectionOfOne(self).makeIterator()
}
}
// A receipt implementation
open class ReceiptOf: Receipt {
open var isCancelled: Bool { return cancelCounter.get() > 0 }
fileprivate let cancelCounter: Counter = 0
let canceler: () -> ()
public init(canceler: @escaping () -> () = { }) {
self.canceler = canceler
}
/// Disconnects this receipt from the source observable
open func cancel() {
// only cancel the first time
if cancelCounter.increment() == 1 {
canceler()
}
}
}
// A thread-safe multi-receipt implementation
open class MultiReceipt: Receipt {
private let queue = DispatchQueue(label: "ReceiptOfQueue", attributes: .concurrent)
private var receipts: [Receipt] = []
/// Creates a Receipt backed by one or more other Receipts
public init(receipts: [Receipt]) {
addReceipts(receipts)
}
/// Creates a Receipt backed by another Receipt
public convenience init(receipt: Receipt) {
self.init(receipts: [receipt])
}
/// Creates an empty cancelled Receipt
public convenience init() {
self.init(receipts: [])
}
public func addReceipts(_ receipts: [Receipt]) {
queue.async(flags: .barrier) { self.receipts.append(contentsOf: receipts) }
}
/// Disconnects this receipt from the source observable
open func cancel() {
queue.sync {
for receipt in self.receipts {
receipt.cancel()
}
}
}
public var isCancelled: Bool {
var cancelled: Bool = true
queue.sync {
cancelled = self.receipts.filter({ $0.isCancelled == false }).isEmpty
}
return cancelled
}
}
/// How many levels of re-entrancy are permitted when flowing state observations
public var ChannelZReentrancyLimit: Int = 1
/// Global number of times a reentrant invocation was made
public let ChannelZReentrantReceptions: Counter = 0
/// A ReceiverQueue manages a list of receivers and handles dispatching pulses to all the receivers
public final class ReceiverQueue<T> : ReceiverType {
public typealias Receptor = (T) -> ()
public let maxdepth: Int
var receivers: ContiguousArray<(index: Int64, receptor: Receptor)> = []
let entrancy: Counter = 0
let receptorIndex: Counter = 0
public var count: Int { return receivers.count }
// os_unfair_lock would probably be faster (albeit unfair), but it seems to crash on forked processes (like when XCode unit tests in parallel; https://forums.developer.apple.com/thread/60622)
// let lock = UnfairLock()
let lock = ReentrantLock()
public init(maxdepth: Int? = nil) {
self.maxdepth = maxdepth ?? ChannelZReentrancyLimit
}
public func receive(_ element: T) {
lock.lock()
defer { lock.unlock() }
let currentEntrancy = entrancy.increment()
defer { entrancy.decrement() }
if currentEntrancy > Int64(maxdepth + 1) {
reentrantChannelReception(element)
} else {
for (_, receiver) in receivers {
receiver(element)
}
}
}
public func reentrantChannelReception(_ element: Any) {
#if DEBUG_CHANNELZ
//print("ChannelZ reentrant channel short-circuit; break on \(#function) to debug", type(of: element))
ChannelZReentrantReceptions.increment()
#endif
}
/// Adds a receiver that will return a receipt that simply removes itself from the list
public func addReceipt(_ receptor: @escaping Receptor) -> Receipt {
let token = addReceiver(receptor)
return ReceiptOf(canceler: { self.removeReceptor(token) })
}
/// Adds a custom receiver block and returns a token that can later be used to remove the receiver
public func addReceiver(_ receptor: @escaping Receptor) -> Int64 {
precondition(entrancy.get() == 0, "cannot add to receivers while they are flowing")
let index = receptorIndex.increment()
receivers.append((index, receptor))
return index
}
public func removeReceptor(_ index: Int64) {
receivers = receivers.filter { $0.index != index }
}
/// Clear all the receivers
public func clear() {
receivers = []
}
}
open class ReceiverQueueSource<T> {
let receivers = ReceiverQueue<T>()
}
/// A Lock used for synchronizing access to the receiver queue
protocol Lock {
init()
func lock()
func unlock()
func withLock<T>(_ f: () throws -> T) rethrows -> T
var isReentrant: Bool { get }
}
/// A no-op `Lock` implementation
final class NoLock : Lock {
init() {
}
func lock() {
}
func unlock() {
}
func withLock<T>(_ f: () throws -> T) rethrows -> T {
return try f()
}
var isReentrant: Bool { return true }
}
/// A `Lock` implementation that uses a `pthread_mutex_t`
final class ReentrantLock : Lock {
var mutex = pthread_mutex_t()
var mutexAttr = pthread_mutexattr_t()
#if os(Linux)
typealias PTHREAD_ATTR_TYPE = Int
#else
typealias PTHREAD_ATTR_TYPE = Int32
#endif
convenience init() {
self.init(attr: PTHREAD_MUTEX_RECURSIVE)
}
var isReentrant: Bool {
var attr: Int32 = 0
assertSuccess(pthread_mutexattr_gettype(&mutexAttr, &attr))
return attr == PTHREAD_MUTEX_RECURSIVE
}
init(attr: PTHREAD_ATTR_TYPE = PTHREAD_MUTEX_RECURSIVE) {
assertSuccess(pthread_mutexattr_init(&mutexAttr))
assertSuccess(pthread_mutexattr_settype(&mutexAttr, Int32(attr)))
assertSuccess(pthread_mutex_init(&mutex, &mutexAttr))
}
deinit {
assertSuccess(pthread_mutex_destroy(&mutex))
assertSuccess(pthread_mutexattr_destroy(&mutexAttr))
}
func lock() {
assertSuccess(pthread_mutex_lock(&self.mutex))
}
func unlock() {
assertSuccess(pthread_mutex_unlock(&self.mutex))
}
func withLock<T>(_ f: () throws -> T) rethrows -> T {
assertSuccess(pthread_mutex_lock(&self.mutex))
defer { assertSuccess(pthread_mutex_unlock(&self.mutex)) }
return try f()
}
func assertSuccess(_ f: @autoclosure () -> Int32) {
let success = f()
assert(success == 0, "critical error – pthread call failed \(success)")
}
}
#if !(os(Linux))
/// A `Lock` implementation that uses an `os_unfair_lock`
@available(macOS 10.12, iOS 10.0, *)
final class UnfairLock : Lock {
var unfairLock = os_unfair_lock_s()
init() {
}
var isReentrant: Bool {
return false
}
func lock() {
os_unfair_lock_lock(&unfairLock)
}
func unlock() {
os_unfair_lock_unlock(&unfairLock)
}
func withLock<T>(_ f: () throws -> T) rethrows -> T {
os_unfair_lock_lock(&unfairLock)
defer { os_unfair_lock_unlock(&unfairLock) }
return try f()
}
func tryLock<T>(_ f: () throws -> T) rethrows -> T? {
if !os_unfair_lock_trylock(&unfairLock) { return nil }
defer { os_unfair_lock_unlock(&unfairLock) }
return try f()
}
}
#endif
|
mit
|
0b128738229b8da2963a5304b3860b26
| 25.465565 | 195 | 0.619652 | 4.031473 | false | false | false | false |
wireapp/wire-ios
|
Wire-iOS/Sources/UserInterface/Helpers/UIViewController+Navigation.swift
|
1
|
1145
|
//
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
extension UIViewController {
func hideDefaultButtonTitle() {
guard navigationItem.backBarButtonItem == nil else { return }
hideBackButtonTitle()
}
func hideBackButtonTitle() {
let item = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
item.accessibilityLabel = L10n.Localizable.General.back
navigationItem.backBarButtonItem = item
}
}
|
gpl-3.0
|
49bf60650faee6d54293e789683f8df5
| 30.805556 | 86 | 0.719651 | 4.507874 | false | false | false | false |
phakphumi/Chula-Expo-iOS-Application
|
Chula Expo 2017/Chula Expo 2017/CoreData/PlaceData+CoreDataClass.swift
|
1
|
6077
|
//
// PlaceData+CoreDataClass.swift
// Chula Expo 2017
//
// Created by Pakpoom on 2/10/2560 BE.
// Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved.
// This file was automatically generated and should not be edited.
//
import Foundation
import CoreData
@objc(PlaceData)
public class PlaceData: NSManagedObject {
class func addData(
id: String,
code: String,
nameTh: String,
nameEn: String,
longitude: Double,
latitude: Double,
zoneID: String,
inManageobjectcontext context: NSManagedObjectContext,
completion: ((PlaceData?) -> Void)?
)
{
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "PlaceData")
request.predicate = NSPredicate(format: "id = %@", id)
if let placeData = (try? context.fetch(request))?.first as? PlaceData {
// found this event in the database, return it ...
// print("Found place \(result.nameEn)")
placeData.id = id
placeData.code = code
placeData.nameTh = nameTh
placeData.nameEn = nameEn
placeData.longitude = longitude
placeData.latitude = latitude
let zoneRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ZoneData")
zoneRequest.predicate = NSPredicate(format: "id = %@", zoneID)
if let result = (try? context.fetch(zoneRequest))?.first as? ZoneData {
// found this event in the database, return it ...
placeData.toZone = result
}
completion?(placeData)
} else {
if let placeData = NSEntityDescription.insertNewObject(forEntityName: "PlaceData", into: context) as? PlaceData {
// created a new event in the database
placeData.id = id
placeData.code = code
placeData.nameTh = nameTh
placeData.nameEn = nameEn
placeData.longitude = longitude
placeData.latitude = latitude
let zoneRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ZoneData")
zoneRequest.predicate = NSPredicate(format: "id = %@", zoneID)
if let result = (try? context.fetch(zoneRequest))?.first as? ZoneData {
// found this event in the database, return it ...
placeData.toZone = result
}
completion?(placeData)
} else {
completion?(nil)
}
}
}
class func fetchPlace(InZone id : String, inManageobjectcontext context: NSManagedObjectContext) -> [[String: String]]?{
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "ZoneData")
request.predicate = NSPredicate(format: "id = %@", id)
do {
let zoneResults = try context.fetch(request).first as? ZoneData
let places = zoneResults?.toPlaces?.allObjects as! [PlaceData]
var locations = [[String: String]]()
for place in places {
locations.append(["latitude": String(place.latitude),
"longitude": String(place.longitude),
"id": place.id!,
"nameTh": place.nameTh!,
"nameEn": place.nameEn!,
// "nameTh": place.nameTh!,
"code": place.code!])
}
return locations
} catch {
print("Couldn't fetch results")
}
return nil
}
class func fetchFacility(InPlace id : String, inManageobjectcontext context: NSManagedObjectContext) -> [[String: String]]?{
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "PlaceData")
request.predicate = NSPredicate(format: "id = %@", id)
do {
let placeResults = try context.fetch(request).first as? PlaceData
let facilities = placeResults?.toFacility?.allObjects as! [FacilityData]
var locations = [[String: String]]()
for facility in facilities {
locations.append(["latitude": String(facility.latitude),
"longitude": String(facility.longitude),
"id": facility.id!,
"type": facility.type!,
"nameTh": facility.nameTh!,
"nameEn": facility.nameEn!,
"descTh": facility.descTh!,
"descEn": facility.descEn!])
}
return locations
} catch {
print("Couldn't fetch results")
}
return nil
}
class func getPlaceName(fromPlaceId id: String, inManageobjectcontext context: NSManagedObjectContext) -> String {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "PlaceData")
request.predicate = NSPredicate(format: "id = %@", id)
if let result = (try? context.fetch(request))?.first as? PlaceData {
// found this event in the database, return it ...
return result.nameTh!
}
return ""
}
}
|
mit
|
b3a778fa77f65a074dce4966fd7b5aff
| 33.134831 | 128 | 0.484858 | 5.847931 | false | false | false | false |
gspd-mobi/rage-ios
|
Sources/RxRage/RageRxSwift+Codable.swift
|
1
|
1547
|
import Foundation
import Rage
import RxSwift
extension RageRequest {
public func executeObjectObservable<T: Codable>(decoder: JSONDecoder = JSONDecoder()) -> Observable<T> {
return taskObservable()
.flatMap { result -> Observable<T> in
switch result {
case .success(let response):
let parsedObject: T? = response.data?.parseJson(decoder: decoder)
if let resultObject = parsedObject {
return Observable.just(resultObject)
} else {
return Observable.error(RageError(type: .configuration))
}
case .failure(let error):
return Observable.error(error)
}
}
}
public func executeArrayObservable<T: Codable>(decoder: JSONDecoder = JSONDecoder()) -> Observable<[T]> {
return taskObservable()
.flatMap { result -> Observable<[T]> in
switch result {
case .success(let response):
let parsedObject: [T]? = response.data?.parseJsonArray(decoder: decoder)
if let resultObject = parsedObject {
return Observable.just(resultObject)
} else {
return Observable.error(RageError(type: .configuration))
}
case .failure(let error):
return Observable.error(error)
}
}
}
}
|
mit
|
693c0728a27792e46896c4a877a0d764
| 36.731707 | 109 | 0.517776 | 5.72963 | false | false | false | false |
rymcol/Linux-Server-Side-Swift-Benchmarking
|
PerfectJSON/Sources/routing.swift
|
1
|
905
|
//
// routing.swift
// PerfectPress
//
// Created by Ryan Collins on 6/9/16.
// Copyright (C) 2016 Ryan M. Collins.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the PerfectPress open source blog project
//
//===----------------------------------------------------------------------===//
//
import PerfectLib
import PerfectHTTP
func makeRoutes() -> Routes {
var routes = Routes()
routes.add(method: .get, uris: ["json"], handler: JSONHandler)
return routes
}
func JSONHandler(request: HTTPRequest, _ response: HTTPResponse) {
let JSONData = JSONCreator().generateJSON()
do {
response.setHeader(.contentType, value: "application/json; charset=utf-8")
try response.setBody(json: JSONData)
} catch {
response.appendBody(string: "JSON Failed")
}
response.completed()
}
|
apache-2.0
|
b86630143d284ef9fd2cbf53da7b78eb
| 22.815789 | 82 | 0.543646 | 4.502488 | false | false | false | false |
gcba/usig-normalizador-ios
|
USIGNormalizador/USIGNormalizadorAddress.swift
|
1
|
2937
|
//
// USIGNormalizadorAddress.swift
// USIGNormalizador
//
// Created by Rita Zerrizuela on 9/28/17.
// Copyright © 2017 GCBA. All rights reserved.
//
import Foundation
import Moya
public struct USIGNormalizadorAddress {
public let address: String
public let street: String
public let number: Int?
public let type: String
public let corner: String?
public let latitude: Double?
public let longitude: Double?
public let districtCode: String?
public let districtName: String?
public let localityName: String?
public let label: String?
internal let source: TargetType.Type
init(from json: [String: Any]) {
let coordinates = json["coordenadas"] as? [String: Any]
self.address = (json["direccion"] as! String).removeWhitespace().uppercased()
self.street = (json["nombre_calle"] as! String).removeWhitespace().uppercased()
self.number = json["altura"] as? Int
self.type = (json["tipo"] as! String).removeWhitespace()
self.corner = (json["nombre_calle_cruce"] as? String)?.removeWhitespace()
self.districtCode = (json["cod_partido"] as? String)?.removeWhitespace()
self.districtName = (json["nombre_partido"] as? String)?.removeWhitespace()
self.localityName = (json["nombre_localidad"] as? String)?.removeWhitespace()
self.label = json["label"] as? String
self.source = json["source"] as? TargetType.Type ?? USIGNormalizadorAPI.self
self.latitude = USIGNormalizadorAddress.parseCoordinate(fromDict: coordinates, key: "y")
self.longitude = USIGNormalizadorAddress.parseCoordinate(fromDict: coordinates, key: "x")
}
static private func parseCoordinate(fromDict dict: [String: Any]?, key: String) -> Double? {
guard let coordinatesDict = dict else { return nil }
if let coordinateString = coordinatesDict[key] as? String {
return Double(coordinateString)
}
return coordinatesDict[key] as? Double
}
}
extension USIGNormalizadorAddress: Equatable {
public static func ==(lhs: USIGNormalizadorAddress, rhs: USIGNormalizadorAddress) -> Bool {
return lhs.address == rhs.address && lhs.type == rhs.type
}
}
extension USIGNormalizadorAddress: CustomStringConvertible {
public var description: String {
return "Address: \(address), " +
"Street: \(street), " +
"Number: \(String(describing: number)), " +
"Type: \(type), " +
"Corner: \(String(describing: corner)), " +
"Latitude: \(String(describing: latitude)), " +
"Longitude: \(String(describing: longitude))," +
"District Code: \(String(describing: districtCode))," +
"District Name: \(String(describing: districtName))," +
"Locality Name: \(String(describing: localityName))," +
"Label: \(String(describing: label))"
}
}
|
mit
|
bb7f2f5bc04538036d4c3d30f1e4ae31
| 38.146667 | 97 | 0.648842 | 4.066482 | false | false | false | false |
nodes-vapor/admin-panel-provider
|
Sources/AdminPanelProvider/Helpers/String.swift
|
1
|
3596
|
import Vapor
import Foundation
extension String {
public static func random(_ length: Int = 64) -> String {
var buffer = Array<UInt8>()
buffer.reserveCapacity(length)
for _ in 0..<length {
var value = Int.random(min: 0, max: 61)
if value < 10 { // 0-10
value = value &+ 0x30
} else if value < 36 { // A-Z
value = value &+ 0x37
} else { // a-z
value = value &+ 0x3D
}
buffer.append(UInt8(truncatingBitPattern: value))
}
return String(bytes: buffer)
}
public var isLocalhost: Bool {
return self == "0.0.0.0" || self == "127.0.0.1"
}
}
extension Date {
public func timeUntilNow(fallbackAfter: Int? = nil, fallbackFormat: String? = nil) -> String {
let calendar = Calendar.current
let components = calendar.dateComponents(
[.year, .weekOfYear, .month, .day, .hour, .minute, .second],
from: self, to: Date()
)
if let fallback = fallbackAfter {
let formatString: () -> String = {
let formatter = DateFormatter()
let fallbackFormat = fallbackFormat ?? "mm/dd/yyyy"
formatter.dateFormat = fallbackFormat
return formatter.string(from: self)
}
// NOTE: this code is very deliberate. Please be alert while making
// any modifications.
let years = fallback / 365
let months = fallback / 30
let weeks = fallback / 7
if years > 0 {
if components.year ?? 0 >= years {
return formatString()
}
} else if months > 0 {
if components.month ?? 0 >= months {
return formatString()
}
} else if weeks > 0 {
if components.weekOfYear ?? 0 >= weeks {
return formatString()
}
} else {
if components.day ?? 0 > fallback {
return formatString()
}
}
}
if let year = components.year {
if year >= 2 {
return "\(year) years ago"
} else if year >= 1 {
return "a year ago"
}
}
if let month = components.month {
if month >= 2 {
return "\(month) months ago"
} else if month >= 1 {
return "a month ago"
}
}
if let week = components.weekOfYear {
if week >= 2 {
return "\(week) weeks ago"
} else if week >= 1 {
return "a week ago"
}
}
if let day = components.day {
if day >= 2 {
return "\(day) days ago"
} else if day >= 1 {
return "a day ago"
}
}
if let hour = components.hour {
if hour >= 2 {
return "\(hour) hours ago"
} else if hour >= 1 {
return "an hour ago"
}
}
if let minute = components.minute {
if minute >= 2 {
return "\(minute) minutes ago"
} else if minute >= 1 {
return "a minute ago"
}
}
if let second = components.second, second >= 5 {
return "\(second) seconds ago"
}
return "just now"
}
}
|
mit
|
3fc9d90d4d70e703a25f700d83eefb8d
| 27.768 | 98 | 0.439377 | 4.852901 | false | false | false | false |
remind101/AutoGraph
|
AutoGraphTests/Requests/FilmSubscriptionRequest.swift
|
1
|
12011
|
@testable import AutoGraphQL
import Foundation
import JSONValueRX
class FilmSubscriptionRequest: Request {
/*
query film {
film(id: "ZmlsbXM6MQ==") {
id
title
episodeID
director
openingCrawl
}
}
*/
let operationName: String
let queryDocument = Operation(type: .subscription,
name: "film",
selectionSet: [
Object(name: "film",
alias: nil,
arguments: ["id" : "ZmlsbXM6MQ=="],
selectionSet: [
"id",
Scalar(name: "title", alias: nil),
Scalar(name: "episodeID", alias: nil),
Scalar(name: "director", alias: nil),
Scalar(name: "openingCrawl", alias: nil)])
])
let variables: [AnyHashable : Any]? = nil
let rootKeyPath: String = "data.film"
init(operationName: String = "film") {
self.operationName = operationName
}
public func willSend() throws { }
public func didFinishRequest(response: HTTPURLResponse?, json: JSONValue) throws { }
public func didFinish(result: AutoGraphResult<Film>) throws { }
static let jsonResponse: [String: Any] = [
"type": "data",
"id": "film",
"payload": [
"data": [
"id": "ZmlsbXM6MQ==",
"title": "A New Hope",
"episodeID": 4,
"director": "George Lucas",
"openingCrawl": "It is a period of civil war.\r\nRebel spaceships, striking\r\nfrom a hidden base, have won\r\ntheir first victory against\r\nthe evil Galactic Empire.\r\n\r\nDuring the battle, Rebel\r\nspies managed to steal secret\r\nplans to the Empire's\r\nultimate weapon, the DEATH\r\nSTAR, an armored space\r\nstation with enough power\r\nto destroy an entire planet.\r\n\r\nPursued by the Empire's\r\nsinister agents, Princess\r\nLeia races home aboard her\r\nstarship, custodian of the\r\nstolen plans that can save her\r\npeople and restore\r\nfreedom to the galaxy...."
]
]
]
}
class FilmSubscriptionRequestWithVariables: Request {
/*
query film {
film(id: "ZmlsbXM6MQ==") {
id
title
episodeID
director
openingCrawl
}
}
*/
let queryDocument = Operation(type: .subscription,
name: "film",
selectionSet: [
Object(name: "film",
alias: nil,
arguments: ["id" : "ZmlsbXM6MQ=="],
selectionSet: [
"id",
Scalar(name: "title", alias: nil),
Scalar(name: "episodeID", alias: nil),
Scalar(name: "director", alias: nil),
Scalar(name: "openingCrawl", alias: nil)])
])
let variables: [AnyHashable : Any]? = [
"id": "ZmlsbXM6MQ=="
]
let rootKeyPath: String = "data.film"
public func willSend() throws { }
public func didFinishRequest(response: HTTPURLResponse?, json: JSONValue) throws { }
public func didFinish(result: AutoGraphResult<Film>) throws { }
static let jsonResponse: [String: Any] = [
"type": "data",
"id": "film",
"payload": [
"data": [
"id": "ZmlsbXM6MQ==",
"title": "A New Hope",
"episodeID": 4,
"director": "George Lucas",
"openingCrawl": "It is a period of civil war.\r\nRebel spaceships, striking\r\nfrom a hidden base, have won\r\ntheir first victory against\r\nthe evil Galactic Empire.\r\n\r\nDuring the battle, Rebel\r\nspies managed to steal secret\r\nplans to the Empire's\r\nultimate weapon, the DEATH\r\nSTAR, an armored space\r\nstation with enough power\r\nto destroy an entire planet.\r\n\r\nPursued by the Empire's\r\nsinister agents, Princess\r\nLeia races home aboard her\r\nstarship, custodian of the\r\nstolen plans that can save her\r\npeople and restore\r\nfreedom to the galaxy...."
]
]
]
}
class AllFilmsSubscriptionRequest: Request {
/*
query allFilms {
film(id: "ZmlsbXM6MQ==") {
id
title
episodeID
director
openingCrawl
}
}
*/
let queryDocument = Operation(type: .subscription,
name: "allFilms",
selectionSet: [
Object(name: "allFilms",
arguments: nil,
selectionSet: [
Object(name: "films",
alias: nil,
arguments: nil,
selectionSet: [
"id",
Scalar(name: "title", alias: nil),
Scalar(name: "episodeID", alias: nil),
Scalar(name: "director", alias: nil),
Scalar(name: "openingCrawl", alias: nil)])
])
])
let variables: [AnyHashable : Any]? = nil
// TODO: this isn't even used on subscriptions. consider moving this into an extensive protocol and out of Request.
let rootKeyPath: String = "data.allFilms"
struct Data: Decodable {
struct AllFilms: Decodable {
let films: [Film]
}
let allFilms: AllFilms
}
public func willSend() throws { }
public func didFinishRequest(response: HTTPURLResponse?, json: JSONValue) throws { }
public func didFinish(result: AutoGraphResult<Data>) throws { }
static let jsonResponse: [String : Any] = [
"type": "data",
"id": "allFilms",
"payload": [
"data": [
"allFilms": [
"films": [
[
"id": "ZmlsbXM6MQ==",
"title": "A New Hope",
"episodeID": 4,
"openingCrawl": "It is a period of civil war.\r\nRebel spaceships, striking\r\nfrom a hidden base, have won\r\ntheir first victory against\r\nthe evil Galactic Empire.\r\n\r\nDuring the battle, Rebel\r\nspies managed to steal secret\r\nplans to the Empire's\r\nultimate weapon, the DEATH\r\nSTAR, an armored space\r\nstation with enough power\r\nto destroy an entire planet.\r\n\r\nPursued by the Empire's\r\nsinister agents, Princess\r\nLeia races home aboard her\r\nstarship, custodian of the\r\nstolen plans that can save her\r\npeople and restore\r\nfreedom to the galaxy....",
"director": "George Lucas"
],
[
"id": "ZmlsbXM6Mg==",
"title": "The Empire Strikes Back",
"episodeID": 5,
"openingCrawl": "It is a dark time for the\r\nRebellion. Although the Death\r\nStar has been destroyed,\r\nImperial troops have driven the\r\nRebel forces from their hidden\r\nbase and pursued them across\r\nthe galaxy.\r\n\r\nEvading the dreaded Imperial\r\nStarfleet, a group of freedom\r\nfighters led by Luke Skywalker\r\nhas established a new secret\r\nbase on the remote ice world\r\nof Hoth.\r\n\r\nThe evil lord Darth Vader,\r\nobsessed with finding young\r\nSkywalker, has dispatched\r\nthousands of remote probes into\r\nthe far reaches of space....",
"director": "Irvin Kershner"
],
[
"id": "ZmlsbXM6Mw==",
"title": "Return of the Jedi",
"episodeID": 6,
"openingCrawl": "Luke Skywalker has returned to\r\nhis home planet of Tatooine in\r\nan attempt to rescue his\r\nfriend Han Solo from the\r\nclutches of the vile gangster\r\nJabba the Hutt.\r\n\r\nLittle does Luke know that the\r\nGALACTIC EMPIRE has secretly\r\nbegun construction on a new\r\narmored space station even\r\nmore powerful than the first\r\ndreaded Death Star.\r\n\r\nWhen completed, this ultimate\r\nweapon will spell certain doom\r\nfor the small band of rebels\r\nstruggling to restore freedom\r\nto the galaxy...",
"director": "Richard Marquand"
],
[
"id": "ZmlsbXM6NA==",
"title": "The Phantom Menace",
"episodeID": 1,
"openingCrawl": "Turmoil has engulfed the\r\nGalactic Republic. The taxation\r\nof trade routes to outlying star\r\nsystems is in dispute.\r\n\r\nHoping to resolve the matter\r\nwith a blockade of deadly\r\nbattleships, the greedy Trade\r\nFederation has stopped all\r\nshipping to the small planet\r\nof Naboo.\r\n\r\nWhile the Congress of the\r\nRepublic endlessly debates\r\nthis alarming chain of events,\r\nthe Supreme Chancellor has\r\nsecretly dispatched two Jedi\r\nKnights, the guardians of\r\npeace and justice in the\r\ngalaxy, to settle the conflict....",
"director": "George Lucas"
],
[
"id": "ZmlsbXM6NQ==",
"title": "Attack of the Clones",
"episodeID": 2,
"openingCrawl": "There is unrest in the Galactic\r\nSenate. Several thousand solar\r\nsystems have declared their\r\nintentions to leave the Republic.\r\n\r\nThis separatist movement,\r\nunder the leadership of the\r\nmysterious Count Dooku, has\r\nmade it difficult for the limited\r\nnumber of Jedi Knights to maintain \r\npeace and order in the galaxy.\r\n\r\nSenator Amidala, the former\r\nQueen of Naboo, is returning\r\nto the Galactic Senate to vote\r\non the critical issue of creating\r\nan ARMY OF THE REPUBLIC\r\nto assist the overwhelmed\r\nJedi....",
"director": "George Lucas"
],
[
"id": "ZmlsbXM6Ng==",
"title": "Revenge of the Sith",
"episodeID": 3,
"openingCrawl": "War! The Republic is crumbling\r\nunder attacks by the ruthless\r\nSith Lord, Count Dooku.\r\nThere are heroes on both sides.\r\nEvil is everywhere.\r\n\r\nIn a stunning move, the\r\nfiendish droid leader, General\r\nGrievous, has swept into the\r\nRepublic capital and kidnapped\r\nChancellor Palpatine, leader of\r\nthe Galactic Senate.\r\n\r\nAs the Separatist Droid Army\r\nattempts to flee the besieged\r\ncapital with their valuable\r\nhostage, two Jedi Knights lead a\r\ndesperate mission to rescue the\r\ncaptive Chancellor....",
"director": "George Lucas"
]
]
]
]
]
]
}
|
mit
|
e05855276a889813b95dfed3c6e41a1f
| 55.126168 | 611 | 0.512447 | 4.137444 | false | false | false | false |
natecook1000/swift
|
test/SILOptimizer/outliner.swift
|
2
|
9590
|
// RUN: %target-swift-frontend -Osize -import-objc-header %S/Inputs/Outliner.h %s -emit-sil | %FileCheck %s
// RUN: %target-swift-frontend -Osize -g -import-objc-header %S/Inputs/Outliner.h %s -emit-sil | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
public class MyGizmo {
private var gizmo : Gizmo
private var optionalGizmo : Gizmo?
init() {
gizmo = Gizmo()
}
// CHECK-LABEL: sil @$S8outliner7MyGizmoC11usePropertyyyF
// CHECK: [[A_FUN:%.*]] = function_ref @$SSo5GizmoC14stringPropertySSSgvgToTeab_
// CHECK: apply [[A_FUN]]({{.*}}) : $@convention(thin) (@in_guaranteed Gizmo) -> @owned Optional<String>
// CHECK-NOT: return
// CHECK: [[P_FUN:%.*]] = function_ref @$SSo5GizmoC14stringPropertySSSgvgToTepb_
// CHECK: apply [[P_FUN]]({{.*}}) : $@convention(thin) (Gizmo) -> @owned Optional<String>
// CHECK: return
public func useProperty() {
print(gizmo.stringProperty)
print(optionalGizmo!.stringProperty)
}
}
// CHECK-LABEL: sil @$S8outliner13testOutliningyyF
// CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC14stringPropertySSSgvgToTepb_
// CHECK: apply [[FUN]](%{{.*}}) : $@convention(thin) (Gizmo) -> @owned Optional<String>
// CHECK: apply [[FUN]](%{{.*}}) : $@convention(thin) (Gizmo) -> @owned Optional<String>
// CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC14stringPropertySSSgvsToTembnn_
// CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Gizmo) -> ()
// CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Gizmo) -> ()
// CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC12modifyString_10withNumber0D6FoobarSSSgAF_SiypSgtFToTembnnnb_
// CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String>
// CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String>
// CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC11doSomethingyypSgSaySSGSgFToTembnn_
// CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject>
// CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject>
// CHECK: return
public func testOutlining() {
let gizmo = Gizmo()
let foobar = Gizmo()
print(gizmo.stringProperty)
print(gizmo.stringProperty)
gizmo.stringProperty = "foobar"
gizmo.stringProperty = "foobar2"
gizmo.modifyString("hello", withNumber:1, withFoobar: foobar)
gizmo.modifyString("hello", withNumber:1, withFoobar: foobar)
let arr = [ "foo", "bar"]
gizmo.doSomething(arr)
gizmo.doSomething(arr)
}
// CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC14stringPropertySSSgvgToTeab_ : $@convention(thin) (@in_guaranteed Gizmo) -> @owned Optional<String>
// CHECK: bb0(%0 : $*Gizmo):
// CHECK: %1 = load %0 : $*Gizmo
// CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.stringProperty!getter.1.foreign : (Gizmo) -> () -> String?
// CHECK: %3 = apply %2(%1) : $@convention(objc_method) (Gizmo) -> @autoreleased Optional<NSString>
// CHECK: switch_enum %3 : $Optional<NSString>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2
// CHECK: bb1(%5 : $NSString):
// CHECK: %6 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String
// CHECK: %7 = metatype $@thin String.Type
// CHECK: %8 = apply %6(%3, %7) : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String
// CHECK: release_value %3 : $Optional<NSString>
// CHECK: %10 = enum $Optional<String>, #Optional.some!enumelt.1, %8 : $String
// CHECK: br bb3(%10 : $Optional<String>)
// CHECK: bb2:
// CHECK: %12 = enum $Optional<String>, #Optional.none!enumelt
// CHECK: br bb3(%12 : $Optional<String>)
// CHECK: bb3(%14 : $Optional<String>):
// CHECK: return %14 : $Optional<String>
// CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC14stringPropertySSSgvgToTepb_ : $@convention(thin) (Gizmo) -> @owned Optional<String>
// CHECK: bb0(%0 : $Gizmo):
// CHECK: %1 = objc_method %0 : $Gizmo, #Gizmo.stringProperty!getter.1.foreign : (Gizmo) -> () -> String?
// CHECK: %2 = apply %1(%0) : $@convention(objc_method) (Gizmo) -> @autoreleased Optional<NSString>
// CHECK: switch_enum %2 : $Optional<NSString>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2
// CHECK:bb1(%4 : $NSString):
// CHECK: %5 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String
// CHECK: %6 = metatype $@thin String.Type
// CHECK: %7 = apply %5(%2, %6) : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String
// CHECK: release_value %2 : $Optional<NSString>
// CHECK: %9 = enum $Optional<String>, #Optional.some!enumelt.1, %7 : $String
// CHECK: br bb3(%9 : $Optional<String>)
// CHECK:bb2:
// CHECK: %11 = enum $Optional<String>, #Optional.none!enumelt
// CHECK: br bb3(%11 : $Optional<String>)
// CHECK:bb3(%13 : $Optional<String>):
// CHECK: return %13 : $Optional<String>
// CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC14stringPropertySSSgvsToTembnn_ : $@convention(thin) (@owned String, Gizmo) -> () {
// CHECK: bb0(%0 : $String, %1 : $Gizmo):
// CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.stringProperty!setter.1.foreign : (Gizmo) -> (String?) -> ()
// CHECK: %3 = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK: %4 = apply %3(%0) : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK: release_value %0 : $String
// CHECK: %6 = enum $Optional<NSString>, #Optional.some!enumelt.1, %4 : $NSString
// CHECK: %7 = apply %2(%6, %1) : $@convention(objc_method) (Optional<NSString>, Gizmo) -> ()
// CHECK: strong_release %4 : $NSString
// CHECK: return %7 : $()
// CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC12modifyString_10withNumber0D6FoobarSSSgAF_SiypSgtFToTembnnnb_ : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String> {
// CHECK: bb0(%0 : $String, %1 : $Int, %2 : $Optional<AnyObject>, %3 : $Gizmo):
// CHECK: %4 = objc_method %3 : $Gizmo, #Gizmo.modifyString!1.foreign : (Gizmo) -> (String?, Int, Any?) -> String?
// CHECK: %5 = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK: %6 = apply %5(%0) : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK: release_value %0 : $String
// CHECK: %8 = enum $Optional<NSString>, #Optional.some!enumelt.1, %6 : $NSString
// CHECK: %9 = apply %4(%8, %1, %2, %3) : $@convention(objc_method) (Optional<NSString>, Int, Optional<AnyObject>, Gizmo) -> @autoreleased Optional<NSString>
// CHECK: strong_release %6 : $NSString
// CHECK: switch_enum %9 : $Optional<NSString>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1
//
// CHECK: bb1:
// CHECK: %12 = enum $Optional<String>, #Optional.none!enumelt
// CHECK: br bb3(%12 : $Optional<String>)
//
// CHECK: bb2(%14 : $NSString):
// CHECK: %15 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String
// CHECK: %16 = metatype $@thin String.Type
// CHECK: %17 = apply %15(%9, %16) : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String
// CHECK: release_value %9 : $Optional<NSString> // id: %18
// CHECK: %19 = enum $Optional<String>, #Optional.some!enumelt.1, %17 : $String
// CHECK: br bb3(%19 : $Optional<String>)
//
// CHECK: bb3(%21 : $Optional<String>):
// CHECK: return %21 : $Optional<String>
// CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC11doSomethingyypSgSaySSGSgFToTembnn_ : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject> {
// CHECK: bb0(%0 : $Array<String>, %1 : $Gizmo):
// CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.doSomething!1.foreign : (Gizmo) -> ([String]?) -> Any?
// CHECK: %3 = function_ref @$SSa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF : $@convention(method) <{{.*}}> (@guaranteed Array<{{.*}}>) -> @owned NSArray
// CHECK: %4 = apply %3<String>(%0) : $@convention(method) <{{.*}}> (@guaranteed Array<{{.*}}>) -> @owned NSArray
// CHECK: release_value %0 : $Array<String>
// CHECK: %6 = enum $Optional<NSArray>, #Optional.some!enumelt.1, %4 : $NSArray
// CHECK: %7 = apply %2(%6, %1) : $@convention(objc_method) (Optional<NSArray>, Gizmo) -> @autoreleased Optional<AnyObject>
// CHECK: strong_release %4 : $NSArray
// CHECK: return %7 : $Optional<AnyObject>
public func dontCrash<T: Proto>(x : Gizmo2<T>) {
let s = x.doSomething()
print(s)
}
public func dontCrash2(_ c: SomeGenericClass) -> Bool {
guard let str = c.version else {
return false
}
guard let str2 = c.doSomething() else {
return false
}
let arr = [ "foo", "bar"]
c.doSomething2(arr)
return true
}
func dontCrash3() -> String? {
let bundle = Bundle.main
let resource = "common parameter"
return bundle.path(forResource: resource, ofType: "png")
?? bundle.path(forResource: resource, ofType: "apng")
}
extension Operation {
func dontCrash4() {
if completionBlock != nil {
completionBlock = { }
}
}
}
|
apache-2.0
|
0516b3c6621780bed892a4dcef6219c8
| 53.180791 | 211 | 0.66048 | 3.286498 | false | false | false | false |
robocopklaus/sportskanone
|
Sportskanone/Views/CoordinatorViewController.swift
|
1
|
3476
|
//
// CoordinatorViewController.swift
// Sportskanone
//
// Created by Fabian Pahl on 25/03/2017.
// Copyright © 2017 21st digital GmbH. All rights reserved.
//
import UIKit
import ReactiveCocoa
import ReactiveSwift
final class CoordinatorViewController<Store: StoreType>: UIViewController {
fileprivate let mainTabBarController = UITabBarController()
fileprivate let onboardingNavigationController = UINavigationController()
private let (lifetime, token) = Lifetime.make()
private let viewModel: CoordinatorViewModel<Store>
// MARK: - Object Life Cycle
init(viewModel: CoordinatorViewModel<Store>) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
onboardingNavigationController.setNavigationBarHidden(true, animated: false)
viewModel.currentScreen.producer
.take(during: lifetime)
.observe(on: UIScheduler())
.startWithValues { [weak self] screen in
self?.show(screen: screen)
}
}
}
fileprivate extension CoordinatorViewController {
// TODO: Refactor this ugly implementation
func show(screen: CoordinatorViewModel<Store>.Screen) {
var isOnboarding = false
switch screen {
case .signUp(let viewModel):
onboardingNavigationController.pushViewController(SignUpViewController(viewModel: viewModel), animated: true)
isOnboarding = true
case .healthAccess(let viewModel):
onboardingNavigationController.pushViewController(HealthAccessViewController(viewModel: viewModel), animated: true)
isOnboarding = true
case .healthDataSync(let viewModel):
onboardingNavigationController.pushViewController(HealthDataSyncViewController(viewModel: viewModel), animated: true)
isOnboarding = true
case .notificationPermission(let viewModel):
onboardingNavigationController.pushViewController(NotificationPermissionViewController(viewModel: viewModel), animated: true)
isOnboarding = true
case .ranking(let viewModel):
mainTabBarController.viewControllers = [UINavigationController(rootViewController: RankingViewController(viewModel: viewModel))]
}
if isOnboarding {
mainTabBarController.willMove(toParentViewController: nil)
mainTabBarController.view.removeFromSuperview()
mainTabBarController.removeFromParentViewController()
if !childViewControllers.contains(onboardingNavigationController) {
addChildViewController(onboardingNavigationController)
onboardingNavigationController.view.frame = view.bounds
view.addSubview(onboardingNavigationController.view)
onboardingNavigationController.didMove(toParentViewController: self)
}
} else {
onboardingNavigationController.willMove(toParentViewController: nil)
onboardingNavigationController.view.removeFromSuperview()
onboardingNavigationController.removeFromParentViewController()
if !childViewControllers.contains(mainTabBarController) {
addChildViewController(mainTabBarController)
mainTabBarController.view.frame = view.bounds
view.addSubview(mainTabBarController.view)
mainTabBarController.didMove(toParentViewController: self)
}
}
}
}
|
mit
|
efcc2bd04f3771a3f2036e70ca97e8f7
| 34.10101 | 134 | 0.74964 | 5.659609 | false | false | false | false |
Daij-Djan/DDCalendarView
|
Demos/EventKitDemo_swift/EventManager.swift
|
1
|
3687
|
//
// EventManager.swift
// Demos
//
// Created by Dominik Pich on 13/10/15.
// Copyright © 2015 Dominik Pich. All rights reserved.
//
import UIKit
import EventKit
public typealias EventManagerLoadCalendersCompletionHandler = ([EKCalendar]) -> Void
public typealias EventManagerCalenderCreatedCompletionHandler = (EKCalendar) -> Void
public typealias EventManagerLoadEventsCompletionHandler = ([EKEvent]) -> Void
public typealias EventManagerEventCreatedCompletionHandler = (EKEvent) -> Void
open class EventManager: NSObject {
let eventStore = EKEventStore()
//reading
open func getEventCalendars(_ handler:@escaping EventManagerLoadCalendersCompletionHandler) {
assertAuthorization() {
DispatchQueue.global().async {
let allCalendars = self.eventStore.calendars(for: .event)
DispatchQueue.main.async {
handler(allCalendars)
}
}
}
}
open func getEvents(_ daysModifier:Int,calendars:[EKCalendar]?, handler:@escaping EventManagerLoadEventsCompletionHandler) {
assertAuthorization() {
DispatchQueue.global().async {
let calendar = Calendar.current
let units = NSCalendar.Unit.day.union(NSCalendar.Unit.month).union(NSCalendar.Unit.year).union(NSCalendar.Unit.weekday).union(NSCalendar.Unit.weekOfMonth).union(NSCalendar.Unit.hour).union(NSCalendar.Unit.minute)
var nowComps = (calendar as NSCalendar).components(units, from: Date())
nowComps.day = daysModifier + (nowComps.day ?? 0);
nowComps.hour = 0;
nowComps.minute = 0;
let from = calendar.date(from: nowComps)
nowComps.hour = 23;
nowComps.minute = 59;
let to = calendar.date(from: nowComps)
assert(from != nil);
assert(to != nil);
// Create the predicate from the event store's instance method
let predicate = self.eventStore.predicateForEvents(withStart: from!, end: to!, calendars: calendars)
// Fetch all events that match the predicate
let events = self.eventStore.events(matching: predicate)
DispatchQueue.main.async {
handler(events)
}
}
}
}
// MARK: writing
open func createUnsavedEventCalendar(_ name:String, handler:@escaping EventManagerCalenderCreatedCompletionHandler) {
assertAuthorization() {
// create new calendar.
let calendar = EKCalendar(for: .event, eventStore: self.eventStore)
calendar.title = name
handler(calendar)
}
}
open func createUnsavedEvent(_ title:String, calendar:EKCalendar, handler:@escaping EventManagerEventCreatedCompletionHandler) {
assertAuthorization() {
// create new event
let event = EKEvent(eventStore: self.eventStore)
event.title = title
event.calendar = calendar
handler(event)
}
}
// MARK: auth helper
fileprivate func assertAuthorization(_ handler:@escaping (()->Void)) {
if EKEventStore.authorizationStatus(for: .event) != .authorized {
eventStore.requestAccess(to: .event, completion: { (newAuth, error) -> Void in
//get it
handler()
})
}
else {
//get it
handler()
}
}
}
|
bsd-2-clause
|
7e513e18ecc4f9f4d720e0aa36d27856
| 35.49505 | 228 | 0.586544 | 5.213579 | false | false | false | false |
yariksmirnov/aerial
|
shared/LogMessage.swift
|
1
|
2008
|
//
// LogMessage.swift
//
// Created by Yaroslav Smirnov on 05/12/2016.
// Copyright © 2016 Yaroslav Smirnov. All rights reserved.
//
import ObjectMapper
enum LogLevel: Int, CustomStringConvertible {
case off
case fatal
case error
case warning
case info
case debug
case verbose
var description: String {
switch self {
case .fatal: return "Fatal"
case .error: return "Error"
case .warning: return "Warning"
case .info: return "Info"
case .debug: return "Debug"
case .verbose: return "Verbose"
case .off: return "Off"
}
}
init(string: String) {
switch string {
case "Fatal": self = .fatal
case "Error": self = .error
case "Warning": self = .warning
case "Info": self = .info
case "Debug": self = .debug
case "Verbose": self = .verbose
default: self = .off
}
}
func contains(_ level: LogLevel) -> Bool {
return level.rawValue >= self.rawValue
}
static func allLevels() -> [LogLevel] {
return [.fatal, .error, .warning, .info, .debug, .verbose]
}
}
public class LogMessage: NSObject, Mappable {
var message: String = ""
var level: LogLevel = .off
var file: String = ""
var function: String = ""
var line: Int = 0
var timestamp: Date = Date()
override init() {
super.init()
}
required public init?(map: Map) {
}
public func mapping(map: Map) {
message <- map["message"]
level <- map["level"]
file <- map["file"]
function <- map["function"]
line <- map["line"]
timestamp <- (map["timestamp"], DateTransform())
}
}
extension Packet {
convenience init(_ logMessage: LogMessage) {
self.init()
self.data = logMessage.toJSON()
}
func logMessages() -> [LogMessage] {
return []
}
}
|
mit
|
ed50a026b40453d1b2f34b49d55bb391
| 20.815217 | 66 | 0.541604 | 4.270213 | false | false | false | false |
CoderST/XMLYDemo
|
XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/CategoryViewController/View/CategoryNormalCell.swift
|
1
|
2578
|
//
// CategoryNormalCell.swift
// XMLYDemo
//
// Created by xiudou on 2016/12/27.
// Copyright © 2016年 CoderST. All rights reserved.
//
import UIKit
class CategoryNormalCell: UICollectionViewCell {
var indexPath : IndexPath?
fileprivate lazy var iconImageView : UIImageView = {
let iconImageView = UIImageView()
iconImageView.contentMode = .scaleAspectFill
iconImageView.clipsToBounds = true
return iconImageView
}()
fileprivate lazy var titleLabel : UILabel = {
let titleLabel = UILabel()
titleLabel.font = UIFont.systemFont(ofSize: 12)
titleLabel.numberOfLines = 2
return titleLabel
}()
fileprivate lazy var lineView : UIView = {
let lineView = UIView()
lineView.backgroundColor = UIColor.lightGray
return lineView
}()
var categoryModel : CategoryModel?{
didSet{
guard let categoryModel = categoryModel else { return }
iconImageView.sd_setImage( with: URL(string: categoryModel.coverPath), placeholderImage: UIImage(named: "placeholder_image"))
titleLabel.text = categoryModel.title
if indexPath!.item % 2 == 0{
lineView.isHidden = true
}else{
lineView.isHidden = false
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = UIColor.white
contentView.addSubview(iconImageView)
contentView.addSubview(titleLabel)
contentView.addSubview(lineView)
iconImageView.snp.makeConstraints { (make) in
make.top.equalTo(contentView).offset(10)
make.left.equalTo(contentView).offset(40)
make.bottom.equalTo(contentView).offset(-10)
make.width.equalTo(contentView.bounds.height - 20)
}
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(iconImageView.snp.right).offset(10)
make.top.equalTo(contentView)
make.height.equalTo(contentView)
}
lineView.snp.makeConstraints { (make) in
make.top.equalTo(contentView).offset(10)
make.bottom.equalTo(contentView).offset(-10)
make.left.equalTo(contentView)
make.width.equalTo(1)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
2b59c7a1b1e8075426bcce0c69716cf9
| 28.261364 | 137 | 0.597282 | 5.119284 | false | false | false | false |
ffried/FFUIKit
|
Sources/FFUIKit/Views/Notifications/NotificationView.swift
|
1
|
3405
|
//
// NotificationView.swift
// FFUIKit
//
// Copyright 2016 Florian Friedrich
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#if !os(watchOS)
import UIKit
open class NotificationView: UIView {
public let backgroundView = UIView()
public let contentView = UIView()
private(set) var contentViewTopConstraint: NSLayoutConstraint!
public override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
initialize()
}
private final func initialize() {
backgroundColor = .clear
backgroundView.setupFullscreen(in: self)
contentView.enableAutoLayout()
addSubview(contentView)
let otherConstraints: [NSLayoutConstraint]
if #available(iOS 11, tvOS 11, *) {
contentViewTopConstraint = contentView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor)
otherConstraints = [
contentView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),
contentView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor),
contentView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor),
]
} else {
contentViewTopConstraint = contentView.topAnchor.constraint(equalTo: topAnchor)
otherConstraints = [
contentView.leadingAnchor.constraint(equalTo: leadingAnchor),
contentView.trailingAnchor.constraint(equalTo: trailingAnchor),
contentView.bottomAnchor.constraint(equalTo: bottomAnchor),
]
}
contentViewTopConstraint.isActive = true
otherConstraints.activate()
}
open func configure(for style: NotificationStyle) {
backgroundView.backgroundColor = style.suggestedBackgroundColor
}
@inlinable
internal func _willAppear(animated: Bool) { willAppear(animated: animated) }
@inlinable
internal func _didAppear(animated: Bool) { didAppear(animated: animated) }
@inlinable
internal func _willDisappear(animated: Bool) { willDisappear(animated: animated) }
@inlinable
internal func _didDisappear(animated: Bool) { didDisappear(animated: animated) }
@inlinable
internal func _didReceiveTouch(sender: Any?) { didReceiveTouch(sender: sender) }
// MARK: - Methods for subclasses
open func willAppear(animated: Bool) { /* For Subclasses */ }
open func didAppear(animated: Bool) { /* For Subclasses */ }
open func willDisappear(animated: Bool) { /* For Subclasses */ }
open func didDisappear(animated: Bool) { /* For Subclasses */ }
open func didReceiveTouch(sender: Any?) { /* For Subclasses */ }
}
#endif
|
apache-2.0
|
61e9b375d2afb168a01da05d5ff8ab05
| 36.833333 | 111 | 0.686931 | 4.970803 | false | false | false | false |
CanyFrog/HCComponent
|
HCSource/HCFlowView.swift
|
1
|
2402
|
//
// HCFlowView.swift
// HCComponents
//
// Created by Magee Huang on 5/3/17.
// Copyright © 2017 Person Inc. All rights reserved.
//
import UIKit
public class HCFlowView: UIView {
public static let flow = HCFlowView(frame: CGRect.zero)
private var beforeOrigin: CGPoint!
private override init(frame: CGRect) {
super.init(frame: CGRect(x: 0, y: 24, width: 44, height: 44))
layer.cornerRadius = 5
clipsToBounds = true
layer.contents = #imageLiteral(resourceName: "demo").cgImage
backgroundColor = UIColor.red
beforeOrigin = origin
alpha = 0.0
let tap = UITapGestureRecognizer(target: self, action: #selector(flowViewTapAction(_:)))
addGestureRecognizer(tap)
let pan = UIPanGestureRecognizer(target: self, action: #selector(flowViewPanAction(_:)))
pan.maximumNumberOfTouches = 1
pan.minimumNumberOfTouches = 1
addGestureRecognizer(pan)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public class func showFlow() {
UIApplication.shared.keyWindow?.addSubview(HCFlowView.flow)
UIView.animate(withDuration: 0.3) {
flow.alpha = 1.0
}
}
public class func dismissFlow() {
UIView.animate(withDuration: 0.2, animations: {
flow.alpha = 0.0
}) { (bool) in
flow.removeFromSuperview()
}
}
// MARK: -- actions
@objc private func flowViewTapAction(_ tap: UITapGestureRecognizer) {
print("tap")
}
@objc private func flowViewPanAction(_ pan: UIPanGestureRecognizer) {
switch pan.state {
case .changed:
let p = pan.translation(in: window)
origin = CGPoint(x: left + p.x, y: top + p.y)
pan.setTranslation(CGPoint.zero, in: window) // reset offset
case .ended:
var o = origin
o.x = o.x >= UIScreen.main.bounds.width/2 ? UIScreen.main.bounds.width - width : 0
o.y = max(24, min(o.y, UIScreen.main.bounds.height - height))
origin = o
beforeOrigin = origin
case .cancelled:
origin = beforeOrigin
case .failed:
origin = beforeOrigin
default:
break
}
}
}
|
mit
|
43a081a9ad65fa937807e0ed06e60181
| 29.392405 | 96 | 0.585589 | 4.349638 | false | false | false | false |
nerdishbynature/octokit.swift
|
OctoKit/Milestone.swift
|
1
|
1011
|
import Foundation
open class Milestone: Codable {
open var url: URL?
open var htmlURL: URL?
open var labelsURL: URL?
open private(set) var id: Int = -1
open var number: Int?
open var state: Openness?
open var title: String?
open var milestoneDescription: String?
open var creator: User?
open var openIssues: Int?
open var closedIssues: Int?
open var createdAt: Date?
open var updatedAt: Date?
open var closedAt: Date?
open var dueOn: Date?
enum CodingKeys: String, CodingKey {
case id
case url
case htmlURL = "html_url"
case labelsURL = "labels_url"
case number
case state
case title
case milestoneDescription = "description"
case creator
case openIssues = "open_issues"
case closedIssues = "closed_issues"
case createdAt = "created_at"
case updatedAt = "updated_at"
case closedAt = "closed_at"
case dueOn = "due_on"
}
}
|
mit
|
9da52236f140617f100e5336137d2f76
| 26.324324 | 49 | 0.614243 | 4.143443 | false | false | false | false |
xuech/OMS-WH
|
OMS-WH/Classes/StockSearch/View/Cell/StockOnRoadTableViewCell.swift
|
1
|
1863
|
//
// StockOnRoadTableViewCell.swift
// OMS-WH
//
// Created by ___Gwy on 2017/9/20.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
class StockOnRoadTableViewCell: UITableViewCell {
var stockModel:StockInWHModel?{
didSet{
medControlNameLB.text = "货控方:\(stockModel!.oiName)"
technologyServiceNameLB.text = "技服商:\(stockModel!.dlName)"
hpNameLB.text = "医院:\(stockModel!.hPName)"
medNameLB.text = "物料名称编码:\(stockModel!.medMIName)(\(stockModel!.medMICode))"
medSpecificationLB.text = "物料规格:\(stockModel!.specification)"
supplyNameLB.text = "供货商:\(stockModel!.pOVDOrgCodeName)"
outBoundNumLB.text = "出库单号:\(stockModel!.wONo)"
outBoundStatusLB.text = "出库单状态:\(stockModel!.statusByOutBoundName)"
batchCodeLB.text = "批次/序列号:\(stockModel!.lotSerial)"
countLB.text = "数量:\(stockModel!.inventory)"
}
}
//货控方
@IBOutlet weak var medControlNameLB: UILabel!
@IBOutlet weak var technologyServiceNameLB: UILabel!
@IBOutlet weak var hpNameLB: UILabel!
@IBOutlet weak var medNameLB: UILabel!
@IBOutlet weak var medSpecificationLB: UILabel!
//供货方
@IBOutlet weak var supplyNameLB: UILabel!
@IBOutlet weak var outBoundNumLB: UILabel!
@IBOutlet weak var outBoundStatusLB: UILabel!
@IBOutlet weak var batchCodeLB: UILabel!
@IBOutlet weak var countLB: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
b3a34f3ca8303f4d79725e76366bd222
| 32.730769 | 88 | 0.653364 | 3.880531 | false | false | false | false |
4jchc/4jchc-BaiSiBuDeJie
|
4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Essence-精华/Controller/XMGEssenceViewController.swift
|
1
|
8060
|
//
// XMGEssenceViewController.swift
// 4jchc-BaiSiBuDeJie
//
// Created by 蒋进 on 16/2/15.
// Copyright © 2016年 蒋进. All rights reserved.
//
import UIKit
class XMGEssenceViewController: UIViewController {
/** 标签栏底部的红色指示器 */
var indicatorView:UIView?
/** 当前选中的按钮 */
var selectedButton:UIButton?
/** 顶部的所有标签 */
var titlesView:UIView?
/** 底部的所有内容 */
var contentView:UIScrollView?
override func viewDidLoad() {
super.viewDidLoad()
// 设置导航栏
setupNav()
// 初始化子控制器
setupChildVces()
// 设置顶部的标签栏
setupTitlesView()
// 底部的scrollView
setupContentView()
}
//MARK: 设置顶部的标签栏
func setupTitlesView(){
// 标签栏整体
let titlesView:UIView = UIView()
titlesView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.7)
titlesView.width = self.view.width;
titlesView.height = XMGTitilesViewH;
titlesView.y = XMGTitilesViewY;
self.view.addSubview(titlesView)
self.titlesView = titlesView;
// 底部的红色指示器
let indicatorView:UIView = UIView()
indicatorView.backgroundColor = UIColor.redColor()
indicatorView.height = 2;
indicatorView.tag = -1
indicatorView.y = titlesView.height - indicatorView.height;
self.indicatorView = indicatorView;
// 内部的子标签
let width:CGFloat = titlesView.width / CGFloat(self.childViewControllers.count)
let height:CGFloat = titlesView.height
for var i:Int = 0; i < self.childViewControllers.count; i++ {
let button:UIButton = UIButton()
button.tag = i
button.height = height;
button.width = width;
button.x = CGFloat(i) * width;
let vc:UIViewController = self.childViewControllers[i];
button.setTitle(vc.title, forState: UIControlState.Normal)
button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
button.setTitleColor(UIColor.redColor(), forState: UIControlState.Disabled)
button.titleLabel?.font = UIFont.systemFontOfSize(14)
button.addTarget(self, action: "titleClick:", forControlEvents: UIControlEvents.TouchUpInside)
titlesView.addSubview(button)
// 默认点击了第一个按钮
if (i == 0) {
button.enabled = false
self.selectedButton = button;
// 让按钮内部的label根据文字内容来计算尺寸
button.titleLabel!.sizeToFit()
self.indicatorView!.width = button.titleLabel!.width;
self.indicatorView!.centerX = button.centerX;
}
}
titlesView.addSubview(indicatorView)
}
func titleClick(button:UIButton){
// 修改按钮状态
self.selectedButton!.enabled = true
button.enabled = false
self.selectedButton = button;
UIView.animateWithDuration(0.25) { () -> Void in
self.indicatorView!.width = button.titleLabel!.width;
self.indicatorView!.centerX = button.centerX;
}
// 设置滚动范围
var offset:CGPoint = self.contentView!.contentOffset;
offset.x = CGFloat(button.tag) * self.contentView!.width
self.contentView?.setContentOffset(offset, animated: true)
}
//MARK: 设置导航栏
func setupNav() {
// 设置导航栏标题
self.navigationItem.titleView = UIImageView(image: UIImage(named: "MainTitle"))
// 设置导航栏左的按钮
self.navigationItem.leftBarButtonItem = UIBarButtonItem.ItemWithBarButtonItem("MainTagSubIcon", target: self, action: "tagClick")
// 设置背景色
self.view.backgroundColor = XMGGlobalBg;
}
//MARK: - 底部的scrollView
func setupContentView(){
// 不要自动调整ScrollView Insets
self.automaticallyAdjustsScrollViewInsets = false
let contentView = UIScrollView()
contentView.frame = self.view.bounds;
contentView.delegate = self;
contentView.pagingEnabled = true
self.view.insertSubview(contentView, atIndex: 0)
contentView.contentSize = CGSizeMake(contentView.width * CGFloat(self.childViewControllers.count), 0);
self.contentView = contentView;
// 添加第一个控制器的view
self.scrollViewDidEndScrollingAnimation(contentView)
}
//MARK: 初始化子控制器
func setupChildVces(){
let all = XMGTopicViewController()
all.title = "全部";
all.type = XMGTopicType.All;
self.addChildViewController(all)
let video = XMGTopicViewController()
video.title = "视频";
video.type = XMGTopicType.Video
self.addChildViewController(video)
let voice = XMGTopicViewController()
voice.title = "声音";
voice.type = XMGTopicType.Voice;
self.addChildViewController(voice)
let picture = XMGTopicViewController()
picture.title = "图片";
picture.type = XMGTopicType.Picture;
self.addChildViewController(picture)
let word = XMGTopicViewController()
word.title = "段子";
word.type = XMGTopicType.Word;
self.addChildViewController(word)
}
func tagClick(){
let tags = XMGRecommendTagsViewController()
self.navigationController?.pushViewController(tags, animated: true)
}
}
extension XMGEssenceViewController:UIScrollViewDelegate {
//MARK: 结束滚动动画完毕调用Scrolling Animation
func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
// 当前的索引
let index:Int = Int(scrollView.contentOffset.x / scrollView.width)
/*
// 取出子控制器
let vc:UITableViewController = self.childViewControllers[index] as! UITableViewController
// 一定要设置view的x.y
vc.view.x = scrollView.contentOffset.x;
vc.view.y = 0; // 设置控制器view的y值为0(默认是20)
vc.view.height = scrollView.height; // 设置控制器view的height值为整个屏幕的高度(默认是比屏幕高度少个20)
// 设置内边距
let bottom:CGFloat = self.tabBarController!.tabBar.height;
let top:CGFloat = CGRectGetMaxY(self.titlesView!.frame);
vc.tableView.contentInset = UIEdgeInsetsMake(top, 0, bottom, 0);
// 设置滚动条的内边距
vc.tableView.scrollIndicatorInsets = vc.tableView.contentInset;
*/
// 取出子控制器💗设置 xy轴 以后有可能是不同的UIViewController而非都是UITableViewController
let vc:UIViewController = self.childViewControllers[index]
vc.view.x = scrollView.contentOffset.x;
vc.view.y = 0; // 设置控制器view的y值为0(默认是20)
vc.view.height = scrollView.height; // 设置控制器view的height值为整个屏幕的高度(默认是比屏幕高度少个20)
// 设置内边距让他们自己设置
scrollView.addSubview(vc.view)
}
//MARK: 减速完毕调用End Decelerating减速
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
scrollViewDidEndScrollingAnimation(scrollView)
// 点击按钮
let index:Int = Int(scrollView.contentOffset.x / scrollView.width)
self.titleClick(self.titlesView?.subviews[index] as! UIButton)
}
}
|
apache-2.0
|
aee6805d2a12483cd9408942fcb9d8c7
| 30.741379 | 137 | 0.608772 | 4.788036 | false | false | false | false |
brentdax/swift
|
test/IRGen/objc_bridge.swift
|
1
|
11042
|
// RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-ir -primary-file %s | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
// CHECK: [[GETTER_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00"
// CHECK: [[SETTER_SIGNATURE:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00"
// CHECK: [[DEALLOC_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00"
// CHECK: @_INSTANCE_METHODS__TtC11objc_bridge3Bas = private constant { i32, i32, [17 x { i8*, i8*, i8* }] } {
// CHECK: i32 24,
// CHECK: i32 17,
// CHECK: [17 x { i8*, i8*, i8* }] [
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strRealProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC11strRealPropSSvgTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrRealProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC11strRealPropSSvsTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strFakeProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC11strFakePropSSvgTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrFakeProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC11strFakePropSSvsTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrRealProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvgTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrRealProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvsTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrFakeProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvgTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrFakeProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvsTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(strResult)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC9strResultSSyFTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([{{[0-9]*}} x i8], [{{[0-9]*}} x i8]* @"\01L_selector_data(strArgWithS:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC6strArg1sySS_tFTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(nsstrResult)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC11nsstrResultSo8NSStringCyFTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* @"\01L_selector_data(nsstrArgWithS:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC8nsstrArg1sySo8NSStringC_tFTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasCACycfcTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasCfDTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"\01L_selector_data(acceptSet:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @{{[0-9]+}}, i64 0, i64 0),
// CHECK: i8* bitcast (void (%3*, i8*, %4*)* @"$s11objc_bridge3BasC9acceptSetyyShyACSo8NSObjectCSH10ObjectiveCg_GFTo" to i8*)
// CHECK: }
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @{{.*}}, i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasCfETo" to i8*)
// CHECK: }
// CHECK: ]
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: @_PROPERTIES__TtC11objc_bridge3Bas = private constant { i32, i32, [5 x { i8*, i8* }] } {
// CHECK: [[OBJC_BLOCK_PROPERTY:@.*]] = private unnamed_addr constant [11 x i8] c"T@?,N,C,Vx\00"
// CHECK: @_PROPERTIES__TtC11objc_bridge21OptionalBlockProperty = private constant {{.*}} [[OBJC_BLOCK_PROPERTY]]
func getDescription(_ o: NSObject) -> String {
return o.description
}
func getUppercaseString(_ s: NSString) -> String {
return s.uppercase()
}
// @interface Foo -(void) setFoo: (NSString*)s; @end
func setFoo(_ f: Foo, s: String) {
f.setFoo(s)
}
// NSString *bar(int);
func callBar() -> String {
return bar(0)
}
// void setBar(NSString *s);
func callSetBar(_ s: String) {
setBar(s)
}
var NSS : NSString = NSString()
// -- NSString methods don't convert 'self'
extension NSString {
// CHECK: define internal [[OPAQUE:.*]]* @"$sSo8NSStringC11objc_bridgeE13nsstrFakePropABvgTo"([[OPAQUE:.*]]*, i8*) unnamed_addr
// CHECK: define internal void @"$sSo8NSStringC11objc_bridgeE13nsstrFakePropABvsTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr
@objc var nsstrFakeProp : NSString {
get {
return NSS
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @"$sSo8NSStringC11objc_bridgeE11nsstrResultAByFTo"([[OPAQUE:.*]]*, i8*) unnamed_addr
@objc func nsstrResult() -> NSString { return NSS }
// CHECK: define internal void @"$sSo8NSStringC11objc_bridgeE8nsstrArg1syAB_tFTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr
@objc func nsstrArg(s s: NSString) { }
}
class Bas : NSObject {
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC11strRealPropSSvgTo"([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
// CHECK: define internal void @"$s11objc_bridge3BasC11strRealPropSSvsTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
@objc var strRealProp : String
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC11strFakePropSSvgTo"([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
// CHECK: define internal void @"$s11objc_bridge3BasC11strFakePropSSvsTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
@objc var strFakeProp : String {
get {
return ""
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvgTo"([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
// CHECK: define internal void @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvsTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
@objc var nsstrRealProp : NSString
// CHECK: define hidden swiftcc %TSo8NSStringC* @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvg"(%T11objc_bridge3BasC* swiftself) {{.*}} {
// CHECK: define internal void @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvsTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
@objc var nsstrFakeProp : NSString {
get {
return NSS
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC9strResultSSyFTo"([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
@objc func strResult() -> String { return "" }
// CHECK: define internal void @"$s11objc_bridge3BasC6strArg1sySS_tFTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
@objc func strArg(s s: String) { }
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC11nsstrResultSo8NSStringCyFTo"([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
@objc func nsstrResult() -> NSString { return NSS }
// CHECK: define internal void @"$s11objc_bridge3BasC8nsstrArg1sySo8NSStringC_tFTo"([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
@objc func nsstrArg(s s: NSString) { }
override init() {
strRealProp = String()
nsstrRealProp = NSString()
super.init()
}
deinit { var x = 10 }
override var hashValue: Int { return 0 }
@objc func acceptSet(_ set: Set<Bas>) { }
}
func ==(lhs: Bas, rhs: Bas) -> Bool { return true }
class OptionalBlockProperty: NSObject {
@objc var x: (([AnyObject]) -> [AnyObject])?
}
|
apache-2.0
|
5e4dd0500bcd4a3af4c2d7be6d6eb16f
| 53.394089 | 146 | 0.592556 | 3.140501 | false | false | false | false |
HabitRPG/habitrpg-ios
|
Habitica Database/Habitica Database/Models/User/RealmEmailNotifications.swift
|
1
|
1733
|
//
// RealmEmailNotifications.swift
// Habitica Database
//
// Created by Phillip Thelen on 05.02.20.
// Copyright © 2020 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import RealmSwift
class RealmEmailNotifications: Object, EmailNotificationsProtocol {
@objc dynamic var id: String?
@objc dynamic var giftedGems: Bool = false
@objc dynamic var giftedSubscription: Bool = false
@objc dynamic var invitedGuild: Bool = false
@objc dynamic var invitedParty: Bool = false
@objc dynamic var invitedQuest: Bool = false
@objc dynamic var hasNewPM: Bool = false
@objc dynamic var questStarted: Bool = false
@objc dynamic var wonChallenge: Bool = false
@objc dynamic var majorUpdates: Bool = false
@objc dynamic var unsubscribeFromAll: Bool = false
@objc dynamic var kickedGroup: Bool = false
@objc dynamic var subscriptionReminders: Bool = false
override static func primaryKey() -> String {
return "id"
}
convenience init(id: String?, pnProtocol: EmailNotificationsProtocol) {
self.init()
self.id = id
giftedGems = pnProtocol.giftedGems
giftedSubscription = pnProtocol.giftedSubscription
invitedGuild = pnProtocol.invitedGuild
invitedParty = pnProtocol.invitedParty
invitedQuest = pnProtocol.invitedQuest
hasNewPM = pnProtocol.hasNewPM
questStarted = pnProtocol.questStarted
wonChallenge = pnProtocol.wonChallenge
majorUpdates = pnProtocol.majorUpdates
unsubscribeFromAll = pnProtocol.unsubscribeFromAll
kickedGroup = pnProtocol.kickedGroup
subscriptionReminders = pnProtocol.subscriptionReminders
}
}
|
gpl-3.0
|
f9ddc7a6af65f25d5e3cb81856a3a55f
| 35.083333 | 75 | 0.713626 | 4.452442 | false | false | false | false |
Urinx/SublimeCode
|
Sublime/Sublime/Utils/Extension/UITextView.swift
|
1
|
824
|
//
// UITextView.swift
// Sublime
//
// Created by Eular on 4/20/16.
// Copyright © 2016 Eular. All rights reserved.
//
import Foundation
// MARK: - UITextView
extension UITextView {
func scrollToBottom() {
let range:NSRange = NSMakeRange(self.text.characters.count - 1, 1)
self.scrollRangeToVisible(range)
self.scrollEnabled = false
self.scrollEnabled = true
}
func setLineBreakMode(mode: NSLineBreakMode) {
let attrStr = self.attributedText.mutableCopy()
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = mode
attrStr.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attrStr.mutableString.length))
self.attributedText = attrStr as! NSAttributedString
}
}
|
gpl-3.0
|
e468129d793ef2510ed3d26a0ff33862
| 29.518519 | 135 | 0.695018 | 4.869822 | false | false | false | false |
PJayRushton/stats
|
Stats/NewUserState.swift
|
1
|
818
|
//
// NewUserState.swift
// Stats
//
// Created by Parker Rushton on 3/28/17.
// Copyright © 2017 AppsByPJ. All rights reserved.
//
import UIKit
struct NoOp: Event { }
struct EmailAvailabilityUpdated: Event {
var isAvailable: Bool
}
struct EmailUpdated: Event {
var email: String?
}
struct NewUserState: State {
var email: String?
var emailIsAvailable = false
var isLoading = false
mutating func react(to event: Event) {
switch event {
case let event as EmailUpdated:
email = event.email
case let event as EmailAvailabilityUpdated:
emailIsAvailable = event.isAvailable
isLoading = false
case _ as Loading<NewUserState>:
isLoading = true
default:
break
}
}
}
|
mit
|
b68d677f6897a8b6cd5a47f9057eba64
| 19.425 | 51 | 0.609547 | 4.416216 | false | false | false | false |
StanZabroda/Hydra
|
Hydra/HRAPIManager.swift
|
1
|
1902
|
import Foundation
class HRAPIManager {
//////////////////////////////////////////
static let sharedInstance = HRAPIManager()
//////////////////////////////////////////
// audio.get
func vk_audioget(ownerId:Int, count:Int,offset:Int,completion: ([HRAudioItemModel]) -> ()) {
let getAudio : VKRequest!
if ownerId == 0 {
getAudio = VKRequest(method: "audio.get", andParameters: ["count":count,"offset":offset], andHttpMethod: "GET")
} else {
getAudio = VKRequest(method: "audio.get", andParameters: ["owner_id":ownerId,"count":count,"offset":offset], andHttpMethod: "GET")
}
getAudio.executeWithResultBlock({ (response) -> Void in
var audiosArray = Array<HRAudioItemModel>()
let json = response.json as! Dictionary<String,AnyObject>
let items = json["items"] as! Array<Dictionary<String,AnyObject>>
for audioDict in items {
let jsonAudioItem = JSON(audioDict)
let audioItemModel:HRAudioItemModel = HRAudioItemModel(json: jsonAudioItem)
if HRDataManager.sharedInstance.arrayWithDownloadedIds.contains(audioItemModel.audioID) {
audioItemModel.downloadState = 3
} else {
audioItemModel.downloadState = 1
}
audiosArray.append(audioItemModel)
}
completion(audiosArray)
}, errorBlock: { (error) -> Void in
log.error("audio.get #### \(error)")
})
}
}
|
mit
|
dee4ab8b2229aec43efdcabddf94544a
| 31.793103 | 142 | 0.461094 | 5.660714 | false | false | false | false |
abertelrud/swift-package-manager
|
Fixtures/Miscellaneous/Plugins/PluginWithInternalExecutable/Sources/PluginExecutable/main.swift
|
2
|
988
|
import Foundation
// Sample source generator tool that emits a Swift variable declaration of a string containing the hex representation of the contents of a file as a quoted string. The variable name is the base name of the input file. The input file is the first argument and the output file is the second.
if ProcessInfo.processInfo.arguments.count != 3 {
print("usage: MySourceGenBuildTool <input> <output>")
exit(1)
}
let inputFile = ProcessInfo.processInfo.arguments[1]
let outputFile = ProcessInfo.processInfo.arguments[2]
let variableName = URL(fileURLWithPath: inputFile).deletingPathExtension().lastPathComponent
let inputData = FileManager.default.contents(atPath: inputFile) ?? Data()
let dataAsHex = inputData.map { String(format: "%02hhx", $0) }.joined()
let outputString = "public var \(variableName) = \(dataAsHex.quotedForSourceCode)\n"
let outputData = outputString.data(using: .utf8)
FileManager.default.createFile(atPath: outputFile, contents: outputData)
|
apache-2.0
|
4a82f7e11fe102922dba54cc60010195
| 57.117647 | 291 | 0.781377 | 4.352423 | false | false | false | false |
MoodTeam/MoodApp
|
MoodApp/MoodApp/RealParse.swift
|
1
|
2417
|
//
// RealParse.swift
// MoodApp
//
// Created by Charles Lin on 29/11/14.
// Copyright (c) 2014 42labs. All rights reserved.
//
import Foundation
class RealParse : IParse {
required init() {
}
// Sample usage:
// GenericParse.addToParse("NameInParse", dict: ["fId": "3", "name": "Hello World", "imageUrl": ""])
func addToParse(parseClassName: String, dict: Dictionary<String, AnyObject>) {
var query = PFQuery(className: parseClassName)
query.findObjectsInBackgroundWithBlock{(objects: [AnyObject]!, error: NSError!) -> Void in
for object in objects {
if (parseClassName == "Friend")
{
var dataRow = object as PFObject
var fId = dataRow.objectForKey("fId") as String
var fIdToSave = dict["fId"] as String
if (fId == fIdToSave)
{
return
}
}
}
var dataRow = PFObject(className: parseClassName)
for keyValue in dict {
dataRow.setObject(keyValue.1, forKey: keyValue.0)
}
dataRow.saveInBackgroundWithBlock {
(success: Bool!, error: NSError!) -> () in
if (success != nil && success!) {
NSLog("Object created in \(parseClassName) with id: \(dataRow.objectId)")
} else {
NSLog("%@", error)
}
}
}
}
// Sample usage:
// func parseObjects(objects: [AnyObject]!) { ... }
// func handleError(error: NSError!) { ... }
// GenericParse.loadFromParse("NameInParse", parseObjects, handleError)
func loadFromParse(parseClassName: String, onLoadSuccess: ([AnyObject]!) -> (), onLoadFailure: (NSError!) -> ()) {
var query = PFQuery(className: parseClassName)
query.findObjectsInBackgroundWithBlock{
(objects: [AnyObject]!, error: NSError!) -> () in
if error == nil {
NSLog("Successfully retrieved \(objects.count) objects from \(parseClassName).")
onLoadSuccess(objects)
} else {
NSLog("Error loading \(parseClassName) from Parse")
onLoadFailure(error)
}
}
}
}
|
mit
|
ed3783af23c52c91d4716cab4d4062aa
| 33.528571 | 118 | 0.512619 | 5.035417 | false | false | false | false |
urbanthings/urbanthings-sdk-apple
|
UrbanThingsAPI/Internal/UrbanThingsAPI.swift
|
1
|
4057
|
//
// UrbanThingsAPI.swift
// UrbanThingsAPI
//
// Created by Mark Woollard on 26/04/2016.
// Copyright © 2016 UrbanThings. All rights reserved.
//
import Foundation
extension NSLocale {
static var httpAcceptLanguage: String {
return preferredLanguages.prefix(5).enumerated().map { "\($0.1);q=\(1.0-Double($0.0)*0.1)" }.joined(separator: ", ")
}
}
extension URLSessionTask : UrbanThingsAPIRequest {
}
extension Service {
var baseURLString: String {
return "\(endpoint)/\(version)"
}
}
extension UrbanThingsAPI {
func toHttpResponse(response: URLResponse?) throws -> HTTPURLResponse {
guard let httpResponse = response as? HTTPURLResponse else {
throw UTAPIError(unexpected: "Expected HTTPURLResponse, got \(String(describing: response))", file: #file, function: #function, line: #line)
}
return httpResponse
}
func validateHTTPStatus(response: HTTPURLResponse, data: Data?) throws {
guard response.statusCode < 300 else {
var message: String? = "Unknown server error"
if response.hasJSONBody && data != nil {
// This is to catch the non-standard JSON based error that API currently reports at times. If this is
// not present message is default localised message for error code
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
message = (json as? [String:AnyObject])?["message"] as? String
} catch {
}
}
throw UTAPIError.HTTPStatusError(code: response.statusCode, message: message)
}
}
func validateData(response: HTTPURLResponse, data: Data?) throws {
guard response.hasJSONBody else {
throw UTAPIError(unexpected: "Content-Type not application/json", file: #file, function: #function, line: #line)
}
guard let _ = data else {
throw UTAPIError(unexpected: "No data in response", file: #file, function: #function, line: #line)
}
}
func parseData<T>(parser:(_ json: Any?, _ logger: Logger) throws -> T, data: Data) throws -> T {
#if DEBUG
if let utf8 = String(data: data, encoding: String.Encoding.utf8) {
logger.log(level: .debug, utf8)
print("\(utf8)")
}
#endif
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]
var v2or3: Any? = json?["data"]
if v2or3 == nil {
v2or3 = json
}
return try parser(v2or3, logger)
}
func handleResponse<T>(parser:@escaping (_ json: Any?, _ logger: Logger) throws -> T, result:@escaping (_ data: T?, _ error: Error?) -> Void)
-> (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void {
func taskCompletionHandler(data: Data?, response: URLResponse?, error: Error?) {
guard error == nil else {
result(nil, error)
return
}
do {
let httpResponse = try self.toHttpResponse(response: response)
logger.log(level: .debug, "\(httpResponse)")
try self.validateHTTPStatus(response: httpResponse, data: data)
try self.validateData(response: httpResponse, data: data)
result(try self.parseData(parser: parser, data: data!) as T, nil)
} catch {
self.logger.log(level: .error, "\(error)")
result(nil, error as Error)
}
}
return taskCompletionHandler
}
func buildURL<R: Request>(request: R) -> String {
let parameters = request.queryParameters.description
let separator = parameters.characters.count > 0 ? "&" : "?"
return "\(self.service.baseURLString)/\(request.endpoint)\(request.queryParameters.description)\(separator)apikey=\(self.service.key)"
}
}
|
apache-2.0
|
da1c64e1e389a51595b3e79274f6a7e0
| 36.906542 | 152 | 0.582594 | 4.552189 | false | false | false | false |
smart23033/boostcamp_iOS_bipeople
|
Bipeople/Bipeople/BiPeopleNavigationViewController.swift
|
1
|
38113
|
//
// BiPeopleNavigationViewController.swift
// Bipeople
//
// Created by YeongSik Lee on 2017. 8. 9..
// Copyright © 2017년 BluePotato. All rights reserved.
//
import UIKit
import RealmSwift
import CoreLocation
import GoogleMaps
import GooglePlaces
import GooglePlacePicker
import GeoQueries
import MarqueeLabel
// MARK: Class
class BiPeopleNavigationViewController: UIViewController {
// MARK: Outlets
/// 기록 취소 후 네비게이션 모드 종료 버튼
@IBOutlet weak var cancelButton: UIBarButtonItem! {
willSet(newVal) {
navigationButtons["left"] = newVal
navigationItem.leftBarButtonItem = nil
}
}
/// 기록 저장 후 네비게이션 모드 종료 버튼
@IBOutlet weak var doneButton: UIBarButtonItem! {
willSet(newVal) {
navigationButtons["right"] = newVal
navigationItem.rightBarButtonItem = nil
}
}
/// 주행 정보 창
@IBOutlet weak var infoView: UIView!
/// 네비게이션 시작 버튼
@IBOutlet weak var startButton: UIButton!
/// 예상 경로 취소 버튼
@IBOutlet weak var clearButton: UIButton!
/// 현재 위치 주변 공공장소를 보여줄지를 결정할 버튼
@IBOutlet weak var placesButton: UIButton!
/// 주행시간 표시 라벨
@IBOutlet weak var timeLabel: UILabel!
/// 주행거리 표시 라벨
@IBOutlet weak var distanceLabel: UILabel!
/// 칼로리 표시 라벨
@IBOutlet weak var calorieLabel: UILabel!
/// 속도계 표시 라벨
@IBOutlet weak var speedLabel: UILabel!
/// 네비게이션에 사용 될 MapView
@IBOutlet weak var navigationMapView: GMSMapView! {
didSet {
navigationMapView.settings.scrollGestures = true
navigationMapView.settings.zoomGestures = true
navigationMapView.settings.consumesGesturesInView = false;
navigationMapView.settings.myLocationButton = true
navigationMapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
navigationMapView.isMyLocationEnabled = true
}
}
/// 맵을 Reloading 할 때 보여줄 Indicator
@IBOutlet weak var loadingIndicatorView: UIActivityIndicatorView!
/// 네비게이션 모드 중 주행 정보를 보여줄 화면
@IBOutlet weak var infoViewHeightConstraint: NSLayoutConstraint!
// MARK: Lazy Variables
/// 구글 장소 자동완성 검색창
lazy private var searchPlaceController: UISearchController = {
// GMS(Google Mobile Service) 장소 자동완성 검색기능 설정
let resultsViewController = GMSAutocompleteResultsViewController()
let innerSearchPlaceController = UISearchController(searchResultsController: resultsViewController)
resultsViewController.delegate = self
innerSearchPlaceController.searchResultsUpdater = resultsViewController
// 장소 검색창을 네비게이션 타이틀 위치에 삽입
// innerSearchPlaceController.searchBar.sizeToFit()
// Prevent the navigation bar from being hidden when searching...
innerSearchPlaceController.hidesNavigationBarDuringPresentation = false
innerSearchPlaceController.searchBar.placeholder = "장소 검색"
innerSearchPlaceController.searchBar.tintColor = UIColor.primary
return innerSearchPlaceController
} ()
/// 좌에서 우로 흘러가며 앞글자는 사라지고, 뒷글자는 보이는 Label
lazy private var marqueeTitle : MarqueeLabel = {
let label = MarqueeLabel()
label.frame = self.view.frame
label.textAlignment = .center
label.type = .continuous
label.speed = .duration(10)
label.adjustsFontSizeToFitWidth = true
label.adjustsFontForContentSizeCategory = true
label.textColor = UIColor.white
return label
} ()
// private var infoViewFrame: CGRect!
// private var mapViewFrame: CGRect!
// MARK: Private Variables
/// navigationItem에서 보이지 않게 하기 위해 버튼을 nil로 만들면 메모리 해제 되는 것을 막기 위해 저장
private var navigationButtons: [String:UIBarButtonItem] = [:]
/// 네비게이션 모드 책임
private var navigationManager: NavigationManager!
/// GPS 정보(위치, 방향, 속도, 고도) 관리자
private var locationManager: CLLocationManager!
/// 정보 창 라벨 갱신 타이머
private var recordTimer: Timer?
/// 네비게이션 모드가 실행되거나 종료될 때, UI의 변화를 책임
private var isNavigationOn: Bool = false {
willSet(newVal) {
if newVal {
do {
initInfoView()
startTimer(selector: #selector(updateInfoView))
try navigationManager.initDatas()
self.navigationItem.titleView = marqueeTitle
self.navigationItem.leftBarButtonItem = navigationButtons["cancel"]
self.navigationItem.rightBarButtonItem = navigationButtons["done"]
startButton.isHidden = true
clearButton.isHidden = true
toggleInfoView()
}
catch {
self.isNavigationOn = false
print("Initialize datas failed with error: ", error)
let warningAlert = UIAlertController(
title: "네비게이션 모드 전환에 실패하였습니다",
message: error.localizedDescription,
preferredStyle: .alert
)
warningAlert.addAction(UIAlertAction(title: "확인", style: .default))
self.present(warningAlert, animated: true)
stopTimer()
initInfoView()
}
} else {
self.navigationItem.leftBarButtonItem = nil
self.navigationItem.rightBarButtonItem = nil
self.navigationItem.titleView = searchPlaceController.searchBar
navigationManager.clearRoute()
if #available(iOS 11.0, *) {
let navigationBarFrame = CGRect(x: 0 , y: 20, width: self.view.frame.width, height: 64)
self.navigationController?.navigationBar.frame = navigationBarFrame
}
startButton.isHidden = false
clearButton.isHidden = true
stopTimer()
initInfoView()
}
}
}
/// 마커가 선택 된 경우, 맵을 선택한 경우 마커 선택이 해제되도록
private var selectedMarker: GMSMarker?
/// 네비게이션 모드에서 터치 시, 5초 가량 현재위치 화면고정 해제
private var timeUnlocked: TimeInterval = Date().timeIntervalSince1970
// MARK: Life Cycle
override func viewDidLoad() {
/*******************************************************************************************/
// 공공장소 세부사항 View에서 검색창이 사라지면서 네비게이션 바 아래에 검정줄이 생기는 것을 해결
self.navigationController?.navigationBar.isTranslucent = true;
UIBarButtonItem.appearance(whenContainedInInstancesOf:[UISearchBar.self]).tintColor = UIColor.white
/*******************************************************************************************/
// 첫 화면에 네비게이션 버튼을 없애고, 장소 검색창이 보이도록 설정
navigationButtons = [
"cancel" : cancelButton,
"done" : doneButton
]
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
navigationItem.titleView = searchPlaceController.searchBar
// When UISearchController presents the results view, present it in
// this view controller, not one further up the chain...
self.definesPresentationContext = true
/*******************************************************************************************/
// CLLocationManager 초기화
locationManager = CLLocationManager()
locationManager.allowsBackgroundLocationUpdates = true
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationManager.distanceFilter = 10 // 이전 위치에서 얼마나 거리차가 나면 위치변경 트리거를 실행할지 결정
locationManager.startUpdatingLocation()
locationManager.startUpdatingHeading()
locationManager.delegate = self
/*******************************************************************************************/
// NavigationManager 초기화
navigationManager = NavigationManager(mapView: navigationMapView)
}
// MARK: Actions
/// 공공장소에서 이동 버튼을 눌렀을 경우 unwind
@IBAction func unwindFromPlaceDetailVC(_ segue: UIStoryboardSegue) {
guard
let placeDetailVC = segue.source as? PlaceDetailViewController,
let selectedPlace = placeDetailVC.selectedPlace
else {
return
}
unpinScreen(for: 5)
let placeCoord = CLLocationCoordinate2D(
latitude: selectedPlace.lat,
longitude: selectedPlace.lng
)
moveMap(coordinate: placeCoord)
if isNavigationOn == false {
navigationManager.setDestination(
coord: placeCoord,
name: selectedPlace.title,
address: selectedPlace.address
)
getRouteAndDrawForDestination()
}
}
/// 현재 까지의 주행기록을 취소하는 버튼
@IBAction func didTapCancelButton(_ sender: Any) {
let confirmAlert = UIAlertController(
title: "정말 기록을 중지하시겠습니까?",
message: "현재 까지의 기록은 저장되지 않고 종료됩니다",
preferredStyle: .alert
)
confirmAlert.addAction(UIAlertAction(title: "취소", style: .cancel))
confirmAlert.addAction(UIAlertAction(title: "확인", style: .default) { _ in
self.navigationManager.guideWithVoice(at: Int.max)
self.isNavigationOn = false
})
self.present(confirmAlert, animated: true)
}
/// 현재 까지의 주행기록을 저장하는 버튼
@IBAction func didTapDoneButton(_ sender: Any) {
let confirmAlert = UIAlertController(
title: "정말 기록을 중지하시겠습니까?",
message: "현재 까지의 기록을 저장하고 종료합니다",
preferredStyle: .alert
)
confirmAlert.addAction(UIAlertAction(title: "취소", style: .cancel))
confirmAlert.addAction(UIAlertAction(title: "확인", style: .default) { _ in
self.navigationManager.guideWithVoice(at: Int.max)
self.isNavigationOn = false
self.trySaveData()
try? self.navigationManager.initDatas()
})
self.present(confirmAlert, animated: true)
}
/// 네비게이션 모드를 시작하고 주행 정보를 기록하는 버튼
@IBAction func didTapStartButton(_ sender: Any) {
let time = navigationManager.estimatedTime
let distance = navigationManager.expectedDistance
var title: String
if distance > 0 {
title = """
주행 기록을 시작하시겠습니까?
예상주행시간: \(time.digitalFormat)
예상주행거리: \(distance.roundTo(places: 1)) m
"""
}
else {
title = "자율 주행 기록을 시작하시겠습니까?"
}
let confirmAlert = UIAlertController(
title: title,
message: nil,
preferredStyle: .alert
)
confirmAlert.addAction(UIAlertAction(title: "취소", style: .cancel))
confirmAlert.addAction(UIAlertAction(title: "확인", style: .default) { _ in
self.isNavigationOn = true
self.processBasedOnCurrentStatus()
})
self.present(confirmAlert, animated: true)
}
/// 네비게이션 모드를 시작하고 주행 정보를 기록하는 버튼
@IBAction func didTapClearButton(_ sender: Any) {
navigationManager.clearRoute()
clearButton.isHidden = true
}
/// 보이는 화면에 공공장소를 토글하는 버튼
@IBAction func didTapPlacesButton(_ sender: Any) {
unpinScreen(for: 5)
placesButton.isSelected = !placesButton.isSelected
if placesButton.isSelected {
let placesCount = try! Realm().objects(PublicPlace.self).count
guard placesCount > 0 else { // 아직 데이터를 받아 오지 못한 경우
placesButton.isSelected = false
let warningAlert = UIAlertController(
title: "아직 공공데이터를 받아오지 못하였습니다",
message: "다시 시도하시겠습니까?(2초 후 자동으로 사라집니다)",
preferredStyle: .alert
)
warningAlert.addAction(UIAlertAction(title: "취소", style: .cancel))
warningAlert.addAction(UIAlertAction(title: "확인", style: .default) { _ in
self.didTapPlacesButton(sender)
})
self.present(warningAlert, animated: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
warningAlert.dismiss(animated: true, completion: nil)
}
return
}
let bound = GMSCoordinateBounds(region: navigationMapView.projection.visibleRegion())
navigationManager.showPlaces(in: bound)
} else {
navigationManager.clearAllPlaces()
}
}
/// 사용자가 앱을 사용할 경우, 화면 고정을 5초간 해제
@IBAction func didTapView(_ sender: Any) {
unpinScreen(for: 5)
}
/// 사용자가 앱을 사용할 경우, 화면 고정을 5초간 해제
@IBAction func didPinchView(_ sender: Any) {
unpinScreen(for: 5)
}
/// 사용자가 앱을 사용할 경우, 화면 고정을 5초간 해제
@IBAction func didRotateView(_ sender: Any) {
unpinScreen(for: 5)
}
/// 사용자가 앱을 사용할 경우, 화면 고정을 5초간 해제
@IBAction func didSwipeView(_ sender: Any) {
unpinScreen(for: 5)
}
/// 사용자가 앱을 사용할 경우, 화면 고정을 5초간 해제
@IBAction func didPanView(_ sender: Any)
{
unpinScreen(for: 5)
}
/// 사용자가 앱을 사용할 경우, 화면 고정을 5초간 해제
@IBAction func didEdgePanView(_ sender: Any) {
unpinScreen(for: 5)
}
/// 사용자가 앱을 사용할 경우, 화면 고정을 5초간 해제
@IBAction func didLongPressView(_ sender: Any) {
unpinScreen(for: 5)
}
// MARK: Private Methods
/// 인자로 받은 시간만큼 화면 고정을 해제
private func unpinScreen(for second: Double) {
timeUnlocked = Date().timeIntervalSince1970 + second
if isNavigationOn {
toggleInfoView()
}
}
/// 화면을 현재 위치로 고정
private func pinScreen() {
timeUnlocked = Date().timeIntervalSince1970
if isNavigationOn {
toggleInfoView()
}
}
/// 현재위치에서 목적지까지의 경로를 갖고와 맵에 표시
private func getRouteAndDrawForDestination(recorded: Bool = false) {
navigationMapView.isHidden = true // 경로 파싱이 완료 될 때까지 맵 감춤
loadingIndicatorView.startAnimating()
navigationManager.getGeoJSONFromTMap(failure: { (error) in
print("getGeoJSONFromTMap failed with error: ", error)
let warningAlert = UIAlertController(
title: "경로를 가져오는데 실패했습니다",
message: error.localizedDescription,
preferredStyle: .alert
)
warningAlert.addAction(UIAlertAction(title: "확인", style: .default))
self.present(warningAlert, animated: true) {
self.loadingIndicatorView.stopAnimating()
self.navigationMapView.isHidden = false
self.startButton.isHidden = true
}
}) { data in
// print("data: ", String(data:data, encoding: .utf8) ?? "nil") // FOR DEBUG
guard recorded == self.isNavigationOn else {
return
}
let geoJSON = try JSONDecoder().decode(
GeoJSON.self,
from: data
)
self.navigationManager.setRouteAndWaypoints(from: geoJSON)
self.navigationManager.drawRoute()
self.navigationManager.showMarkers()
self.loadingIndicatorView.stopAnimating()
self.navigationMapView.isHidden = false
self.startButton.isHidden = self.isNavigationOn
self.clearButton.isHidden = self.isNavigationOn
if recorded == false, let destination = self.navigationManager.getDestinationCoord() {
self.moveMap(coordinate: destination)
self.unpinScreen(for: 5)
}
}
}
/// 주행 기록을 저장
private func trySaveData() {
do {
try navigationManager.saveData()
let confirmAlert = UIAlertController(
title: "주행기록 저장에 성공하였습니다",
message: "",
preferredStyle: .alert
)
confirmAlert.addAction(UIAlertAction(title: "확인", style: .default))
self.present(confirmAlert, animated: true)
} catch {
let warningAlert = UIAlertController(
title: "주행기록 저장에 실패하였습니다",
message: error.localizedDescription,
preferredStyle: .alert
)
warningAlert.addAction(UIAlertAction(title: "취소", style: .cancel) { _ in
self.isNavigationOn = false
})
warningAlert.addAction(UIAlertAction(title: "재시도", style: .default) { _ in
self.trySaveData() // 주의 - 재귀함수
})
self.present(warningAlert, animated: true)
}
}
/// 맵을 coordinate 위치로 이동시키고, bearing 방향으로 회전시킴
private func moveMap(coordinate: CLLocationCoordinate2D?) {
guard let coord = coordinate else {
return
}
// #if arch(i386) || arch(x86_64)
let bearing = navigationManager.calculateBearing(to: coord)
let camera = GMSCameraPosition.camera(
withTarget: coord,
zoom: 15.0,
bearing: bearing,
viewingAngle: -1
)
// #else
// let camera = GMSCameraPosition.camera(
// withTarget: coord,
// zoom: 15.0
// )
// #endif
if navigationMapView.isHidden {
loadingIndicatorView.stopAnimating()
navigationMapView.isHidden = false
DispatchQueue.main.async {
self.navigationMapView.camera = camera
}
} else {
navigationMapView.animate(to: camera)
}
}
/// 주행 정보창을 띄우거나 숨김
private func toggleInfoView() {
if timeUnlocked < Date().timeIntervalSince1970 { // 화면 고정이 된 상태에서
if infoView.isHidden == true { // 정보 창이 보이지 않는 상태라면
infoView.isHidden = false // 정보 창을 보여준다(애니메이션 효과)
UIView.animate(
withDuration: 1.0,
delay: 0.0,
options: .curveEaseInOut,
animations: {
let height = self.view.frame.height * 0.3
self.infoViewHeightConstraint.constant = height
self.view.layoutIfNeeded()
},
completion: nil
)
}
} else { // 화면 고정되지 않은 상태에서
if infoView.isHidden == false { // 정보 창이 보이는 상태라면
UIView.animate( // 정보 창을 감춘다(애니메이션 효과)
withDuration: 1.0,
delay: 0.0,
options: .curveEaseInOut,
animations: {
self.infoViewHeightConstraint.constant = 0
self.view.layoutIfNeeded()
}
) { _ in
self.infoView.isHidden = true
}
}
}
}
/// 네비게이션에서 현재 위치를 바탕으로 안내를 해줌
private func processBasedOnCurrentStatus() {
switch navigationManager.currentStatus {
case .arrived: // 목적지 도착을 확인 후, 도착한 경우 기록 저장 및 안내 종료
navigationManager.guideWithVoice(at: Int.max)
isNavigationOn = false
trySaveData()
case let .waypoint(index): // 중간 경유지를 지나가는 경우 음성 안내
navigationManager.guideWithVoice(at: index)
case .offroad: // 경로에서 벗어난 경우, 현 위치에서 목적지 까지 새로운 경로를 구해 안내(Async)
let warningAlert = UIAlertController(
title: "경로 이탈",
message: "경로를 재설정 합니다(3초 후 자동으로 사라집니다)",
preferredStyle: .alert
)
warningAlert.addAction(UIAlertAction(title: "종료(저장)", style: .destructive){ _ in
self.navigationManager.guideWithVoice(at: Int.max)
self.isNavigationOn = false
self.trySaveData()
})
warningAlert.addAction(UIAlertAction(title: "종료(취소)", style: .cancel){ _ in
self.navigationManager.guideWithVoice(at: Int.max)
self.isNavigationOn = false
})
self.present(warningAlert, animated: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
warningAlert.dismiss(animated: true, completion: nil)
}
navigationManager.guideWithVoice(at: Int.min)
getRouteAndDrawForDestination(recorded: true)
case .freeride:
navigationManager.guideWithVoice(at: 0)
break
case .onroad:
break
case .error:
break
}
}
/// 주행기록 타이머 시작
private func startTimer(selector: Selector) {
recordTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: selector, userInfo: nil, repeats: true)
}
/// 주행기록 타이머 종료
private func stopTimer() {
recordTimer?.invalidate()
recordTimer = nil
}
/// 주행 정보창 초기화
private func initInfoView() {
infoViewHeightConstraint.constant = 0
infoView.isHidden = true
timeLabel.text = "00:00:00"
distanceLabel.text = nil
calorieLabel.text = nil
speedLabel.text = nil
marqueeTitle.text = LiteralString.tracking.rawValue
}
/// 타이머를 통해 주행 정보 창 갱신
@objc private func updateInfoView() {
guard let speed = navigationManager.currentLocation?.speed else {
return
}
timeLabel.text = navigationManager.recordTime.digitalFormat
distanceLabel.text = "\((navigationManager.recordDistance / 1000.0).roundTo(places: 2))"
calorieLabel.text = "\(navigationManager.recordCalorie.roundTo(places: 1))"
speedLabel.text = speed < 0 ? "계산중" : "\(speed.roundTo(places: 1))"
}
}
// MARK: Exteinsions
/// CoreLocation 네비게이션 작동 시에 사용
extension BiPeopleNavigationViewController: CLLocationManagerDelegate {
func locationManagerShouldDisplayHeadingCalibration(_ manager: CLLocationManager) -> Bool {
return false
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
// #if arch(i386) || arch(x86_64)
return
// #else
// guard
// timeUnlocked < Date().timeIntervalSince1970,
// newHeading.timestamp.timeIntervalSinceNow > -30,
// newHeading.headingAccuracy >= 0
// else {
// return
// }
//
// navigationMapView.animate(toBearing: newHeading.trueHeading)
// #endif
}
/// 위치 변화 이벤트 핸들러
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let updatedLocation = locations.last else {
print("Location is nil")
return
}
// print("Updated Location: ", updatedLocation) // FOR DEBUG
if navigationManager.currentLocation == nil {
navigationMapView.isHidden = false
let seoul = CLLocationCoordinate2D(
latitude: 37.541,
longitude: 126.986
)
let worldCamera = GMSCameraPosition.camera(
withTarget: seoul,
zoom: 10
)
navigationMapView.camera = worldCamera
DispatchQueue.main.async {
CATransaction.begin()
CATransaction.setValue(2, forKey: kCATransactionAnimationDuration)
let camera = GMSCameraPosition.camera(
withTarget: updatedLocation.coordinate,
zoom: 15
)
self.navigationMapView.animate(to: camera)
CATransaction.commit()
}
navigationMapView.setMinZoom(14, maxZoom: 100)
}
navigationManager.currentLocation = updatedLocation
// 사용자의 사용이 없는 경우 맵의 중심을 현재 위치로
if timeUnlocked < Date().timeIntervalSince1970 {
moveMap(coordinate: updatedLocation.coordinate)
}
// 네비게이션 모드가 켜져있는 경우
if isNavigationOn {
// 상태 정보 창 토글
toggleInfoView()
// 위치 변화 정보 저장
do {
try navigationManager.addTrace(location: updatedLocation)
} catch {
print("Save trace data failed with error: ", error)
}
// 현재 위치를 NavigationBar Title로(Async)
navigationManager.geoCoder(failure: { (error) in
print("GeoCoder failed with error: ", error)
self.marqueeTitle.text = LiteralString.tracking.rawValue
}) { (address) in
self.marqueeTitle.text = address
}
processBasedOnCurrentStatus()
}
}
/// 위치 권한 변화 이벤트 핸들러
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted:
print("Location access was restricted...") // FOR DEBUG
case .denied:
print("User denied access to location...") // FOR DEBUG
navigationMapView.isHidden = true
loadingIndicatorView.startAnimating()
// Alert 문을 띄우고 앱 이용을 위해 위치 권한이 필요함을 알리고
// 확인을 누르면 환경설정 탭으로, 종료를 누르면 앱을 종료
let warningAlert = UIAlertController(
title: "Bipeople을 사용하기 위해서는 위치 정보 권한이 필요합니다",
message: "사용을 위해 확인을 눌러 환경설정으로 이동한 후 위치 권한을 승인해주세요",
preferredStyle: .alert
)
warningAlert.addAction(UIAlertAction(title: "이동", style: .default) { _ in
guard
let settingsUrl = URL(string: UIApplicationOpenSettingsURLString),
UIApplication.shared.canOpenURL(settingsUrl)
else {
return
}
UIApplication.shared.open(settingsUrl) { result in
print("Settings open ", (result ? "success" : "failed"))
}
})
warningAlert.addAction(UIAlertAction(title: "종료", style: .destructive) { _ in
exit(EXIT_SUCCESS)
})
self.present(warningAlert, animated: true)
case .notDetermined:
print("Location status not determined...") // FOR DEBUG
case .authorizedAlways: fallthrough
case .authorizedWhenInUse:
print("Location status is OK...") // FOR DEBUG
}
}
/// 위치 정보 에러 처리 핸들러
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
// FOR DEBUG
print("Location update fail with: ", error)
}
}
/// 구글 맵뷰 Delegate
extension BiPeopleNavigationViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
selectedMarker = marker
return false
}
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
guard
let infoWindow = Bundle.main.loadNibNamed("MarkerInfoWindow", owner: self, options: nil)?.first as? MarkerInfoWindow,
let place = marker.userData as? PublicPlace
else {
return nil
}
infoWindow.nameLabel.text = place.title
return infoWindow
}
func mapView(_ mapView: GMSMapView, didTapInfoWindowOf marker: GMSMarker) {
let storyboard = UIStoryboard(name: "Navigation", bundle: nil)
guard
let place = marker.userData as? PublicPlace,
let placeDetailVC = storyboard.instantiateViewController(withIdentifier: "PlaceDetailViewController") as? PlaceDetailViewController
else {
return
}
placeDetailVC.isNavigationOn = isNavigationOn
placeDetailVC.selectedPlace = place
placeDetailVC.nearPlaces = navigationManager.publicPlaces
self.navigationController?.pushViewController(placeDetailVC, animated: true)
}
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
let bound = GMSCoordinateBounds(region: navigationMapView.projection.visibleRegion())
// 현재 위치 주변 공공장소 보여주기
if placesButton.isSelected {
navigationManager.showPlaces(in: bound)
} else {
navigationManager.clearAllPlaces()
}
guard let marker = selectedMarker else {
return
}
if bound.contains(marker.position) == false {
selectedMarker = nil
}
}
/// 맵에서 위치가 선택(터치)된 경우
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
// 네비게이션 모드 중이 아닌 경우, 마커가 선택되어 Info Window가 보이고 있는 경우
guard isNavigationOn == false, selectedMarker == nil else {
selectedMarker = nil
return
}
let VIEWPORT_DELTA = 0.001 // 선택된 지점 주변 반경(맵에서 보여줄)
let northEast = CLLocationCoordinate2DMake(coordinate.latitude + VIEWPORT_DELTA, coordinate.longitude + VIEWPORT_DELTA) // ㄱ
let southWest = CLLocationCoordinate2DMake(coordinate.latitude - VIEWPORT_DELTA, coordinate.longitude - VIEWPORT_DELTA) // ㄴ
let viewport = GMSCoordinateBounds(coordinate: northEast, coordinate: southWest)
let config = GMSPlacePickerConfig(viewport: viewport)
let placePicker = GMSPlacePickerViewController(config: config)
placePicker.delegate = self
self.present(placePicker, animated: true)
}
func didTapMyLocationButton(for mapView: GMSMapView) -> Bool {
pinScreen()
return false
}
}
/// 장소를 맵을 선택(터치)하여 선택해서
extension BiPeopleNavigationViewController: GMSPlacePickerViewControllerDelegate {
func placePicker(_ viewController: GMSPlacePickerViewController, didPick place: GMSPlace) {
// FOR DEBUG
print("Selected Place name: ", place.name)
print("Selected Place address: ", place.formattedAddress ?? LiteralString.unknown.rawValue)
print("Selected Place attributions: ", place.attributions ?? NSAttributedString())
// Dismiss the place picker.
viewController.dismiss(animated: true) {
self.navigationManager.setDestination(
coord: place.coordinate,
name: place.name,
address: place.formattedAddress
)
self.getRouteAndDrawForDestination()
}
}
func placePicker(_ viewController: GMSPlacePickerViewController, didFailWithError error: Error) {
// FOR DEBUG
print("place picker fail with : ", error.localizedDescription)
viewController.dismiss(animated: true)
}
func placePickerDidCancel(_ viewController: GMSPlacePickerViewController) {
// FOR DEBUG
print("The place picker was canceled by the user")
viewController.dismiss(animated: true)
}
}
/// 구글 장소 자동완성 기능
extension BiPeopleNavigationViewController: GMSAutocompleteResultsViewControllerDelegate {
func resultsController(_ resultsController: GMSAutocompleteResultsViewController, didAutocompleteWith place: GMSPlace) {
searchPlaceController.isActive = false
// FOR DEBUG
print("Searched Place name: ", place.name)
print("Searched Place address: ", place.formattedAddress ?? LiteralString.unknown.rawValue)
print("Searched Place attributions: ", place.attributions ?? NSAttributedString())
// 선택된 장소로 화면을 전환하기 위한 카메라 정보
moveMap(coordinate: place.coordinate)
navigationManager.setDestination(
coord: place.coordinate,
name: place.name,
address: place.formattedAddress
)
getRouteAndDrawForDestination()
}
/// FOR DEBUG: 장소검색 자동완성에서 에러 발생 시
func resultsController(_ resultsController: GMSAutocompleteResultsViewController, didFailAutocompleteWithError error: Error) {
print("result update fail with : ", error.localizedDescription)
}
/// Turn the network activity indicator on
func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
/// Turn the network activity indicator off
func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
|
mit
|
67aad8a427b66c7c79dc5a7348d99f42
| 32.819593 | 143 | 0.551136 | 4.444048 | false | false | false | false |
venticake/RetricaImglyKit-iOS
|
RetricaImglyKit/Classes/Frontend/DataSources/RemoteFramesDataSource.swift
|
1
|
5501
|
// This file is part of the PhotoEditor Software Development Kit.
// Copyright (C) 2016 9elements GmbH <[email protected]>
// All rights reserved.
// Redistribution and use in source and binary forms, without
// modification, are permitted provided that the following license agreement
// is approved and a legal/financial contract was signed by the user.
// The license agreement can be found under the following link:
// https://www.photoeditorsdk.com/LICENSE.txt
import UIKit
/**
This protocol is used to get tokens and insert them into the called url.
That way we can deal with urls that contain tokens.
*/
@available(iOS 8, *)
@objc(IMGLYTokenProvider) public protocol TokenProvider {
/**
Returns a token that is used to perform an API call.
- parameter completionBlock: A completion block that has the token or an error as payload.
*/
func getToken(completionBlock: (String?, NSError?) -> Void)
}
/**
An implementation of `FramesDataSourceProtocol` that can be used to download frames from a remote source.
*/
@available(iOS 8, *)
@objc(IMGLYRemoteFramesDataSource) public class RemoteFramesDataSource: NSObject, FramesDataSourceProtocol {
/// The placeholder string that will be replaced by the token of the token provider.
public static let TokenString = "##Token##"
/// A `FrameStore` that is used by this class. It defaults to the `sharedStore`.
public var frameStore: FrameStoreProtocol = FrameStore.sharedStore
/// The URL used for the call use ##Token## as place holder for a token that is set by a token provider.
public var url = ""
/// An object that implements the `TokenProvider` protocol.
public var tokenProvider: TokenProvider? = nil
private var frames: [Frame]? = nil
// MARK: - Init
private func getFrames(completionBlock: ([Frame]?, NSError?) -> Void) {
guard url.characters.count > 0 else {
completionBlock(nil, NSError(info: Localize("URL not set")))
return
}
if let frames = self.frames {
completionBlock(frames, nil)
} else {
if url.containsString(RemoteFramesDataSource.TokenString) {
if let tokenProvider = tokenProvider {
tokenProvider.getToken({ (token, error) -> Void in
if let token = token {
let finalURL = self.url.stringByReplacingOccurrencesOfString(RemoteFramesDataSource.TokenString, withString: token)
self.performFrameCall(NSURL(string: finalURL)!, completionBlock: completionBlock)
}
})
} else {
completionBlock(nil, NSError(info: Localize("Url contains the token place holder, but no token provider is set")))
}
} else {
performFrameCall(NSURL(string: url)!, completionBlock: completionBlock)
}
}
}
private func performFrameCall(finalURL: NSURL, completionBlock: ([Frame]?, NSError?) -> Void) {
frameStore.get(finalURL, completionBlock: { records, error in
if let records = records {
self.frames = [Frame]()
for record in records {
let frame = Frame(info: record)
self.frames?.append(frame)
}
completionBlock(self.frames, nil)
} else {
completionBlock(nil, error)
}
})
}
// MARK: - StickersDataSource
/**
The count of frames.
- parameter completionBlock: A completion block.
*/
public func frameCount(ratio: Float, completionBlock: (Int, NSError?) -> Void) {
getFrames({ frames, error in
if let frames = frames {
self.frames = frames
completionBlock(frames.count, nil)
} else {
completionBlock(0, error)
}
})
}
/**
Returns the thumbnail and label of the frame at a given index for the ratio.
- parameter index: The index of the frame.
- parameter ratio: The ratio of the image.
- parameter completionBlock: Used to return the result asynchronously.
*/
public func thumbnailAndLabelAtIndex(index: Int, ratio: Float, completionBlock: (UIImage?, String?, NSError?) -> ()) {
getFrames({ frames, error in
if let frames = self.frames {
let frame = frames[index]
frame.thumbnailForRatio(ratio, completionBlock: { (image, error) -> () in
if let image = image {
completionBlock(image, frame.accessibilityText, nil)
} else {
completionBlock(nil, nil, error)
}
})
} else {
completionBlock(nil, nil, error)
}
})
}
/**
Retrieves a the frame at the given index.
- parameter index: A index.
- parameter completionBlock: A completion block.
*/
public func frameAtIndex(index: Int, ratio: Float, completionBlock: (Frame?, NSError?) -> ()) {
getFrames({ frames, error in
self.frames = frames
if let frames = frames {
completionBlock(frames[index], nil)
} else {
completionBlock(nil, error)
}
})
}
}
|
mit
|
255c829b8fbbb1771d3f8e70c58dbab2
| 36.168919 | 143 | 0.590802 | 5.019161 | false | false | false | false |
MetalPetal/MetalPetal
|
MetalPetalExamples/Shared/ImageFilterView.swift
|
1
|
4008
|
//
// ImageFilterView.swift
// MetalPetalDemo
//
// Created by YuAo on 2021/4/5.
//
import Foundation
import MetalPetal
import SwiftUI
import VideoToolbox
struct FilterParameter<Filter> {
var name: String
var defaultValue: Float
var sliderRange: ClosedRange<Float>
var step: Float.Stride? = nil
let updater: (Filter, Float) -> Void
}
extension FilterParameter: Identifiable {
var id: String { name }
}
struct ImageFilterView<Filter>: View where Filter: MTIFilter {
@State private var inputImage: MTIImage = DemoImages.p1040808
@State private var values: [String: Float]
@StateObject private var renderContext = try! MTIContext(device: MTLCreateSystemDefaultDevice()!)
private let filter: Filter
private let parameters: [FilterParameter<Filter>]
private let filterInputKeyPath: ReferenceWritableKeyPath<Filter, MTIImage?>
private let isChangingImageAllowed: Bool
private let imageRenderer = PixelBufferPoolBackedImageRenderer()
init(filter: Filter, filterInputKeyPath: ReferenceWritableKeyPath<Filter, MTIImage?>, parameters: [FilterParameter<Filter>], isChangingImageAllowed: Bool = true) {
self.isChangingImageAllowed = isChangingImageAllowed
self.filterInputKeyPath = filterInputKeyPath
self.parameters = parameters
self.filter = filter
self.values = [:]
}
private func valueBinding<T>(for parameter: FilterParameter<T>) -> Binding<Float> {
Binding<Float>(get: {
values[parameter.name, default: parameter.defaultValue]
}, set: {
values[parameter.name] = $0
})
}
private func filter(_ image: MTIImage?) throws -> CGImage {
filter[keyPath: filterInputKeyPath] = image
for parameter in parameters {
parameter.updater(filter, values[parameter.name, default: parameter.defaultValue])
}
guard let outputImage = filter.outputImage else {
throw DescriptiveError("Filter outputs nil image.")
}
return try self.imageRenderer.render(outputImage, using: renderContext).cgImage
}
var body: some View {
Group {
switch Result(catching: {
try filter(inputImage)
}) {
case .success(let image):
VStack {
Image(cgImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
VStack {
ForEach(parameters) { parameter in
VStack(alignment: .leading) {
Text("\(parameter.name) \(values[parameter.name, default: parameter.defaultValue], specifier: "%.2f")")
if let step = parameter.step {
Slider(value: valueBinding(for: parameter), in: parameter.sliderRange, step: step, onEditingChanged: { _ in })
} else {
Slider(value: valueBinding(for: parameter), in: parameter.sliderRange)
}
}
.padding()
.background(RoundedRectangle(cornerRadius: 10)
.foregroundColor(Color.secondarySystemBackground))
}
}.padding()
}
case .failure(let error):
Text(error.localizedDescription)
}
}
.toolbar(content: {
if isChangingImageAllowed {
ImagePicker(title: "Choose Image", handler: { url in
if let image = ImageUtilities.loadUserPickedImage(from: url, requiresUnpremultipliedAlpha: true) {
self.inputImage = image
}
})
} else {
Spacer()
}
})
}
}
|
mit
|
a33a9db1993f587f52645f50ce467885
| 36.811321 | 167 | 0.561627 | 5.372654 | false | false | false | false |
micchyboy1023/CoreAnimation100Days
|
CoreAnimation100Days/Day2View.swift
|
1
|
2915
|
//
// Day2View.swift
// CoreAnimation100Days
//
// Created by UetaMasamichi on 2015/06/01.
// Copyright (c) 2015年 Masamichi Ueta. All rights reserved.
//
import UIKit
@objc(Day2View)
class Day2View: UIView {
var circleProgressLayer: CAShapeLayer!
var circleBackLayer: CAShapeLayer!
let circleRadius = CGFloat(100)
var circleCenter: CGPoint!
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
func configureView() {
circleCenter = CGPoint(x: self.center.x , y: 200)
}
override func drawRect(rect: CGRect) {
drawBackgoundGradient()
drawBackCircle()
drawProgressCircle()
}
func drawBackgoundGradient() {
let ctx = UIGraphicsGetCurrentContext()
CGContextSaveGState(ctx)
let startColor = UIColor(red: 194.0 / 255.0, green: 70.0 / 255.0, blue: 70.0 / 255.0, alpha: 1.0)
let endColor = UIColor(red: 204.0 / 255.0, green: 104.0 / 255.0, blue: 58.0 / 255.0, alpha: 1.0)
let colors = [startColor.CGColor, endColor.CGColor]
let locations:[CGFloat] = [0.0, 1.0]
let space = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradientCreateWithColors(space, colors, locations)
CGContextDrawLinearGradient(ctx, gradient, CGPointZero, CGPoint(x: 0, y: self.bounds.height), CGGradientDrawingOptions.allZeros)
CGContextRestoreGState(ctx)
}
func drawBackCircle() {
if circleBackLayer == nil {
circleBackLayer = CAShapeLayer()
let path = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: CGFloat(0), endAngle: CGFloat(M_PI * 2), clockwise: true)
circleBackLayer.path = path.CGPath
circleBackLayer.strokeColor = UIColor.darkGrayColor().CGColor
circleBackLayer.opacity = 0.5
circleBackLayer.fillColor = nil
circleBackLayer.lineWidth = 20.0
self.layer.addSublayer(circleBackLayer)
}
}
func drawProgressCircle() {
if circleProgressLayer == nil {
circleProgressLayer = CAShapeLayer()
var startAngle = CGFloat(-M_PI_2)
var endAngle = CGFloat(M_PI_2 * 0.8)
let path = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
circleProgressLayer.path = path.CGPath
circleProgressLayer.lineWidth = 20.0
circleProgressLayer.lineCap = "round"
circleProgressLayer.strokeColor = UIColor.whiteColor().CGColor
circleProgressLayer.fillColor = nil
self.layer.addSublayer(circleProgressLayer)
}
}
}
|
mit
|
328ce3ad075e6d98802152cdfac72bbc
| 32.872093 | 152 | 0.627532 | 4.43379 | false | false | false | false |
wackosix/WSCoderObject-Swift
|
WSCoderObject/Classes/WSCoderObject.swift
|
1
|
1329
|
//
// WSCoderObject.swift
// WSCoderObject
//
// Created by OneZens on 16/1/25.
// Copyright © 2016年 www.onezen.cc. All rights reserved.
//
import UIKit
class WSCoderObject: NSObject, NSCoding {
//归档
func encode(with aCoder: NSCoder) {
var count: UInt32 = 0
let ivars = class_copyIvarList(self.classForCoder, &count)
for i in 0..<count {
let ivar = ivars?[Int(i)]
let name = String.init(cString: ivar_getName(ivar), encoding: .utf8)
if let varName = name {
aCoder.encode(value(forKey: varName), forKey: varName)
}
}
free(ivars)
}
//解档
required init?(coder aDecoder: NSCoder) {
super.init()
var count: UInt32 = 0
let ivars = class_copyIvarList(self.classForCoder, &count)
for i in 0..<count {
let ivar = ivars?[Int(i)]
let name = String.init(cString: ivar_getName(ivar), encoding: .utf8)
if let varName = name {
setValue(aDecoder.decodeObject(forKey: varName), forKey: varName)
}
}
free(ivars)
}
override init() {
super.init()
}
}
|
mit
|
a4ccc8b6d20a80f4f92184ec91f02713
| 21.724138 | 81 | 0.503035 | 4.279221 | false | false | false | false |
wuzhenli/MyDailyTestDemo
|
swiftTest/swifter-tips+swift+3.0/Swifter.playground/Pages/local-scope.xcplaygroundpage/Contents.swift
|
2
|
887
|
import UIKit
import PlaygroundSupport
func local(_ closure: ()->()) {
closure()
}
func loadView() {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
view.backgroundColor = .white
local {
let titleLabel = UILabel(frame: CGRect(x: 150, y: 30, width: 200, height: 40))
titleLabel.textColor = .red
titleLabel.text = "Title"
view.addSubview(titleLabel)
}
local {
let textLabel = UILabel(frame: CGRect(x: 150, y: 80, width: 200, height: 40))
textLabel.textColor = .red
textLabel.text = "Text"
view.addSubview(textLabel)
}
PlaygroundPage.current.liveView = view
}
loadView()
let titleLabel: UILabel = {
let label = UILabel(frame: CGRect(x: 150, y: 30, width: 200, height: 40))
label.textColor = .red
label.text = "Title"
return label
}()
|
apache-2.0
|
f32facd50e15aaf9ac6ab40e7fc04e85
| 23 | 86 | 0.600902 | 3.806867 | false | false | false | false |
miracl/amcl
|
version3/swift/config_curve.swift
|
2
|
732
|
public struct CONFIG_CURVE{
static public let WEIERSTRASS=0
static public let EDWARDS=1
static public let MONTGOMERY=2
static public let NOT=0
static public let BN=1
static public let BLS=2
static public let D_TYPE=0
static public let M_TYPE=1
static public let POSITIVEX=0
static public let NEGATIVEX=1
static public let CURVETYPE = @CT@
static public let CURVE_PAIRING_TYPE = @PF@
static public let SEXTIC_TWIST = @ST@
static public let SIGN_OF_X = @SX@
static public let ATE_BITS = @AB@
static public let HASH_TYPE = @HT@
static public let AESKEY = @AK@
static let USE_GLV = true
static let USE_GS_G2 = true
static let USE_GS_GT = true
}
|
apache-2.0
|
c0bad503316be8f45bf3ec1b067d6eb0
| 28.28 | 47 | 0.668033 | 3.469194 | false | false | false | false |
ustwo/formvalidator-swift
|
Tests/Unit Tests/Conditions/Logic/OrConditionTests.swift
|
1
|
2270
|
//
// OrConditionTests.swift
// FormValidatorSwift
//
// Created by Aaron McTavish on 13/01/2016.
// Copyright © 2016 ustwo. All rights reserved.
//
import XCTest
@testable import FormValidatorSwift
final class OrConditionTests: XCTestCase {
let firstCondition = RangeCondition(configuration: ConfigurationSeeds.RangeSeeds.zeroToFour)
let secondCondition = AlphanumericCondition()
// MARK: - Test Initializers
func testOrCondition_DefaultInit() {
// Given
let condition = OrCondition()
let expectedCount = 1
// When
let actualCount = condition.conditions.count
// Test
XCTAssertEqual(actualCount,
expectedCount,
"Expected number of conditions to be: \(expectedCount) but found: \(actualCount)")
}
// MARK: - Test Success
func testOrCondition_Success() {
// Given
let testInput = ""
var condition = OrCondition(conditions: [firstCondition, secondCondition])
let expectedResult = true
// When
condition.localizedViolationString = "Min 0 Max 4 or must only contain alphanumeric"
// Initial Tests
AssertCondition(firstCondition, testInput: testInput, expectedResult: true)
AssertCondition(secondCondition, testInput: testInput, expectedResult: false)
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
// MARK: - Test Failure
func testOrCondition_Failure() {
// Given
let testInput = "1A234?"
var condition = OrCondition(conditions: [firstCondition, secondCondition])
let expectedResult = false
// When
condition.localizedViolationString = "Min 0 Max 4 or must only contain alphanumeric"
// Initial Tests
AssertCondition(firstCondition, testInput: testInput, expectedResult: false)
AssertCondition(secondCondition, testInput: testInput, expectedResult: false)
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
}
|
mit
|
9ec82e67982fe46fed575a695d1774cf
| 28.855263 | 105 | 0.626267 | 5.42823 | false | true | false | false |
rolson/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Content Display Logic/Controllers/SegmentedViewController.swift
|
1
|
1959
|
// Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
class SegmentedViewController: UIViewController {
@IBOutlet private weak var segmentedControl:UISegmentedControl!
@IBOutlet private weak var infoContainerView:UIView!
@IBOutlet private weak var codeContainerView:UIView!
private var sourceCodeVC:SourceCodeViewController!
private var sampleInfoVC:SampleInfoViewController!
var filenames:[String]!
var folderName:String!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "SourceCodeSegue" {
let controller = segue.destinationViewController as! SourceCodeViewController
controller.filenames = self.filenames
}
else if segue.identifier == "SampleInfoSegue" {
let controller = segue.destinationViewController as! SampleInfoViewController
controller.folderName = self.folderName
}
}
//MARK: - Actions
@IBAction func valueChanged(sender: UISegmentedControl) {
self.infoContainerView.hidden = (sender.selectedSegmentIndex == 1)
}
}
|
apache-2.0
|
fdf1ea9f9f18745ab9461d8a0d541558
| 32.775862 | 89 | 0.697805 | 5.237968 | false | false | false | false |
MakiZz/30DaysToLearnSwift3.0
|
project 16 - sildeMenu/project 16 - sildeMenu/MenuTransitionManager.swift
|
1
|
2984
|
//
// MenuTransitionManager.swift
// project 16 - sildeMenu
//
// Created by mk on 17/3/20.
// Copyright © 2017年 maki. All rights reserved.
//
import UIKit
@objc protocol MenuTransitionManagerDelegate {
func dismiss()
}
class MenuTransitionManager: NSObject ,UIViewControllerAnimatedTransitioning,UIViewControllerTransitioningDelegate {
var duration = 0.5
var isPresenting = false
var delegate:MenuTransitionManagerDelegate?
var snapshot:UIView? {
didSet {
if let _delegate = delegate {
let tapGestureRecongnizer = UITapGestureRecognizer.init(target: _delegate, action: #selector(MenuTransitionManagerDelegate.dismiss))
snapshot?.addGestureRecognizer(tapGestureRecongnizer)
}
}
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)!
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
let container = transitionContext.containerView
let moveDown = CGAffineTransform(translationX: 0, y: container.frame.height - 150)
let moveUp = CGAffineTransform.init(translationX: 0, y: -50)
if isPresenting {
toView.transform = moveUp
snapshot = fromView.snapshotView(afterScreenUpdates: true)
container.addSubview(toView)
container.addSubview(snapshot!)
}
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.3, options: .curveEaseInOut, animations: {
if self.isPresenting {
self.snapshot?.transform = moveDown
toView.transform = CGAffineTransform.identity
}else{
self.snapshot?.transform = CGAffineTransform.identity
fromView.transform = moveUp
}
}) { (finished) in
transitionContext.completeTransition(true)
if !self.isPresenting {
self.snapshot?.removeFromSuperview()
}
}
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = false
return self
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = true
return self
}
}
|
mit
|
8cb348009b02a0b6170487eaa596a704
| 29.418367 | 170 | 0.612546 | 6.342553 | false | false | false | false |
dclelland/AudioKit
|
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Formant Filter.xcplaygroundpage/Contents.swift
|
2
|
2758
|
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Formant Filter
//: ##
import XCPlayground
import AudioKit
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("drumloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
var filter = AKFormantFilter(player)
AudioKit.output = filter
AudioKit.start()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
//: UI Elements we'll need to be able to access
var centerFrequencyLabel: Label?
var attackLabel: Label?
var decayLabel: Label?
override func setup() {
addTitle("Formant Filter")
addLabel("Audio Player")
addButton("Start", action: #selector(start))
addButton("Stop", action: #selector(stop))
addLabel("Formant Filter Parameters")
addButton("Process", action: #selector(process))
addButton("Bypass", action: #selector(bypass))
centerFrequencyLabel = addLabel("Center Frequency: \(filter.centerFrequency) Hz")
addSlider(#selector(setCenterFrequency), value: filter.centerFrequency, minimum: 20, maximum: 22050)
attackLabel = addLabel("Attack: \(filter.attackDuration) Seconds")
addSlider(#selector(setAttack), value: filter.attackDuration, minimum: 0, maximum: 0.1)
decayLabel = addLabel("Decay: \(filter.decayDuration) Seconds")
addSlider(#selector(setDecay), value: filter.decayDuration, minimum: 0, maximum: 0.1)
}
//: Handle UI Events
func start() {
player.play()
}
func stop() {
player.stop()
}
func process() {
filter.play()
}
func bypass() {
filter.bypass()
}
func setCenterFrequency(slider: Slider) {
filter.centerFrequency = Double(slider.value)
let frequency = String(format: "%0.1f", filter.centerFrequency)
centerFrequencyLabel!.text = "Center Frequency: \(frequency) Hz"
}
func setAttack(slider: Slider) {
filter.attackDuration = Double(slider.value)
let attack = String(format: "%0.3f", filter.attackDuration)
attackLabel!.text = "Attack: \(attack) Seconds"
}
func setDecay(slider: Slider) {
filter.decayDuration = Double(slider.value)
let decay = String(format: "%0.3f", filter.decayDuration)
decayLabel!.text = "Decay: \(decay) Seconds"
}
}
let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: 500, height: 550))
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = view
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
|
mit
|
899ea57580fdca2cc2d4303f2bd870f4
| 28.031579 | 108 | 0.637418 | 4.256173 | false | false | false | false |
hollyschilling/EssentialElements
|
EssentialElements/EssentialElements/ItemLists/ViewControllers/SimpleAnnotatedMapViewController.swift
|
1
|
2834
|
//
// SimpleAnnotatedMapViewController.swift
// EssentialElements
//
// Created by Holly Schilling on 3/7/17.
// Copyright © 2017 Better Practice Solutions. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
import MapKit
import CoreData
open class SimpleAnnotatedMapViewController<ItemType, AnnotationViewType: MKAnnotationView>: AnnotatedMapViewController<ItemType> where ItemType: MKAnnotation & NSFetchRequestResult {
open var annotationViewIdentifier: String = "annotationViewIdentifier"
open var configureAnotationView: ((SimpleAnnotatedMapViewController<ItemType, AnnotationViewType>, _ annotationView: AnnotationViewType) -> Void)?
open var calloutAccessoryControlTapped: ((SimpleAnnotatedMapViewController<ItemType, AnnotationViewType>, _ item: ItemType) -> Void)?
open override func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let item = annotation as? ItemType else {
return super.mapView(mapView, viewFor: annotation)
}
let annotationView: AnnotationViewType = mapView.dequeueReusableAnnotationView(withIdentifier: annotationViewIdentifier) as? AnnotationViewType
?? AnnotationViewType(annotation: item, reuseIdentifier: annotationViewIdentifier)
annotationView.annotation = item
configureAnotationView?(self, annotationView)
return annotationView
}
open override func mapView(_ mapView: MKMapView, annotationView: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
guard let item = annotationView.annotation as? ItemType else {
return
}
calloutAccessoryControlTapped?(self, item)
}
}
|
mit
|
1488e8440fd614ea0c6d8e8a8507fd61
| 47.844828 | 183 | 0.751147 | 5.217311 | false | false | false | false |
hanjoes/Breakout
|
Breakout/Breakout/CustomUIBezierPath.swift
|
1
|
1173
|
//
// CustomUIBezierPath.swift
// Breakout
//
// Created by Hanzhou Shi on 1/22/16.
// Copyright © 2016 USF. All rights reserved.
//
import UIKit
class CustomUIBezierPath: UIBezierPath {
enum CustomUIBezierPathType {
case FillType
case LineType
}
var fillColor: UIColor = UIColor.whiteColor()
var strokeColor: UIColor = UIColor.blackColor()
var pathType = CustomUIBezierPathType.FillType
var beginPoint: CGPoint?
var endPoint: CGPoint?
convenience init(rect: CGRect, color: UIColor) {
self.init()
self.init(rect: rect)
fillColor = color
}
convenience init(type: CustomUIBezierPathType, from: CGPoint, to: CGPoint) {
self.init()
pathType = type
beginPoint = from
endPoint = to
}
func draw() {
switch self.pathType {
case .FillType:
fillColor.setFill()
self.fill()
case .LineType:
self.moveToPoint(beginPoint!)
self.addLineToPoint(endPoint!)
strokeColor.setStroke()
self.stroke()
}
}
}
|
mit
|
c1892090cfdb55dee79e13aa8c600b11
| 20.703704 | 80 | 0.575085 | 4.596078 | false | false | false | false |
fespinoza/linked-ideas-osx
|
LinkedIdeas-Shared/Sources/Models/2DMath/Arrow.swift
|
1
|
2362
|
//
// ArrowPath.swift
// LinkedIdeas
//
// Created by Felipe Espinoza Castillo on 25/02/16.
// Copyright © 2016 Felipe Espinoza Dev. All rights reserved.
//
import CoreGraphics
public struct Arrow {
var point1: CGPoint
var point2: CGPoint
let arrowHeight: CGFloat = 20
let arrowWidth: CGFloat = 15
let arrowBodyWidth: CGFloat
public init(point1: CGPoint, point2: CGPoint) {
self.point1 = point1
self.point2 = point2
self.arrowBodyWidth = 5
}
public init(point1: CGPoint, point2: CGPoint, arrowBodyWidth: CGFloat = 5) {
self.point1 = point1
self.point2 = point2
self.arrowBodyWidth = arrowBodyWidth
}
private var pendant: CGFloat { return (point2.y - point1.y) / (point2.x - point1.x) }
private var sideC: CGFloat { return arrowBodyWidth / 2 }
private var sideB: CGFloat { return arrowWidth / 2 }
private var alpha: CGFloat { return atan(pendant) }
private var direction: CGFloat { return point2.x >= point1.x ? 1 : -1 }
private var point5: CGPoint {
return CGPoint(x: (point2.x - direction * cos(alpha) * arrowHeight),
y: (point2.y - direction * sin(alpha) * arrowHeight))
}
private var point3: CGPoint { return CGPoint(x: (point5.x - sideB * sin(alpha)), y: (point5.y + sideB * cos(alpha))) }
private var point4: CGPoint { return CGPoint(x: (point5.x + sideB * sin(alpha)), y: (point5.y - sideB * cos(alpha))) }
private var point6: CGPoint { return CGPoint(x: (point5.x - sideC * sin(alpha)), y: (point5.y + sideC * cos(alpha))) }
private var point7: CGPoint { return CGPoint(x: (point5.x + sideC * sin(alpha)), y: (point5.y - sideC * cos(alpha))) }
private var point8: CGPoint { return CGPoint(x: (point1.x - sideC * sin(alpha)), y: (point1.y + sideC * cos(alpha))) }
private var point9: CGPoint { return CGPoint(x: (point1.x + sideC * sin(alpha)), y: (point1.y - sideC * cos(alpha))) }
public func arrowBodyPoints() -> [CGPoint] {
return [point6, point7, point8, point9]
}
public func bezierPath() -> BezierPath {
let arrowPath = BezierPath()
arrowPath.move(to: point1)
arrowPath.line(to: point8)
arrowPath.line(to: point6)
arrowPath.line(to: point3)
arrowPath.line(to: point2)
arrowPath.line(to: point4)
arrowPath.line(to: point7)
arrowPath.line(to: point9)
arrowPath.close()
return arrowPath
}
}
|
mit
|
be4b12f3fc5e72b9a1630c34f9f97d7c
| 35.323077 | 120 | 0.664972 | 3.274619 | false | false | false | false |
Fidetro/SwiftFFDB
|
Swift-FFDBTests/SelectTest.swift
|
1
|
1375
|
//
// SelectTest.swift
// Swift-FFDBTests
//
// Created by Fidetro on 2017/10/13.
// Copyright © 2017年 Fidetro. All rights reserved.
//
import XCTest
class SelectTest: XCTestCase {
func testSelect1() {
let stmt1 = Select("*").from(Person.self).stmt
let stmt2 = "select * from Person "
if stmt1 != stmt2 {
print(stmt1)
print(stmt2)
assertionFailure()
}
}
func testSelect2() {
let stmt1 = Select("*").from(Person.self).where("name = ?").stmt
let stmt2 = "select * from Person where name = ? "
if stmt1 != stmt2 {
print(stmt1)
print(stmt2)
assertionFailure()
}
}
func testSelect3() {
let stmt1 = Select("*").from(Person.self).where("name = ?").limit("1").stmt
let stmt2 = "select * from Person where name = ? limit 1 "
if stmt1 != stmt2 {
print(stmt1)
print(stmt2)
assertionFailure()
}
}
func testSelect4() {
let stmt1 = Select("*").from(Person.self).where("name = ?").limit("1").offset("0").stmt
let stmt2 = "select * from Person where name = ? limit 1 offset 0 "
if stmt1 != stmt2 {
print(stmt1)
print(stmt2)
assertionFailure()
}
}
}
|
apache-2.0
|
96f60fea4cf43945e0f50d2298fc7be5
| 24.886792 | 95 | 0.508746 | 3.875706 | false | true | false | false |
sameertotey/LimoService
|
LimoService/LocalSearchTableViewController.swift
|
1
|
14069
|
//
// LocalSearchTableViewController.swift
// LimoService
//
// Created by Sameer Totey on 3/23/15.
// Copyright (c) 2015 Sameer Totey. All rights reserved.
//
import UIKit
import AddressBook
import AddressBookUI
import MapKit
class LocalSearchTableViewController: UIViewController, UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating, MKMapViewDelegate, CLLocationManagerDelegate, UITableViewDelegate {
// MARK: Properties
@IBOutlet weak var mapView: MKMapView!
var locationManager: CLLocationManager?
var searchResults = [MKMapItem]()
// Search controller to help us with filtering.
var searchController: UISearchController!
// Secondary search results table view.
var resultsTableController: LocationResultsTableViewController!
// text in the search bar
var searchText = ""
let whitespaceCharacterSet = NSCharacterSet.whitespaceCharacterSet()
var userLocation: CLLocation!
var searchRequest: MKLocalSearchRequest!
var localSearch: MKLocalSearch!
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
searchRequest = MKLocalSearchRequest()
searchRequest.naturalLanguageQuery = searchText
/* Are location services available on this device? */
if CLLocationManager.locationServicesEnabled(){
/* Do we have authorization to access location services? */
switch CLLocationManager.authorizationStatus(){
case .Denied:
/* No */
displayAlertWithTitle("Not Authorized",
message: "Location services are not allowed for this app")
case .NotDetermined:
/* We don't know yet, we have to ask */
locationManager = CLLocationManager()
if let manager = locationManager {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyKilometer
// Set a movement threshold for new events.
manager.distanceFilter = 500; // meters
manager.requestWhenInUseAuthorization()
}
case .Restricted:
/* Restrictions have been applied, we have no access
to location services */
displayAlertWithTitle("Restricted",
message: "Location services are not allowed for this app")
default:
showUserLocationOnMapView()
println("We have authorization to display location")
if locationManager == nil {
locationManager = CLLocationManager()
}
if let manager = locationManager {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyKilometer
// Set a movement threshold for new events.
manager.distanceFilter = 500; // meters
manager.startUpdatingLocation()
}
}
} else {
/* Location services are not enabled.
Take appropriate action: for instance, prompt the
user to enable the location services */
println("Location services are not enabled")
}
resultsTableController = LocationResultsTableViewController()
// We want to be the delegate for our filtered table so didSelectRowAtIndexPath(_:) is called from this controller.
resultsTableController.tableView.delegate = self
searchController = UISearchController(searchResultsController: resultsTableController)
searchController.searchResultsUpdater = self
searchController.searchBar.sizeToFit()
navigationItem.titleView = searchController.searchBar
searchController.delegate = self
searchController.dimsBackgroundDuringPresentation = false // default is True
searchController.hidesNavigationBarDuringPresentation = false // default is True
searchController.searchBar.delegate = self // so we can monitor text changes + others
// Search is now just presenting a view controller. As such, normal view controller
// presentation semantics apply. Namely that presentation will walk up the view controller
// hierarchy until it finds the root view controller or one that defines a presentation context.
definesPresentationContext = true
// Do any additional setup after loading the view.
// let saveBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Save, target: self, action: "saveLocation")
// navigationItem.rightBarButtonItem = saveBarButtonItem
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
searchController.searchBar.text = searchText
searchController.active = true
searchController.searchBar.becomeFirstResponder()
if searchText != "" {
performLocalSearch(searchText)
}
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
locationManager?.stopUpdatingLocation()
}
//destroy the location manager
deinit {
locationManager?.delegate = nil
locationManager = nil
}
// MARK: UISearchBarDelegate
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
// MARK: UISearchControllerDelegate
func presentSearchController(searchController: UISearchController) {
// NSLog(__FUNCTION__)
}
func willPresentSearchController(searchController: UISearchController) {
// NSLog(__FUNCTION__)
}
func didPresentSearchController(searchController: UISearchController) {
// NSLog(__FUNCTION__)
}
func willDismissSearchController(searchController: UISearchController) {
// NSLog(__FUNCTION__)
}
func didDismissSearchController(searchController: UISearchController) {
// NSLog(__FUNCTION__)
}
// MARK: UISearchResultsUpdating
func updateSearchResultsForSearchController(searchController: UISearchController) {
// Update the filtered array based on the search text.
// Strip out all the leading and trailing spaces.
let whitespaceCharacterSet = NSCharacterSet.whitespaceCharacterSet()
let strippedString = searchController.searchBar.text.stringByTrimmingCharactersInSet(whitespaceCharacterSet)
searchText = strippedString
println("inside update search results for search controller: \(searchText)")
let searchItems = strippedString.componentsSeparatedByString(" ") as [String]
// cancel previous in flight search
localSearch?.cancel()
if count(strippedString) >= 3 {
// add minimal delay to search to avoid searching for something outdated
cancelDelayed("search")
delayed(0.1, name: "search") {
self.performLocalSearch(strippedString)
}
} // else do nothing
}
typealias Closure = ()->()
var closures = [String: Closure]()
func delayed(delay: Double, name: String, closure: Closure) {
// store the closure to execute in the closures dictionary
closures[name] = closure
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))),
dispatch_get_main_queue()) {
if let closure = self.closures[name] {
closure()
self.closures[name] = nil
}
}
}
func cancelDelayed(name: String) {
closures[name] = nil
}
func performLocalSearch(searchString: NSString) {
if userLocation != nil {
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = searchString as String
let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
request.region = MKCoordinateRegion( center: userLocation.coordinate, span: span)
localSearch = MKLocalSearch(request: request)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
localSearch.startWithCompletionHandler{
(response: MKLocalSearchResponse!, error: NSError!) in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if error == nil {
var placemarks = [CLPlacemark]()
for item in response.mapItems as! [MKMapItem]{
println("Item name = \(item.name)")
println("Item phone number = \(item.phoneNumber)")
println("Item url = \(item.url)")
println("Item location = \(item.placemark.location)")
placemarks.append(item.placemark)
}
self.mapView.removeAnnotations(self.mapView.annotations)
// this seems to work here, but we need to get custom annotations so that we can provide more information
self.mapView.addAnnotations(placemarks)
self.mapView.showAnnotations(self.mapView.annotations, animated: false)
self.searchResults = response.mapItems as! [MKMapItem]
// Hand over the filtered results to our search results table.
println("received \(placemarks.count) results")
let resultsController = self.searchController.searchResultsController as! LocationResultsTableViewController
resultsController.possibleMatches = placemarks
resultsController.searchText = self.searchText
resultsController.tableView.reloadData()
} else {
println("Received error \(error) for search \(searchString)")
}
}
}
}
// MARK: - MapView delegate
func mapView(mapView: MKMapView!, didFailToLocateUserWithError error: NSError!) {
displayAlertWithTitle("Failed", message: "Could not get the user's location")
}
func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) {
println("Location managed did update the user location: \(userLocation)")
}
// MARK: - LocationManagerDelegate
func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!){
println("Latitude = \(newLocation.coordinate.latitude)")
println("Longitude = \(newLocation.coordinate.longitude)")
self.userLocation = newLocation
if searchText != "" {
performLocalSearch(searchText)
}
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!){
println("Location manager failed with error = \(error)")
}
/* The authorization status of the user has changed, we need to react
to that so that if she has authorized our app to to view her location,
we will accordingly attempt to do so */
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus){
print("The authorization status of location services is changed to: ")
switch CLLocationManager.authorizationStatus(){
case .Denied:
println("Denied")
case .NotDetermined:
println("Not determined")
case .Restricted:
println("Restricted")
default:
showUserLocationOnMapView()
println("Now you have the authorization for location services.")
manager.startUpdatingLocation()
}
}
// MARK: - Helpers
/* Just a little method to help us display alert dialogs to the user */
func displayAlertWithTitle(title: String, message: String){
let controller = UIAlertController(title: title, message: message, preferredStyle: .Alert)
controller.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(controller, animated: true, completion: nil)
}
/* We will call this method when we are sure that the user has given us access to her location */
func showUserLocationOnMapView(){
mapView.showsUserLocation = true
mapView.userTrackingMode = .Follow
}
// MARK: - Table View Delegate
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// Check to see which table view cell was selected.
let attributedString = resultsTableController.attributedAddressStringAtIndexPath(indexPath)
let neededSize = attributedString.size()
return ceil(neededSize.height) + 20
}
// We use this to be the tableview delegate of the search controller so that we can push the map view form this controller and not the results table controller, which is presented by this controller.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Check to see which table view cell was selected.
let selectedPlacemark = resultsTableController.possibleMatches[indexPath.row]
// Set up the detail view controller to show.
let mapViewController = LocationMapViewController.forPlacemark(selectedPlacemark)
// Note: Should not be necessary but current iOS 8.0 bug requires it.
tableView.deselectRowAtIndexPath(tableView.indexPathForSelectedRow()!, animated: false)
navigationController!.pushViewController(mapViewController, animated: true)
}
}
|
mit
|
f6430fd2dc94cf90fb53c9f710d5356f
| 42.156442 | 203 | 0.642761 | 6.176032 | false | false | false | false |
benlangmuir/swift
|
test/SILOptimizer/stack_promotion_2_modules.swift
|
7
|
1976
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -parse-as-library -emit-module -emit-module-path=%t/Module.swiftmodule -module-name=Module -DMODULE %s -O -emit-sil -o %t/module.sil
// RUN: %target-swift-frontend -module-name=main -DMAIN %s -I%t -O -emit-sil | %FileCheck %s
// REQUIRES: swift_stdlib_no_asserts,optimized_stdlib
// REQUIRES: swift_in_compiler
#if MODULE
public struct Foo: Equatable {
@usableFromInline var optionA: Bool
@usableFromInline var optionB: Optional<Int>
public typealias ArrayLiteralElement = FooElement
public struct FooElement: Equatable {
@usableFromInline enum Backing: Equatable {
case a
case b(Int)
}
@usableFromInline var backing: Backing
@inlinable internal init(backing: Backing) {
self.backing = backing
}
public static let optionA = FooElement(backing: .a)
@inlinable
public static func getOptionA() -> FooElement {
return FooElement(backing: .a)
}
@inlinable
public static func optionB(_ x: Int) -> FooElement {
return FooElement(backing: .b(x))
}
}
}
extension Foo: ExpressibleByArrayLiteral {
@inlinable
@inline(never)
public init(arrayLiteral things: FooElement...) {
self.optionA = false
self.optionB = nil
for thing in things {
switch thing.backing {
case .a:
self.optionA = true
case .b(let x):
self.optionB = x
}
}
}
}
#endif
#if MAIN
import Module
// Check if the array literal can be stack promoted.
// CHECK-LABEL: sil @$s4main6testit6Module3FooVyF
// CHECK: alloc_ref{{.*}} [stack] [tail_elems $Foo.FooElement
// CHECK: } // end sil function '$s4main6testit6Module3FooVyF'
public func testit() -> Foo {
return [.optionA, .optionB(0xbeef), .optionA]
}
#endif
|
apache-2.0
|
f6b721e697cd9ec56b60371d51382c91
| 24.333333 | 163 | 0.6083 | 3.882122 | false | false | false | false |
sameertotey/LimoService
|
ModalPresentationTransitionVendor.swift
|
1
|
1940
|
//
// ModalPresentationTransitionVendor.swift
// BlackJack
//
// Created by Sameer Totey on 2/4/15.
// Copyright (c) 2015 Sameer Totey. All rights reserved.
//
import UIKit
class ModalPresentationTransitionVendor: NSObject, UIViewControllerTransitioningDelegate {
func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController!, sourceViewController source: UIViewController) -> UIPresentationController? {
let presentationController: UIPresentationController?
if source is MainMenuViewController {
presentationController = nil
} else {
presentationController = MenuPresentationController(presentedViewController: presented, presentingViewController: source)
}
return presentationController
}
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animator: BaseTransitionAnimator
if source is MainMenuViewController {
animator = FromMainMenuTransitionAnimator()
animator.finalScale = 0.8
} else {
animator = ModalTransitionAnimator()
animator.finalScale = 0.9
}
animator.duration = 0.65
animator.presenting = true
return animator
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animator: BaseTransitionAnimator
if dismissed is MainMenuViewController {
animator = ModalTransitionAnimator()
} else {
animator = FromMainMenuTransitionAnimator()
}
animator.duration = 0.35
animator.presenting = false
return animator
}
}
|
mit
|
26df4342ed20c9f6979c040b656f8016
| 37.8 | 220 | 0.710309 | 6.736111 | false | false | false | false |
accepton/accepton-apple
|
Pod/Classes/AcceptOnUIMachine/Drivers/Paypal.swift
|
1
|
8118
|
import Foundation
import UIKit
import PaypalPrivate
@objc class AcceptOnUIMachinePayPalDriver : AcceptOnUIMachinePaymentDriver, PayPalPaymentDelegate {
//Present using a specially created view controller applied to the root window
var _presentingViewController: UIViewController!
var presentingViewController: UIViewController! {
get {
if (_presentingViewController == nil) {
_presentingViewController = UIViewController()
let rv = UIApplication.sharedApplication().windows.first
if rv == nil {
NSException(name:"AcceptOnUIMachinePaypalDriver", reason: "Tried to get the UIApplication.sharedApplication().windows.first to display the paypal view controller off of but this did not exist", userInfo: nil).raise()
}
rv!.addSubview(_presentingViewController.view)
_presentingViewController.view.bounds = UIScreen.mainScreen().bounds
}
return _presentingViewController
}
}
override class var name: String {
return "paypal"
}
var ppvc: PayPalPaymentViewController!
enum State {
case NotStarted //Initialized
case WaitingForPaypalToSendToken //Showing the PayPal form, user entering info or it's transacting
case CompletingTransactionWithAccepton //Now we are completing the transaction with accepton
case TransactionWithAcceptonDidFail //stateInfo is the error message
case TransactionWithAcceptonDidSucceed //stateInfo is the charge information
case UIDidFinish
}
var state: State = .NotStarted {
didSet {
stateInfo = nil
}
}
var stateInfo: Any?
override func beginTransaction() {
self.state = .WaitingForPaypalToSendToken
//TODO: retrieve key from accepton API
if delegate.api.isProduction {
PayPalMobile.initializeWithClientIdsForEnvironments([PayPalEnvironmentProduction:self.formOptions.paymentMethods.paypalRestClientId!])
PayPalMobile.preconnectWithEnvironment(PayPalEnvironmentProduction)
} else {
PayPalMobile.initializeWithClientIdsForEnvironments([PayPalEnvironmentSandbox:self.formOptions.paymentMethods.paypalRestClientId!])
PayPalMobile.preconnectWithEnvironment(PayPalEnvironmentSandbox)
}
let _config = PayPalConfiguration()
_config.acceptCreditCards = false
_config.payPalShippingAddressOption = PayPalShippingAddressOption.None
let pp = PayPalPayment()
pp.amount = NSDecimalNumber(double: Double(formOptions.amountInCents) / 100.0)
pp.currencyCode = "USD"
pp.shortDescription = formOptions.itemDescription
pp.intent = PayPalPaymentIntent.Sale
ppvc = PayPalPaymentViewController(payment: pp, configuration: _config, delegate: self)
presentingViewController.presentViewController(ppvc, animated: true, completion: nil)
}
func payPalPaymentDidCancel(paymentViewController: PayPalPaymentViewController!) {
handlePaypalUICompletion()
}
func payPalPaymentViewController(paymentViewController: PayPalPaymentViewController!, didCompletePayment completedPayment: PayPalPayment!) {
handlePaypalUICompletion()
}
//We don't necessarily care whether PayPal thinks it completed or failed. We rely on the AcceptOn transaction
//state
func handlePaypalUICompletion() {
if self.state == .UIDidFinish { return }
switch self.state {
case .TransactionWithAcceptonDidSucceed:
self.delegate.transactionDidSucceedForDriver(self, withChargeRes: stateInfo as! [String:AnyObject])
case .TransactionWithAcceptonDidFail:
self.delegate.transactionDidFailForDriver(self, withMessage: stateInfo as! String)
case .WaitingForPaypalToSendToken:
self.delegate.transactionDidCancelForDriver(self)
case .CompletingTransactionWithAccepton:
//Do not allow the UI to close at this point, we can't stop the transaction
return
default:
return
}
dispatch_async(dispatch_get_main_queue()) {
self.state = .UIDidFinish
self._presentingViewController.dismissViewControllerAnimated(true) { [weak self] in
self?._presentingViewController.view.removeFromSuperview()
self?._presentingViewController.removeFromParentViewController()
self?._presentingViewController = nil
}
}
}
func payPalPaymentViewController(paymentViewController: PayPalPaymentViewController!, willCompletePayment completedPayment: PayPalPayment!, completionBlock: PayPalPaymentDelegateCompletionBlock!) {
dispatch_async(dispatch_get_main_queue()) {
if self.state != .WaitingForPaypalToSendToken { return }
let confirmation = completedPayment.confirmation
//Parse response from paypal response
guard let responseType = confirmation["response_type"] as? String else {
self.delegate.transactionDidFailForDriver(self, withMessage: "Could not get response_type from confirmation")
return
}
guard responseType == "payment" else {
self.delegate.transactionDidFailForDriver(self, withMessage: "Response type from PayPal was not a payment")
return
}
guard let response = confirmation["response"] as? [String:AnyObject] else {
self.delegate.transactionDidFailForDriver(self, withMessage: "Could not decode response from paypal's confirmation")
return
}
guard let tokenId = response["id"] as? String else {
self.delegate.transactionDidFailForDriver(self, withMessage: "Could not decode token id from paypal's response")
return
}
self.nonceTokens = ["paypal_payment_id": tokenId]
self.state = .CompletingTransactionWithAccepton
self.readyToCompleteTransaction(completionBlock)
}
}
//Currently, PayPal verifies using a different endpoint then the rest of the tokenizers
override func readyToCompleteTransaction(userInfo: Any?=nil) {
if nonceTokens.count > 0 {
let chargeInfo = AcceptOnAPIChargeInfo(rawCardInfo: self.formOptions.creditCardParams, cardTokens: self.nonceTokens, email: email, metadata: self.metadata)
self.delegate.api.verifyPaypalWithTransactionId(self.formOptions.token.id, andChargeInfo: chargeInfo) { chargeRes, err in
if let err = err {
self.readyToCompleteTransactionDidFail(userInfo, withMessage: err.localizedDescription)
return
}
self.readyToCompleteTransactionDidSucceed(userInfo, withChargeRes: chargeRes!)
}
} else {
self.readyToCompleteTransactionDidFail(userInfo, withMessage: "Could not connect to any payment processing services")
}
}
override func readyToCompleteTransactionDidFail(userInfo: Any?, withMessage message: String) {
self.state = .TransactionWithAcceptonDidFail
self.stateInfo = "Could not complete the payment at this time"
let completion = userInfo as! PayPalPaymentDelegateCompletionBlock
completion()
}
override func readyToCompleteTransactionDidSucceed(userInfo: Any?, withChargeRes chargeRes: [String : AnyObject]) {
self.state = .TransactionWithAcceptonDidSucceed
self.stateInfo = chargeRes
let completion = userInfo as! PayPalPaymentDelegateCompletionBlock
completion()
}
}
|
mit
|
6a549c412bc8166a375a7c5c34c89cf0
| 46.473684 | 236 | 0.659522 | 5.6375 | false | false | false | false |
devpunk/cartesian
|
cartesian/View/DrawProject/Font/VDrawProjectFont.swift
|
1
|
7899
|
import UIKit
class VDrawProjectFont:UIView, UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
{
private let model:MDrawProjectMenuLabelsFont
private let indexPath:IndexPath?
private weak var controller:CDrawProject!
private weak var collectionView:VCollection!
private(set) weak var viewBar:VDrawProjectFontBar!
private weak var blurContainer:UIView!
private weak var layoutBaseTop:NSLayoutConstraint!
private weak var delegate:MDrawProjectFontDelegate?
private let kBaseHeight:CGFloat = 300
private let kBarHeight:CGFloat = 50
private let kAnimationDuration:TimeInterval = 0.3
private let kCellHeight:CGFloat = 95
init(
controller:CDrawProject,
delegate:MDrawProjectFontDelegate)
{
if let model:MDrawProjectMenuLabelsFont = delegate.fontModel()
{
self.model = model
indexPath = model.selectedIndex()
}
else
{
model = MDrawProjectMenuLabelsFont()
if let stringSelected:String = delegate.fontCurrent()
{
indexPath = model.indexForName(name:stringSelected)
}
else
{
indexPath = nil
}
}
super.init(frame:CGRect.zero)
clipsToBounds = true
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = UIColor.clear
self.controller = controller
self.delegate = delegate
let blur:VBlur = VBlur.dark()
let blurContainer:UIView = UIView()
blurContainer.isUserInteractionEnabled = false
blurContainer.clipsToBounds = true
blurContainer.translatesAutoresizingMaskIntoConstraints = false
blurContainer.alpha = 0
self.blurContainer = blurContainer
let button:UIButton = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor.clear
button.addTarget(
self,
action:#selector(actionClose(sender:)),
for:UIControlEvents.touchUpInside)
let baseView:UIView = UIView()
baseView.translatesAutoresizingMaskIntoConstraints = false
baseView.clipsToBounds = true
baseView.backgroundColor = UIColor.white
let viewBar:VDrawProjectFontBar = VDrawProjectFontBar(
controller:controller)
self.viewBar = viewBar
let collectionView:VCollection = VCollection()
collectionView.alwaysBounceVertical = true
collectionView.delegate = self
collectionView.dataSource = self
collectionView.registerCell(cell:VDrawProjectFontCell.self)
self.collectionView = collectionView
baseView.addSubview(viewBar)
baseView.addSubview(collectionView)
blurContainer.addSubview(blur)
addSubview(blurContainer)
addSubview(button)
addSubview(baseView)
NSLayoutConstraint.equals(
view:blur,
toView:blurContainer)
NSLayoutConstraint.equals(
view:blurContainer,
toView:self)
NSLayoutConstraint.equals(
view:button,
toView:self)
layoutBaseTop = NSLayoutConstraint.topToBottom(
view:baseView,
toView:self)
NSLayoutConstraint.height(
view:baseView,
constant:kBaseHeight)
NSLayoutConstraint.equalsHorizontal(
view:baseView,
toView:self)
NSLayoutConstraint.topToTop(
view:viewBar,
toView:baseView)
NSLayoutConstraint.height(
view:viewBar,
constant:kBarHeight)
NSLayoutConstraint.equalsHorizontal(
view:viewBar,
toView:baseView)
NSLayoutConstraint.topToBottom(
view:collectionView,
toView:viewBar)
NSLayoutConstraint.bottomToBottom(
view:collectionView,
toView:baseView)
NSLayoutConstraint.equalsHorizontal(
view:collectionView,
toView:baseView)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
collectionView.collectionViewLayout.invalidateLayout()
super.layoutSubviews()
}
//MARK: actions
func actionClose(sender button:UIButton)
{
animateClose()
}
//MARK: private
private func modelAtIndex(index:IndexPath) -> MDrawProjectMenuLabelsFontItem
{
let item:MDrawProjectMenuLabelsFontItem = model.items[index.item]
return item
}
private func animateClose()
{
layoutBaseTop.constant = 0
UIView.animate(
withDuration:kAnimationDuration,
animations:
{ [weak self] in
self?.alpha = 0
self?.layoutIfNeeded()
})
{ [weak self] (done:Bool) in
self?.removeFromSuperview()
}
}
//MARK: public
func fontSelected()
{
animateClose()
guard
let item:MDrawProjectMenuLabelsFontItem = model.currentFont
else
{
return
}
delegate?.fontSelected(model:item)
}
func animateShow()
{
layoutBaseTop.constant = -kBaseHeight
UIView.animate(
withDuration:kAnimationDuration,
animations:
{ [weak self] in
self?.blurContainer.alpha = 0.95
self?.layoutIfNeeded()
})
{ [weak self] (done:Bool) in
guard
let indexPath:IndexPath = self?.indexPath
else
{
return
}
self?.collectionView.selectItem(
at:indexPath,
animated:true,
scrollPosition:UICollectionViewScrollPosition.top)
}
}
//MARK: collectionView delegate
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
{
let width:CGFloat = collectionView.bounds.maxX
let size:CGSize = CGSize(width:width, height:kCellHeight)
return size
}
func numberOfSections(in collectionView:UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
let count:Int = model.items.count
return count
}
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let item:MDrawProjectMenuLabelsFontItem = modelAtIndex(index:indexPath)
let cell:VDrawProjectFontCell = collectionView.dequeueReusableCell(
withReuseIdentifier:
VDrawProjectFontCell.reusableIdentifier,
for:indexPath) as! VDrawProjectFontCell
cell.config(
controller:controller,
model:item)
return cell
}
func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath)
{
let item:MDrawProjectMenuLabelsFontItem = modelAtIndex(index:indexPath)
model.currentFont = item
collectionView.scrollToItem(
at:indexPath,
at:UICollectionViewScrollPosition.top,
animated:true)
}
}
|
mit
|
d39c06469a91bc3aa91a7f122802df37
| 28.040441 | 155 | 0.594379 | 6.006844 | false | false | false | false |
therealglazou/quaxe-for-swift
|
quaxe/core/CustomEvent.swift
|
1
|
1083
|
/**
* Quaxe for Swift
*
* Copyright 2016-2017 Disruptive Innovations
*
* Original author:
* Daniel Glazman <[email protected]>
*
* Contributors:
*
*/
/*
* https://dom.spec.whatwg.org/#interface-customevent
*
* status: done
*/
public class CustomEvent: Event, pCustomEvent {
internal var mDetail: Any
/*
* https://dom.spec.whatwg.org/#dom-customevent-detail
*/
public var detail: Any { return mDetail }
/*
* https://dom.spec.whatwg.org/#dom-customevent-initcustomevent
*/
public func initCustomEvent(_ type: DOMString, _ bubbles: Bool, _ cancelable: Bool, _ detail: Any) -> Void {
if !hasFlag(Event.DISPATCH_FLAG) {
super.initEvent(type, bubbles, cancelable)
mDetail = detail
}
}
public required init(_ aType: DOMString, _ aEventInitDict: Dictionary<String, Any>,
_ aIsTrusted: Bool = false) {
if let detail = aEventInitDict["detail"] {
self.mDetail = detail
}
else {
self.mDetail = 0
}
super.init(aType, aEventInitDict, false)
}
}
|
mpl-2.0
|
5e8c88a15c5b503fc69ee9f8483674e4
| 22.042553 | 110 | 0.638042 | 3.527687 | false | false | false | false |
isnine/HutHelper-Open
|
HutHelper/SwiftApp/User/UserViewController.swift
|
1
|
15297
|
//
// UserController.swift
// HutHelperSwift
//
// Created by 张驰 on 2020/1/12.
// Copyright © 2020 张驰. All rights reserved.
//
import UIKit
import SnapKit
import RxCocoa
import RxSwift
class UserController: UIViewController {
var classesData: [String: Any]?
var classesDatas = [ClassModel]()
let disposeBag = DisposeBag()
var imgPricker: UIImagePickerController!
var classSelect = ClassModel()
// viewModel层
lazy var viewModel: UseInfoViewModel = {
let viewmodel = UseInfoViewModel()
return viewmodel
}()
// 左边返回
private lazy var leftBarButton: UIButton = {
let btn = UIButton.init(type: .custom)
btn.frame = CGRect(x: -5, y: 0, width: 20, height: 30)
btn.setImage(UIImage(named: "ico_menu_back"), for: .normal)
btn.rx.tap.subscribe(onNext: {[weak self] in
self?.navigationController?.popViewController(animated: true)
}).disposed(by: disposeBag)
return btn
}()
// 主体tableView
lazy var tableView: UITableView = {
let tableview = UITableView(frame: self.view.bounds)
tableview.tag = 2001
tableview.separatorStyle = .none
tableview.delegate = self
tableview.dataSource = self
tableview.backgroundColor = UIColor.init(r: 247, g: 247, b: 247)
tableview.register(UINib(nibName: "UseInfoCell", bundle: nil), forCellReuseIdentifier: "UseInfoCell")
tableview.register(UseHeadCell.self, forCellReuseIdentifier: "UseHeadCell")
return tableview
}()
// 班级选择picker
lazy var pickerView: UIPickerView = {
let picker = UIPickerView(frame: CGRect(x: 0, y: screenHeight+50, width: screenWidth, height: screenHeight/3))
picker.delegate = self
picker.dataSource = self
picker.selectRow(0, inComponent: 0, animated: true)
picker.selectRow(0, inComponent: 1, animated: true)
picker.backgroundColor = .white
return picker
}()
// picker阴影背景
lazy var backView: UIView = {
let vi = UIView(frame: self.view.bounds)
vi.backgroundColor = UIColor.init(r: 33, g: 33, b: 33)
vi.alpha = 0.5
vi.isHidden = true
let tap = UITapGestureRecognizer()
tap.addTarget(self, action: #selector(hiddenPicker))
vi.addGestureRecognizer(tap)
return vi
}()
//班级选择按钮
lazy var selectBtn: UIButton = {
let btn = UIButton(frame: CGRect(x: 0, y: screenHeight, width: screenWidth, height: 50))
btn.backgroundColor = UIColor.init(r: 238, g: 238, b: 238)
btn.setTitleColor(.cyan, for: .normal)
btn.setTitle("确认班级选择", for: .normal)
btn.rx.tap.subscribe(onNext: {[weak self] in
let component = self!.pickerView.selectedRow(inComponent: 0)
let row = self!.pickerView.selectedRow(inComponent: 1)
let className = self!.viewModel.classesDatas[component].classes[row]
let depName = self!.viewModel.classesDatas[component].depName
self?.viewModel.alterUseInfo(type: .classes(className), callback: { (isSuccess) in
guard isSuccess else {return}
changeUserInfo(name: "dep_name", value: depName)
changeUserInfo(name: "class_name", value: className)
self!.hiddenPicker()
self!.tableView.reloadData()
})
}).disposed(by: disposeBag)
return btn
}()
@objc func hiddenPicker() {
UIView.animate(withDuration: 0.25, animations: {
self.backView.alpha = 0.5
//self.backView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.pickerView.frame = CGRect(x: 0, y: screenHeight+50, width: screenWidth, height: screenHeight/3)
self.selectBtn.frame = CGRect(x: 0, y: screenHeight, width: screenWidth, height: 50)
}) { (_) in
self.backView.isHidden = true
}
}
func showPicker() {
self.backView.isHidden = false
//self.backView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
UIView.animate(withDuration: 0.25, animations: {
self.backView.alpha = 0.5
//self.backView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.pickerView.frame = CGRect(x: 0, y: 2*screenHeight/3, width: screenWidth, height: screenHeight/3)
self.selectBtn.frame = CGRect(x: 0, y: 2*screenHeight/3-50, width: screenWidth, height: 50)
}) { (_) in
}
self.pickerView.reloadAllComponents()
}
override func viewDidLoad() {
super.viewDidLoad()
configUI()
}
func configUI() {
self.view.backgroundColor = .white
self.navigation.item.title = "个人信息"
self.navigation.item.leftBarButtonItem = UIBarButtonItem.init(customView: leftBarButton)
self.navigation.bar.isShadowHidden = true
self.view.addSubview(tableView)
self.view.addSubview(self.backView)
self.view.addSubview(self.pickerView)
self.view.addSubview(selectBtn)
}
func getUseHeadImg() {
print("头像更换")
let actionSheet = UIAlertController(title: "更改头像", message: "请选择图像来源", preferredStyle: .actionSheet)
let alterUserImg = UIAlertAction(title: "相册选择", style: .default, handler: {(_: UIAlertAction) -> Void in
print("拍照继续更改头像中..")
self.imgPricker = UIImagePickerController()
self.imgPricker.delegate = self
self.imgPricker.allowsEditing = true
self.imgPricker.sourceType = .photoLibrary
self.imgPricker.navigationBar.barTintColor = UIColor.gray
self.imgPricker.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
self.imgPricker.navigationBar.tintColor = UIColor.white
self.present(self.imgPricker, animated: true, completion: nil)
})
let alterUserImgTake = UIAlertAction(title: "拍照选择", style: .default, handler: {(_: UIAlertAction) -> Void in
print("继续更改头像中..")
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
self.imgPricker = UIImagePickerController()
self.imgPricker.delegate = self
self.imgPricker.allowsEditing = true
self.imgPricker.sourceType = .camera
self.imgPricker.cameraDevice = UIImagePickerController.CameraDevice.rear
self.imgPricker.showsCameraControls = true
self.imgPricker.navigationBar.barTintColor = UIColor.gray
self.imgPricker.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
self.imgPricker.navigationBar.tintColor = UIColor.white
self.present(self.imgPricker, animated: true, completion: nil)
}
})
let cancel = UIAlertAction(title: "取消", style: .cancel, handler: {(_: UIAlertAction) -> Void in print("取消更改头像")})
actionSheet.addAction(cancel)
actionSheet.addAction(alterUserImg)
actionSheet.addAction(alterUserImgTake)
self.present(actionSheet, animated: true) {
print("正在更改")
}
}
}
extension UserController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cellHead = tableView.dequeueReusableCell(withIdentifier: "UseHeadCell", for: indexPath) as! UseHeadCell
cellHead.updateUI(imageUrl: imageUrl+user.head_pic_thumb)
return cellHead
}
let cell = tableView.dequeueReusableCell(withIdentifier: "UseInfoCell", for: indexPath) as! UseInfoCell
switch indexPath.section {
case 1:
cell.updateUI(headlab: "昵称", infolab: user.username)
case 2:
cell.updateUI(headlab: "签名", infolab: user.bio)
case 3:
cell.updateUI(headlab: "密码", infolab: "点击修改")
case 4:
cell.updateUI(headlab: "学院", infolab: user.dep_name)
case 5:
cell.updateUI(headlab: "班级", infolab: user.class_name)
case 6:
cell.updateUI(headlab: "QQ", infolab: "通过QQ联系他人")
case 7:
cell.updateUI(headlab: "姓名", infolab: user.TrueName)
case 8:
cell.updateUI(headlab: "性别", infolab: user.active)
case 9:
cell.updateUI(headlab: "学号", infolab: user.studentKH)
default:
break
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return 65.fit
}
return 45.fit
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// let appDelegate = UIApplication.shared.delegate as? AppDelegate
// [tempAppDelegate.LeftSlideVC closeLeftView];
// let leftVC = UIApplication.shared.windows[0].rootViewController as! LeftSlideViewController
// leftVC.closeLeftView()
// let appDelegate = UIApplication.shared.delegate as! AppDelegate
switch indexPath.section {
case 0:
self.getUseHeadImg()
case 1:
self.alterMethod(name: "修改昵称") { (value) in
let cell = tableView.cellForRow(at: indexPath) as! UseInfoCell
self.viewModel.alterUseInfo(type: .username(value)) { (isSuccess) in
guard isSuccess else { return }
cell.infoLab.text = value
changeUserInfo(name: "username", value: value)
}
}
case 2:
self.alterMethod(name: "修改签名") { (value) in
let cell = tableView.cellForRow(at: indexPath) as! UseInfoCell
self.viewModel.alterUseInfo(type: .bio(value)) { (isSuccess) in
guard isSuccess else { return }
cell.infoLab.text = value
changeUserInfo(name: "bio", value: value)
}
}
case 3:
print("改密码请联系管理员")
case 4:
guard viewModel.classesDatas.isEmpty else {
self.showPicker();return }
viewModel.getAllClassesRequst { self.showPicker() }
case 5 :
guard viewModel.classesDatas.isEmpty else {
self.showPicker();return }
viewModel.getAllClassesRequst { self.showPicker() }
case 6:
print("qq还不能")
default:
break
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let vi = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 1))
vi.backgroundColor = UIColor.init(r: 223, g: 223, b: 223)
return vi
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 || section == 1 || section == 7 {
return 10
}
return 1
}
}
extension UserController {
func alterMethod(name: String, callback: @escaping(_ result: String) -> Void) {
let alert = UIAlertController.init(title: name, message: "请输入", preferredStyle: .alert)
let yesAction = UIAlertAction.init(title: "确定", style: .default) { (_) in
callback((alert.textFields?.first?.text!)!)
}
let noAction = UIAlertAction.init(title: "取消", style: .default) { (no) in
print("取消", no.style)
}
alert.addAction(noAction)
alert.addAction(yesAction)
alert.addTextField { (_) in
}
self.present(alert, animated: true, completion: nil)
}
}
extension UserController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if viewModel.classesDatas.isEmpty {
return 0
} else {
if component == 0 {
return viewModel.classesDatas.count
}
let row = pickerView.selectedRow(inComponent: 0)
let classCurrnt = viewModel.classesDatas[row]
self.classSelect = classCurrnt
return classCurrnt.classes.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int,
forComponent component: Int) -> String? {
if component == 0 {
return viewModel.classesDatas[row].depName
}
let pRow = pickerView.selectedRow(inComponent: 0)
return viewModel.classesDatas[pRow].classes[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int,
inComponent component: Int) {
if component == 0 {
self.pickerView.reloadComponent(1)
}
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int,
forComponent component: Int, reusing view: UIView?) -> UIView {
var pickerLabel = view as? UILabel
if pickerLabel == nil {
pickerLabel = UILabel()
pickerLabel?.font = UIFont.systemFont(ofSize: 14)
pickerLabel?.textAlignment = .center
}
if component == 0 {
pickerLabel?.text = viewModel.classesDatas[row].depName
} else {
pickerLabel?.text = classSelect.classes[row]
}
return pickerLabel!
}
}
extension UserController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
let img = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
let HelperHUD = MBProgressHUD.showAdded(to: self.view, animated: true)
HelperHUD.label.text = "上传中"
viewModel.alterUseHeadImg(image: img) { (result) in
guard let value = result else { return }
changeUserInfo(name: "head_pic_thumb", value: value)
self.tableView.reloadData()
HelperHUD.hide(animated: true)
}
self.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
}
|
lgpl-2.1
|
21c24b264ee402471ecfaafecc570b27
| 38.598945 | 143 | 0.610275 | 4.574215 | false | false | false | false |
blumareks/2016WoW
|
LabVisual/Carthage/Checkouts/Starscream/Source/WebSocket.swift
|
3
|
36237
|
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
// Copyright (c) 2014-2015 Dalton Cherry.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import CoreFoundation
import Security
public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification"
public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification"
public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName"
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: NSError?)
func websocketDidReceiveMessage(socket: WebSocket, text: String)
func websocketDidReceiveData(socket: WebSocket, data: NSData)
}
public protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(socket: WebSocket)
}
public class WebSocket: NSObject, NSStreamDelegate {
enum OpCode: UInt8 {
case ContinueFrame = 0x0
case TextFrame = 0x1
case BinaryFrame = 0x2
// 3-7 are reserved.
case ConnectionClose = 0x8
case Ping = 0x9
case Pong = 0xA
// B-F reserved.
}
public enum CloseCode: UInt16 {
case Normal = 1000
case GoingAway = 1001
case ProtocolError = 1002
case ProtocolUnhandledType = 1003
// 1004 reserved.
case NoStatusReceived = 1005
// 1006 reserved.
case Encoding = 1007
case PolicyViolated = 1008
case MessageTooBig = 1009
}
public static let ErrorDomain = "WebSocket"
enum InternalErrorCode: UInt16 {
// 0-999 WebSocket status codes not used
case OutputStreamWriteError = 1
}
/// Where the callback is executed. It defaults to the main UI thread queue.
public var callbackQueue = dispatch_get_main_queue()
var optionalProtocols : [String]?
// MARK: - Constants
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 4096
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
let httpSwitchProtocolCode = 101
let supportedSSLSchemes = ["wss", "https"]
class WSResponse {
var isFin = false
var code: OpCode = .ContinueFrame
var bytesLeft = 0
var frameCount = 0
var buffer: NSMutableData?
}
// MARK: - Delegates
/// Responds to callback about new messages coming in over the WebSocket
/// and also connection/disconnect messages.
public weak var delegate: WebSocketDelegate?
/// Recives a callback for each pong message recived.
public weak var pongDelegate: WebSocketPongDelegate?
// MARK: - Block based API.
public var onConnect: ((Void) -> Void)?
public var onDisconnect: ((NSError?) -> Void)?
public var onText: ((String) -> Void)?
public var onData: ((NSData) -> Void)?
public var onPong: ((Void) -> Void)?
public var headers = [String: String]()
public var voipEnabled = false
public var selfSignedSSL = false
public var security: SSLSecurity?
public var enabledSSLCipherSuites: [SSLCipherSuite]?
public var origin: String?
public var timeout = 5
public var isConnected :Bool {
return connected
}
public var currentURL: NSURL { return url }
// MARK: - Private
private var url: NSURL
private var inputStream: NSInputStream?
private var outputStream: NSOutputStream?
private var connected = false
private var isConnecting = false
private var writeQueue = NSOperationQueue()
private var readStack = [WSResponse]()
private var inputQueue = [NSData]()
private var fragBuffer: NSData?
private var certValidated = false
private var didDisconnect = false
private var readyToWrite = false
private let mutex = NSLock()
private let notificationCenter = NSNotificationCenter.defaultCenter()
private var canDispatch: Bool {
mutex.lock()
let canWork = readyToWrite
mutex.unlock()
return canWork
}
/// The shared processing queue used for all WebSocket.
private static let sharedWorkQueue = dispatch_queue_create("com.vluxe.starscream.websocket", DISPATCH_QUEUE_SERIAL)
/// Used for setting protocols.
public init(url: NSURL, protocols: [String]? = nil) {
self.url = url
self.origin = url.absoluteString
writeQueue.maxConcurrentOperationCount = 1
optionalProtocols = protocols
}
/// Connect to the WebSocket server on a background thread.
public func connect() {
guard !isConnecting else { return }
didDisconnect = false
isConnecting = true
createHTTPRequest()
isConnecting = false
}
/**
Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed.
If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate.
If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate.
- Parameter forceTimeout: Maximum time to wait for the server to close the socket.
*/
public func disconnect(forceTimeout forceTimeout: NSTimeInterval? = nil) {
switch forceTimeout {
case .Some(let seconds) where seconds > 0:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), callbackQueue) { [weak self] in
self?.disconnectStream(nil)
}
fallthrough
case .None:
writeError(CloseCode.Normal.rawValue)
default:
disconnectStream(nil)
break
}
}
/**
Write a string to the websocket. This sends it as a text frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter str: The string to write.
- parameter completion: The (optional) completion handler.
*/
public func writeString(str: String, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame, writeCompletion: completion)
}
/**
Write binary data to the websocket. This sends it as a binary frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter data: The data to write.
- parameter completion: The (optional) completion handler.
*/
public func writeData(data: NSData, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .BinaryFrame, writeCompletion: completion)
}
// Write a ping to the websocket. This sends it as a control frame.
// Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
public func writePing(data: NSData, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .Ping, writeCompletion: completion)
}
/// Private method that starts the connection.
private func createHTTPRequest() {
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
url, kCFHTTPVersion1_1).takeRetainedValue()
var port = url.port
if port == nil {
if let scheme = url.scheme where ["wss", "https"].contains(scheme) {
port = 443
} else {
port = 80
}
}
addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
if let protocols = optionalProtocols {
addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joinWithSeparator(","))
}
addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey())
if let origin = origin {
addHeader(urlRequest, key: headerOriginName, val: origin)
}
addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
for (key,value) in headers {
addHeader(urlRequest, key: key, val: value)
}
if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) {
let serializedRequest = cfHTTPMessage.takeRetainedValue()
initStreamsWithData(serializedRequest, Int(port!))
}
}
/// Add a header to the CFHTTPMessage by using the NSString bridges to CFString.
private func addHeader(urlRequest: CFHTTPMessage, key: NSString, val: NSString) {
CFHTTPMessageSetHeaderFieldValue(urlRequest, key, val)
}
/// Generate a WebSocket key as needed in RFC.
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for _ in 0..<seed {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni))"
}
let data = key.dataUsingEncoding(NSUTF8StringEncoding)
let baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
return baseKey!
}
/// Start the stream connection and write the data to the output stream.
private func initStreamsWithData(data: NSData, _ port: Int) {
//higher level API we will cut over to at some point
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h: NSString = url.host!
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
guard let inStream = inputStream, let outStream = outputStream else { return }
inStream.delegate = self
outStream.delegate = self
if let scheme = url.scheme where ["wss", "https"].contains(scheme) {
inStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
outStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
} else {
certValidated = true //not a https session, so no need to check SSL pinning
}
if voipEnabled {
inStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
outStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
}
if selfSignedSSL {
let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool: false), kCFStreamSSLPeerName: kCFNull]
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
}
if let cipherSuites = self.enabledSSLCipherSuites {
if let sslContextIn = CFReadStreamCopyProperty(inputStream, kCFStreamPropertySSLContext) as! SSLContextRef?,
sslContextOut = CFWriteStreamCopyProperty(outputStream, kCFStreamPropertySSLContext) as! SSLContextRef? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
disconnectStream(error)
return
}
if resOut != errSecSuccess {
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
disconnectStream(error)
return
}
}
}
CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue)
CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue)
inStream.open()
outStream.open()
self.mutex.lock()
self.readyToWrite = true
self.mutex.unlock()
let bytes = UnsafePointer<UInt8>(data.bytes)
var out = timeout * 1000000 // wait 5 seconds before giving up
writeQueue.addOperationWithBlock { [weak self] in
while !outStream.hasSpaceAvailable {
usleep(100) // wait until the socket is ready
out -= 100
if out < 0 {
self?.cleanupStream()
self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2))
return
} else if outStream.streamError != nil {
return // disconnectStream will be called.
}
}
outStream.write(bytes, maxLength: data.length)
}
}
// Delegate for the stream methods. Processes incoming bytes.
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
if let sec = security where !certValidated && [.HasBytesAvailable, .HasSpaceAvailable].contains(eventCode) {
let possibleTrust: AnyObject? = aStream.propertyForKey(kCFStreamPropertySSLPeerTrust as String)
if let trust: AnyObject = possibleTrust {
let domain: AnyObject? = aStream.propertyForKey(kCFStreamSSLPeerName as String)
if sec.isValid(trust as! SecTrustRef, domain: domain as! String?) {
certValidated = true
} else {
let error = errorWithDetail("Invalid SSL certificate", code: 1)
disconnectStream(error)
return
}
}
}
if eventCode == .HasBytesAvailable {
if aStream == inputStream {
processInputStream()
}
} else if eventCode == .ErrorOccurred {
disconnectStream(aStream.streamError)
} else if eventCode == .EndEncountered {
disconnectStream(nil)
}
}
/// Disconnect the stream object and notifies the delegate.
private func disconnectStream(error: NSError?) {
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
cleanupStream()
doDisconnect(error)
}
private func cleanupStream() {
outputStream?.delegate = nil
inputStream?.delegate = nil
if let stream = inputStream {
CFReadStreamSetDispatchQueue(stream, nil)
stream.close()
}
if let stream = outputStream {
CFWriteStreamSetDispatchQueue(stream, nil)
stream.close()
}
outputStream = nil
inputStream = nil
}
/// Handles the incoming bytes and sending them to the proper processing method.
private func processInputStream() {
let buf = NSMutableData(capacity: BUFFER_MAX)
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
guard length > 0 else { return }
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(NSData(bytes: buffer, length: length))
if process {
dequeueInput()
}
}
/// Dequeue the incoming input so it is processed in order.
private func dequeueInput() {
while !inputQueue.isEmpty {
let data = inputQueue[0]
var work = data
if let fragBuffer = fragBuffer {
let combine = NSMutableData(data: fragBuffer)
combine.appendData(data)
work = combine
self.fragBuffer = nil
}
let buffer = UnsafePointer<UInt8>(work.bytes)
let length = work.length
if !connected {
processTCPHandshake(buffer, bufferLen: length)
} else {
processRawMessagesInBuffer(buffer, bufferLen: length)
}
inputQueue = inputQueue.filter{ $0 != data }
}
}
// Handle checking the initial connection status.
private func processTCPHandshake(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
let code = processHTTP(buffer, bufferLen: bufferLen)
switch code {
case 0:
connected = true
guard canDispatch else {return}
dispatch_async(callbackQueue) { [weak self] in
guard let s = self else { return }
s.onConnect?()
s.delegate?.websocketDidConnect(s)
s.notificationCenter.postNotificationName(WebsocketDidConnectNotification, object: self)
}
case -1:
fragBuffer = NSData(bytes: buffer, length: bufferLen)
break // do nothing, we are going to collect more data
default:
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
}
}
/// Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for i in 0..<bufferLen {
if buffer[i] == CRLFBytes[k] {
k += 1
if k == 3 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
let code = validateResponse(buffer, bufferLen: totalSize)
if code != 0 {
return code
}
totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize)
}
return 0 //success
}
return -1 // Was unable to find the full TCP header.
}
/// Validates the HTTP is a 101 as per the RFC spec.
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
let code = CFHTTPMessageGetResponseStatusCode(response)
if code != httpSwitchProtocolCode {
return code
}
if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {
let headers = cfHeaders.takeRetainedValue() as NSDictionary
if let acceptKey = headers[headerWSAcceptName] as? NSString {
if acceptKey.length > 0 {
return 0
}
}
}
return -1
}
///read a 16-bit big endian value from a buffer
private static func readUint16(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
}
///read a 64-bit big endian value from a buffer
private static func readUint64(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 {
var value = UInt64(0)
for i in 0...7 {
value = (value << 8) | UInt64(buffer[offset + i])
}
return value
}
/// Write a 16-bit big endian value to a buffer.
private static func writeUint16(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) {
buffer[offset + 0] = UInt8(value >> 8)
buffer[offset + 1] = UInt8(value & 0xff)
}
/// Write a 64-bit big endian value to a buffer.
private static func writeUint64(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) {
for i in 0...7 {
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
}
}
/// Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process.
@warn_unused_result
private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> {
let response = readStack.last
let baseAddress = buffer.baseAddress
let bufferLen = buffer.count
if response != nil && bufferLen < 2 {
fragBuffer = NSData(buffer: buffer)
return emptyBuffer
}
if let response = response where response.bytesLeft > 0 {
var len = response.bytesLeft
var extra = bufferLen - response.bytesLeft
if response.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
response.bytesLeft -= len
response.buffer?.appendData(NSData(bytes: baseAddress, length: len))
processResponse(response)
return buffer.fromOffset(bufferLen - extra)
} else {
let isFin = (FinMask & baseAddress[0])
let receivedOpcode = OpCode(rawValue: (OpCodeMask & baseAddress[0]))
let isMasked = (MaskMask & baseAddress[1])
let payloadLen = (PayloadLenMask & baseAddress[1])
var offset = 2
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .Pong {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode))
writeError(errCode)
return emptyBuffer
}
let isControlFrame = (receivedOpcode == .ConnectionClose || receivedOpcode == .Ping)
if !isControlFrame && (receivedOpcode != .BinaryFrame && receivedOpcode != .ContinueFrame &&
receivedOpcode != .TextFrame && receivedOpcode != .Pong) {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
writeError(errCode)
return emptyBuffer
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode))
writeError(errCode)
return emptyBuffer
}
if receivedOpcode == .ConnectionClose {
var code = CloseCode.Normal.rawValue
if payloadLen == 1 {
code = CloseCode.ProtocolError.rawValue
} else if payloadLen > 1 {
code = WebSocket.readUint16(baseAddress, offset: offset)
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
code = CloseCode.ProtocolError.rawValue
}
offset += 2
}
var closeReason = "connection closed by server"
if payloadLen > 2 {
let len = Int(payloadLen - 2)
if len > 0 {
let bytes = baseAddress + offset
if let customCloseReason = String(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding) {
closeReason = customCloseReason
} else {
code = CloseCode.ProtocolError.rawValue
}
}
}
doDisconnect(errorWithDetail(closeReason, code: code))
writeError(code)
return emptyBuffer
}
if isControlFrame && payloadLen > 125 {
writeError(CloseCode.ProtocolError.rawValue)
return emptyBuffer
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
dataLength = WebSocket.readUint64(baseAddress, offset: offset)
offset += sizeof(UInt64)
} else if dataLength == 126 {
dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset))
offset += sizeof(UInt16)
}
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
fragBuffer = NSData(bytes: baseAddress, length: bufferLen)
return emptyBuffer
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
let data: NSData
if len < 0 {
len = 0
data = NSData()
} else {
data = NSData(bytes: baseAddress+offset, length: Int(len))
}
if receivedOpcode == .Pong {
if canDispatch {
dispatch_async(callbackQueue) { [weak self] in
guard let s = self else { return }
s.onPong?()
s.pongDelegate?.websocketDidReceivePong(s)
}
}
return buffer.fromOffset(offset + Int(len))
}
var response = readStack.last
if isControlFrame {
response = nil // Don't append pings.
}
if isFin == 0 && receivedOpcode == .ContinueFrame && response == nil {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode))
writeError(errCode)
return emptyBuffer
}
var isNew = false
if response == nil {
if receivedOpcode == .ContinueFrame {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("first frame can't be a continue frame",
code: errCode))
writeError(errCode)
return emptyBuffer
}
isNew = true
response = WSResponse()
response!.code = receivedOpcode!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == .ContinueFrame {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame",
code: errCode))
writeError(errCode)
return emptyBuffer
}
response!.buffer!.appendData(data)
}
if let response = response {
response.bytesLeft -= Int(len)
response.frameCount += 1
response.isFin = isFin > 0 ? true : false
if isNew {
readStack.append(response)
}
processResponse(response)
}
let step = Int(offset + numericCast(len))
return buffer.fromOffset(step)
}
}
/// Process all messages in the buffer if possible.
private func processRawMessagesInBuffer(pointer: UnsafePointer<UInt8>, bufferLen: Int) {
var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen)
repeat {
buffer = processOneRawMessage(inBuffer: buffer)
} while buffer.count >= 2
if buffer.count > 0 {
fragBuffer = NSData(buffer: buffer)
}
}
/// Process the finished response of a buffer.
private func processResponse(response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .Ping {
let data = response.buffer! // local copy so it's not perverse for writing
dequeueWrite(data, code: OpCode.Pong)
} else if response.code == .TextFrame {
let str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
if str == nil {
writeError(CloseCode.Encoding.rawValue)
return false
}
if canDispatch {
dispatch_async(callbackQueue) { [weak self] in
guard let s = self else { return }
s.onText?(str! as String)
s.delegate?.websocketDidReceiveMessage(s, text: str! as String)
}
}
} else if response.code == .BinaryFrame {
if canDispatch {
let data = response.buffer! //local copy so it's not perverse for writing
dispatch_async(callbackQueue) { [weak self] in
guard let s = self else { return }
s.onData?(data)
s.delegate?.websocketDidReceiveData(s, data: data)
}
}
}
readStack.removeLast()
return true
}
return false
}
/// Create an error.
private func errorWithDetail(detail: String, code: UInt16) -> NSError {
var details = [String: String]()
details[NSLocalizedDescriptionKey] = detail
return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details)
}
/// Write a an error to the socket.
private func writeError(code: UInt16) {
let buf = NSMutableData(capacity: sizeof(UInt16))
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
WebSocket.writeUint16(buffer, offset: 0, value: code)
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
}
/// Used to write things to the stream.
private func dequeueWrite(data: NSData, code: OpCode, writeCompletion: (() -> ())? = nil) {
writeQueue.addOperationWithBlock { [weak self] in
//stream isn't ready, let's wait
guard let s = self else { return }
var offset = 2
let bytes = UnsafeMutablePointer<UInt8>(data.bytes)
let dataLength = data.length
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
let buffer = UnsafeMutablePointer<UInt8>(frame!.mutableBytes)
buffer[0] = s.FinMask | code.rawValue
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength))
offset += sizeof(UInt16)
} else {
buffer[1] = 127
WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength))
offset += sizeof(UInt64)
}
buffer[1] |= s.MaskMask
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
offset += sizeof(UInt32)
for i in 0..<dataLength {
buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)]
offset += 1
}
var total = 0
while true {
guard let outStream = s.outputStream else { break }
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
let len = outStream.write(writeBuffer, maxLength: offset-total)
if len < 0 {
var error: NSError?
if let streamError = outStream.streamError {
error = streamError
} else {
let errCode = InternalErrorCode.OutputStreamWriteError.rawValue
error = s.errorWithDetail("output stream error during write", code: errCode)
}
s.doDisconnect(error)
break
} else {
total += len
}
if total >= offset {
if let callbackQueue = self?.callbackQueue, callback = writeCompletion {
dispatch_async(callbackQueue) {
callback()
}
}
break
}
}
}
}
/// Used to preform the disconnect delegate.
private func doDisconnect(error: NSError?) {
guard !didDisconnect else { return }
didDisconnect = true
connected = false
guard canDispatch else {return}
dispatch_async(callbackQueue) { [weak self] in
guard let s = self else { return }
s.onDisconnect?(error)
s.delegate?.websocketDidDisconnect(s, error: error)
let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] }
s.notificationCenter.postNotificationName(WebsocketDidDisconnectNotification, object: self, userInfo: userInfo)
}
}
// MARK: - Deinit
deinit {
mutex.lock()
readyToWrite = false
mutex.unlock()
cleanupStream()
}
}
private extension NSData {
convenience init(buffer: UnsafeBufferPointer<UInt8>) {
self.init(bytes: buffer.baseAddress, length: buffer.count)
}
}
private extension UnsafeBufferPointer {
func fromOffset(offset: Int) -> UnsafeBufferPointer<Element> {
return UnsafeBufferPointer<Element>(start: baseAddress.advancedBy(offset), count: count - offset)
}
}
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
|
mit
|
7650671d118b266adf218177ed722c47
| 39.945763 | 226 | 0.58443 | 5.409315 | false | false | false | false |
devxoul/allkdic
|
Allkdic/Types/DictionaryType.swift
|
1
|
2942
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Suyeol Jeon (http://xoul.kr)
//
// 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 Cocoa
public enum DictionaryType: String {
case Naver = "Naver"
case Daum = "Daum"
case NaverMobile = "NaverMobile"
static var allTypes: [DictionaryType] {
return [.Naver, .Daum, .NaverMobile]
}
static var selectedDictionary: DictionaryType {
get {
if let name = UserDefaults.standard.string(forKey: UserDefaultsKey.selectedDictionaryName),
let dict = DictionaryType(name: name) {
return dict
}
self.selectedDictionary = .Naver
return .Naver
}
set {
let userDefaults = UserDefaults.standard
userDefaults.setValue(newValue.name, forKey: UserDefaultsKey.selectedDictionaryName)
userDefaults.synchronize()
}
}
public init?(name: String) {
self.init(rawValue: name)
}
public var name: String {
return self.rawValue
}
public var title: String {
switch self {
case .Naver: return gettext("naver_dictionary")
case .Daum: return gettext("daum_dictionary")
case .NaverMobile: return gettext("naver_mobile_dictionary")
}
}
public var URLString: String {
switch self {
case .Naver: return "http://endic.naver.com/popManager.nhn?m=miniPopMain"
case .Daum: return "http://small.dic.daum.net/"
case .NaverMobile: return "http://m.dic.naver.com/"
}
}
public var URLPattern: String {
switch self {
case .Naver: return "[a-z]+(?=\\.naver\\.com)"
case .Daum: return "(?<=[?&]dic=)[a-z]+"
case .NaverMobile: return "(?<=m\\.)[a-z]+(?=\\.naver\\.com)"
}
}
public var inputFocusingScript: String {
switch self {
case .Naver: return "ac_input.focus(); ac_input.select()"
case .Daum: return "q.focus(); q.select()"
case .NaverMobile: return "ac_input.focus(); ac_input.select()"
}
}
}
|
mit
|
07950fd93aa653842988d68413d35b36
| 30.297872 | 97 | 0.685928 | 3.896689 | false | false | false | false |
VBVMI/VerseByVerse-iOS
|
Pods/ParallaxView/Sources/Views/ParallaxView.swift
|
1
|
3550
|
//
// ParallaxCollectionViewCell.swift
//
// Created by Łukasz Śliwiński on 20/04/16.
// Copyright © 2016 Łukasz Śliwiński. All rights reserved.
//
import UIKit
open class ParallaxView: UIView, ParallaxableView {
// MARK: Properties
open var parallaxEffectOptions = ParallaxEffectOptions()
open var parallaxViewActions = ParallaxViewActions<ParallaxView>()
// MARK: Initialization
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
parallaxViewActions.setupUnfocusedState?(self)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
parallaxViewActions.setupUnfocusedState?(self)
}
internal func commonInit() {
if parallaxEffectOptions.glowContainerView == nil {
let view = UIView(frame: bounds)
addSubview(view)
parallaxEffectOptions.glowContainerView = view
}
}
// MARK: UIView
open override var canBecomeFocused : Bool {
return true
}
open override func layoutSubviews() {
super.layoutSubviews()
guard let glowEffectContainerView = parallaxEffectOptions.glowContainerView else { return }
if glowEffectContainerView != self, let glowSuperView = glowEffectContainerView.superview {
glowEffectContainerView.frame = glowSuperView.bounds
}
let maxSize = max(glowEffectContainerView.frame.width, glowEffectContainerView.frame.height)*1.7
// Make glow a litte bit bigger than the superview
guard let glowImageView = getGlowImageView() else { return }
glowImageView.frame = CGRect(x: 0, y: 0, width: maxSize, height: maxSize)
// Position in the middle and under the top edge of the superview
glowImageView.center = CGPoint(x: glowEffectContainerView.frame.width/2, y: -glowImageView.frame.height)
}
// MARK: UIResponder
// Generally, all responders which do custom touch handling should override all four of these methods.
// If you want to customize animations for press events do not forget to call super.
open override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
parallaxViewActions.animatePressIn?(self, presses, event)
super.pressesBegan(presses, with: event)
}
open override func pressesCancelled(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
parallaxViewActions.animatePressOut?(self, presses, event)
super.pressesCancelled(presses, with: event)
}
open override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
parallaxViewActions.animatePressOut?(self, presses, event)
super.pressesEnded(presses, with: event)
}
open override func pressesChanged(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
super.pressesChanged(presses, with: event)
}
// MARK: UIFocusEnvironment
open override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
super.didUpdateFocus(in: context, with: coordinator)
if self == context.nextFocusedView {
// Add parallax effect to focused cell
parallaxViewActions.becomeFocused?(self, context, coordinator)
} else if self == context.previouslyFocusedView {
// Remove parallax effect
parallaxViewActions.resignFocus?(self, context, coordinator)
}
}
}
|
mit
|
0dbd7fc1fe2874054eaee876cf60dc1d
| 32.424528 | 120 | 0.6884 | 4.787838 | false | false | false | false |
machelix/SwiftySideMenu
|
Demo/Timeline/Timeline/OptionsTableViewController.swift
|
5
|
3420
|
//
// OptionsTableViewController.swift
// Timeline
//
// Created by Hossam Ghareeb on 8/14/15.
// Copyright © 2015 Hossam Ghareeb. All rights reserved.
//
import UIKit
class OptionsTableViewController: UITableViewController {
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 didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 3
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// self.swiftySideMenu?.toggleSideMenu()
}
/*
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 NO 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.
}
*/
}
|
mit
|
15df73195acbb40add2290d9895276a6
| 33.19 | 157 | 0.68792 | 5.568404 | false | false | false | false |
taiphamtiki/TikiTool
|
TikiTool/Box/LoveViewController.swift
|
1
|
1770
|
//
// LoveViewController.swift
// TikiTool
//
// Created by ZickOne on 2/28/17.
// Copyright © 2017 ZickOne. All rights reserved.
//
import Foundation
import UIKit
import ChameleonFramework
import GDPerformanceView_Swift
import TTSegmentedControl
import RxCocoa
import RxSwift
class LoveViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var loveTableview: UITableView!
var loveViewModel = LoveViewModal()
override func viewDidLoad() {
self.loveTableview.register(UINib.init(nibName: "BoxItemCell", bundle: Bundle.main), forCellReuseIdentifier: "BoxItemCell")
self.loveViewModel.createListDBObssever().subscribe(onCompleted: {
self.loveTableview.reloadData()
}).addDisposableTo(DisposeBag())
self.loveTableview.tableFooterView = UIView()
}
override func viewDidAppear(_ animated: Bool) {
self.loveViewModel.createListDBObssever().subscribe(onCompleted: {
self.loveTableview.reloadData()
}).addDisposableTo(DisposeBag())
}
// MARK: - TableviewDataSourcess
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return loveViewModel.boxs.count
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let box = self.loveViewModel.boxs[indexPath.row]
let cell : BoxItemCell = tableView.dequeueReusableCell(withIdentifier: "BoxItemCell", for: indexPath) as! BoxItemCell
cell.favoritesBtn.isHidden = true
cell.boxNameTitle.text = box.name
return cell
}
}
|
mit
|
8d20844d0f1fd29730ba5c130082817c
| 31.759259 | 132 | 0.702092 | 4.807065 | false | false | false | false |
AnRanScheme/magiGlobe
|
magi/magiGlobe/magiGlobe/Classes/Tool/Extension/UIKit/UIWindow/UIWindow+Man.swift
|
1
|
918
|
//
// UIWindow+Man.swift
// swift-magic
//
// Created by 安然 on 17/2/15.
// Copyright © 2017年 安然. All rights reserved.
//
import UIKit
public extension UIWindow {
public func m_topMostController() -> UIViewController? {
var topController = self.rootViewController
while topController?.presentedViewController != nil {
topController = topController?.presentedViewController
}
return topController
}
public func m_currentViewController() -> UIViewController? {
var currentViewController = self.m_topMostController()
while currentViewController is UINavigationController && (currentViewController as? UINavigationController)?.topViewController != nil{
currentViewController = (currentViewController as? UINavigationController)?.topViewController
}
return currentViewController
}
}
|
mit
|
e8332f5add49c83c31d77fa0248775c9
| 28.258065 | 142 | 0.687982 | 5.88961 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.